rusackas commented on a change in pull request #17570:
URL: https://github.com/apache/superset/pull/17570#discussion_r765981621



##########
File path: superset-frontend/src/dashboard/components/PropertiesModal/index.tsx
##########
@@ -0,0 +1,603 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import React, { useCallback, useEffect, useState } from 'react';
+import { Form, Row, Col, Input } from 'src/common/components';
+import { FormItem } from 'src/components/Form';
+import jsonStringify from 'json-stringify-pretty-compact';
+import Button from 'src/components/Button';
+import { Select } from 'src/components';
+import rison from 'rison';
+import {
+  styled,
+  t,
+  SupersetClient,
+  getCategoricalSchemeRegistry,
+  ensureIsArray,
+} from '@superset-ui/core';
+
+import Modal from 'src/components/Modal';
+import { JsonEditor } from 'src/components/AsyncAceEditor';
+
+import ColorSchemeControlWrapper from 
'src/dashboard/components/ColorSchemeControlWrapper';
+import { getClientErrorObject } from 'src/utils/getClientErrorObject';
+import withToasts from 'src/components/MessageToasts/withToasts';
+import { FeatureFlag, isFeatureEnabled } from 'src/featureFlags';
+
+const StyledFormItem = styled(FormItem)`
+  margin-bottom: 0;
+`;
+
+const StyledJsonEditor = styled(JsonEditor)`
+  border-radius: ${({ theme }) => theme.borderRadius}px;
+  border: 1px solid ${({ theme }) => theme.colors.secondary.light2};
+`;
+
+type PropertiesModalProps = {
+  dashboardId: number;
+  dashboardTitle?: string;
+  dashboardInfo?: Record<string, any>;
+  show?: boolean;
+  onHide?: () => void;
+  colorScheme?: string;
+  setColorSchemeAndUnsavedChanges?: () => void;
+  onSubmit?: (params: Record<string, any>) => void;
+  addSuccessToast: (message: string) => void;
+  onlyApply?: boolean;
+};
+
+type Roles = { id: number; name: string }[];
+type Owners = {
+  id: number;
+  full_name?: string;
+  first_name?: string;
+  last_name?: string;
+}[];
+type DashboardInfo = {
+  id: number;
+  title: string;
+  slug: string;
+  certifiedBy: string;
+  certificationDetails: string;
+};
+
+const PropertiesModal = ({
+  addSuccessToast,
+  colorScheme: currentColorScheme,
+  dashboardId,
+  dashboardInfo: currentDashboardInfo,
+  dashboardTitle,
+  onHide = () => {},
+  onlyApply = false,
+  onSubmit = () => {},
+  show = false,
+}: PropertiesModalProps) => {
+  const [form] = Form.useForm();
+  const [isLoading, setIsLoading] = useState(false);
+  const [isAdvancedOpen, setIsAdvancedOpen] = useState(false);
+  const [colorScheme, setColorScheme] = useState(currentColorScheme);
+  const [jsonMetadata, setJsonMetadata] = useState('');
+  const [dashboardInfo, setDashboardInfo] = useState<DashboardInfo>();
+  const [owners, setOwners] = useState<Owners>([]);
+  const [roles, setRoles] = useState<Roles>([]);
+  const saveLabel = onlyApply ? t('Apply') : t('Save');
+
+  const handleErrorResponse = async (response: Response) => {
+    const { error, statusText, message } = await 
getClientErrorObject(response);
+    let errorText = error || statusText || t('An error has occurred');
+    if (typeof message === 'object' && 'json_metadata' in message) {
+      errorText = (message as { json_metadata: string }).json_metadata;
+    } else if (typeof message === 'string') {
+      errorText = message;
+
+      if (message === 'Forbidden') {
+        errorText = t('You do not have permission to edit this dashboard');
+      }
+    }
+
+    Modal.error({
+      title: 'Error',
+      content: errorText,
+      okButtonProps: { danger: true, className: 'btn-danger' },
+    });
+  };
+
+  const loadAccessOptions = useCallback(
+    (accessType = 'owners', input = '', page: number, pageSize: number) => {
+      const query = rison.encode({
+        filter: input,
+        page,
+        page_size: pageSize,
+      });
+      return SupersetClient.get({
+        endpoint: `/api/v1/dashboard/related/${accessType}?q=${query}`,
+      }).then(response => ({
+        data: response.json.result.map(
+          (item: { value: number; text: string }) => ({
+            value: item.value,
+            label: item.text,
+          }),
+        ),
+        totalCount: response.json.count,
+      }));
+    },
+    [],
+  );
+
+  const handleDashboardData = useCallback(
+    dashboardData => {
+      const {
+        id,
+        dashboard_title,
+        slug,
+        certified_by,
+        certification_details,
+        owners,
+        roles,
+        metadata,
+      } = dashboardData;
+      const dashboardInfo = {
+        id,
+        title: dashboard_title,
+        slug: slug || '',
+        certifiedBy: certified_by || '',
+        certificationDetails: certification_details || '',
+      };
+
+      form.setFieldsValue(dashboardInfo);
+      setDashboardInfo(dashboardInfo);
+      setJsonMetadata(metadata ? jsonStringify(metadata) : '');
+      setOwners(owners);
+      setRoles(roles);
+      setColorScheme(metadata.color_scheme);
+    },
+    [form],
+  );
+
+  const fetchDashboardDetails = useCallback(() => {
+    setIsLoading(true);
+    // We fetch the dashboard details because not all code
+    // that renders this component have all the values we need.
+    // At some point when we have a more consistent frontend
+    // datamodel, the dashboard could probably just be passed as a prop.
+    SupersetClient.get({
+      endpoint: `/api/v1/dashboard/${dashboardId}`,
+    }).then(response => {
+      const dashboard = response.json.result;
+      const jsonMetadataObj = dashboard.json_metadata?.length
+        ? JSON.parse(dashboard.json_metadata)
+        : {};
+
+      handleDashboardData({
+        ...dashboard,
+        metadata: jsonMetadataObj,
+      });
+
+      setIsLoading(false);
+    }, handleErrorResponse);
+  }, [dashboardId, handleDashboardData]);
+
+  const getJsonMetadata = () => {
+    try {
+      const jsonMetadataObj = jsonMetadata?.length
+        ? JSON.parse(jsonMetadata)
+        : {};
+      return jsonMetadataObj;
+    } catch (_) {
+      return {};
+    }
+  };
+
+  const handleOnChangeOwners = (owners: { value: number; label: string }[]) => 
{
+    const parsedOwners: Owners = ensureIsArray(owners).map(o => ({
+      id: o.value,
+      full_name: o.label,
+    }));
+    setOwners(parsedOwners);
+  };
+
+  const handleOnChangeRoles = (roles: { value: number; label: string }[]) => {
+    const parsedRoles: Roles = ensureIsArray(roles).map(r => ({
+      id: r.value,
+      name: r.label,
+    }));
+    setRoles(parsedRoles);
+  };
+
+  const handleOwnersSelectValue = () => {
+    const parsedOwners = (owners || []).map(
+      (owner: {
+        id: number;
+        first_name?: string;
+        last_name?: string;
+        full_name?: string;
+      }) => ({
+        value: owner.id,
+        label: owner.full_name || `${owner.first_name} ${owner.last_name}`,
+      }),
+    );
+    return parsedOwners;
+  };
+
+  const handleRolesSelectValue = () => {
+    const parsedRoles = (roles || []).map(
+      (role: { id: number; name: string }) => ({
+        value: role.id,
+        label: `${role.name}`,
+      }),
+    );
+    return parsedRoles;
+  };
+
+  const onColorSchemeChange = (
+    colorScheme?: string,
+    { updateMetadata = true } = {},
+  ) => {
+    // check that color_scheme is valid
+    const colorChoices = getCategoricalSchemeRegistry().keys();
+    const jsonMetadataObj = getJsonMetadata();
+
+    // only fire if the color_scheme is present and invalid
+    if (colorScheme && !colorChoices.includes(colorScheme)) {
+      Modal.error({
+        title: 'Error',
+        content: t('A valid color scheme is required'),
+        okButtonProps: { danger: true, className: 'btn-danger' },
+      });
+      throw new Error('A valid color scheme is required');

Review comment:
       ```suggestion
         throw new Error(t('A valid color scheme is required'));
   ```
   Could use a `t()` here. Not blocking the PR for this!




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to