michael-s-molina commented on code in PR #37298:
URL: https://github.com/apache/superset/pull/37298#discussion_r2738022284


##########
superset-frontend/src/components/DatabaseSelector/index.tsx:
##########
@@ -131,8 +181,10 @@ export function DatabaseSelector({
   schema,
   readOnly = false,
   sqlLabMode = false,
+  onOpenModal,
 }: DatabaseSelectorProps) {
   const showCatalogSelector = !!db?.allow_multi_catalog;
+  console.log('db', db, showCatalogSelector);

Review Comment:
   ```suggestion
   ```



##########
superset-frontend/src/SqlLab/components/SqlEditorLeftBar/index.tsx:
##########
@@ -16,154 +16,175 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { useCallback, useMemo, useState } from 'react';
-import { shallowEqual, useDispatch, useSelector } from 'react-redux';
+import { useCallback, useState } from 'react';
+import { useDispatch } from 'react-redux';
 
-import { SqlLabRootState, Table } from 'src/SqlLab/types';
+import { resetState } from 'src/SqlLab/actions/sqlLab';
 import {
-  addTable,
-  removeTables,
-  collapseTable,
-  expandTable,
-  resetState,
-} from 'src/SqlLab/actions/sqlLab';
-import { Button, EmptyState, Icons } from '@superset-ui/core/components';
+  Button,
+  EmptyState,
+  Icons,
+  Popconfirm,
+} from '@superset-ui/core/components';
 import { t } from '@apache-superset/core';
 import { styled, css } from '@apache-superset/core/ui';
-import { TableSelectorMultiple } from 'src/components/TableSelector';
-import useQueryEditor from 'src/SqlLab/hooks/useQueryEditor';
-import { noop } from 'lodash';
-import TableElement from '../TableElement';
+import type { SchemaOption, CatalogOption } from 'src/hooks/apiResources';
+import { DatabaseSelector, type DatabaseObject } from 'src/components';
+
 import useDatabaseSelector from '../SqlEditorTopBar/useDatabaseSelector';
+import TableExploreTree from '../TableExploreTree';
 
 export interface SqlEditorLeftBarProps {
   queryEditorId: string;
 }
 
-const StyledScrollbarContainer = styled.div`
-  flex: 1 1 auto;
-  overflow: auto;
-`;
-
 const LeftBarStyles = styled.div`
+  display: flex;
+  flex-direction: column;
+  gap: ${({ theme }) => theme.sizeUnit * 2}px;
+
   ${({ theme }) => css`
     height: 100%;
     display: flex;
     flex-direction: column;
 
     .divider {
       border-bottom: 1px solid ${theme.colorSplit};
-      margin: ${theme.sizeUnit * 4}px 0;
+      margin: ${theme.sizeUnit * 1}px 0;
     }
   `}
 `;
 
+const StyledDivider = styled.div`
+  border-bottom: 1px solid ${({ theme }) => theme.colorSplit};
+  margin: 0 -${({ theme }) => theme.sizeUnit * 2.5}px 0;
+`;
+
 const SqlEditorLeftBar = ({ queryEditorId }: SqlEditorLeftBarProps) => {
-  const { db: userSelectedDb, ...dbSelectorProps } =
-    useDatabaseSelector(queryEditorId);
-  const allSelectedTables = useSelector<SqlLabRootState, Table[]>(
-    ({ sqlLab }) =>
-      sqlLab.tables.filter(table => table.queryEditorId === queryEditorId),
-    shallowEqual,
-  );
+  const dbSelectorProps = useDatabaseSelector(queryEditorId);
+  const { db, catalog, schema, onDbChange, onCatalogChange, onSchemaChange } =
+    dbSelectorProps;
+
   const dispatch = useDispatch();
-  const queryEditor = useQueryEditor(queryEditorId, [
-    'dbId',
-    'catalog',
-    'schema',
-    'tabViewId',
-  ]);
-  const [_emptyResultsWithSearch, setEmptyResultsWithSearch] = useState(false);
-  const { dbId, schema } = queryEditor;
-  const tables = useMemo(
-    () =>
-      allSelectedTables.filter(
-        table => table.dbId === dbId && table.schema === schema,
-      ),
-    [allSelectedTables, dbId, schema],
-  );
+  const shouldShowReset = window.location.search === '?reset=1';
 
-  noop(_emptyResultsWithSearch); // This is to avoid unused variable warning, 
can be removed if not needed
+  // Modal state for Database/Catalog/Schema selector
+  const [selectorModalOpen, setSelectorModalOpen] = useState(false);
+  const [modalDb, setModalDb] = useState<DatabaseObject | 
undefined>(undefined);
+  const [modalCatalog, setModalCatalog] = useState<
+    CatalogOption | null | undefined
+  >(undefined);
+  const [modalSchema, setModalSchema] = useState<SchemaOption | undefined>(
+    undefined,
+  );
 
-  const onEmptyResults = useCallback((searchText?: string) => {
-    setEmptyResultsWithSearch(!!searchText);
+  const openSelectorModal = useCallback(() => {
+    setModalDb(db ?? undefined);
+    setModalCatalog(
+      catalog ? { label: catalog, value: catalog, title: catalog } : undefined,
+    );
+    setModalSchema(
+      schema ? { label: schema, value: schema, title: schema } : undefined,
+    );
+    setSelectorModalOpen(true);
+  }, [db, catalog, schema]);
+
+  const closeSelectorModal = useCallback(() => {
+    setSelectorModalOpen(false);
   }, []);
 
-  const selectedTableNames = useMemo(
-    () => tables?.map(table => table.name) || [],
-    [tables],
-  );
-
-  const onTablesChange = (
-    tableNames: string[],
-    catalogName: string | null,
-    schemaName: string,
-  ) => {
-    if (!schemaName) {
-      return;
+  const handleModalOk = useCallback(() => {
+    if (modalDb && modalDb.id !== db?.id) {
+      onDbChange?.(modalDb);
     }
-
-    const currentTables = [...tables];
-    const tablesToAdd = tableNames.filter(name => {
-      const index = currentTables.findIndex(table => table.name === name);
-      if (index >= 0) {
-        currentTables.splice(index, 1);
-        return false;
-      }
-
-      return true;
-    });
-
-    tablesToAdd.forEach(tableName => {
-      dispatch(addTable(queryEditor, tableName, catalogName, schemaName));
-    });
-
-    dispatch(removeTables(currentTables));
-  };
-
-  const onToggleTable = (updatedTables: string[]) => {
-    tables.forEach(table => {
-      if (!updatedTables.includes(table.id.toString()) && table.expanded) {
-        dispatch(collapseTable(table));
-      } else if (
-        updatedTables.includes(table.id.toString()) &&
-        !table.expanded
-      ) {
-        dispatch(expandTable(table));
-      }
-    });
-  };
-
-  const shouldShowReset = window.location.search === '?reset=1';
+    if (modalCatalog?.value !== catalog) {
+      onCatalogChange?.(modalCatalog?.value);
+    }
+    if (modalSchema?.value !== schema) {
+      onSchemaChange?.(modalSchema?.value ?? '');
+    }
+    setSelectorModalOpen(false);
+  }, [
+    modalDb,
+    modalCatalog,
+    modalSchema,
+    db,
+    catalog,
+    schema,
+    onDbChange,
+    onCatalogChange,
+    onSchemaChange,
+  ]);
 
   const handleResetState = useCallback(() => {
     dispatch(resetState());
   }, [dispatch]);
 
-  return (
-    <LeftBarStyles data-test="sql-editor-left-bar">
-      <TableSelectorMultiple
-        {...dbSelectorProps}
-        onEmptyResults={onEmptyResults}
+  const popconfirmDescription = (
+    <div
+      data-test="DatabaseSelector"
+      css={css`
+        min-width: 500px;
+      `}
+    >
+      <DatabaseSelector
+        key={modalDb ? modalDb.id : 'no-db'}
+        db={modalDb}
         emptyState={<EmptyState />}
-        database={userSelectedDb}
-        onTableSelectChange={onTablesChange}
-        tableValue={selectedTableNames}
-        sqlLabMode
+        getDbList={dbSelectorProps.getDbList}
+        handleError={dbSelectorProps.handleError}
+        onDbChange={setModalDb}
+        onCatalogChange={cat =>
+          setModalCatalog(
+            cat ? { label: cat, value: cat, title: cat } : undefined,
+          )
+        }
+        catalog={modalCatalog?.value}
+        onSchemaChange={sch =>
+          setModalSchema(
+            sch ? { label: sch, value: sch, title: sch } : undefined,
+          )
+        }
+        schema={modalSchema?.value}
+        sqlLabMode={false}
       />
-      <div className="divider" />
-      <StyledScrollbarContainer>
-        {tables.map(table => (
-          <TableElement
-            table={table}
-            key={table.id}
-            activeKey={tables
-              .filter(({ expanded }) => expanded)
-              .map(({ id }) => id)}
-            onChange={onToggleTable}
+    </div>
+  );
+
+  return (
+    <LeftBarStyles data-test="sql-editor-left-bar">
+      <Popconfirm

Review Comment:
   It may be better to use `Popover` in this case because the user is making a 
selection rather than confirming an action.  Using the description for complex 
form content is not typical.



##########
superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx:
##########
@@ -0,0 +1,736 @@
+/**
+ * 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 {
+  useMemo,
+  useCallback,
+  useState,
+  useRef,
+  type ChangeEvent,
+} from 'react';
+import { useSelector, useDispatch, shallowEqual } from 'react-redux';
+import { css, styled, t } from '@apache-superset/core';
+import AutoSizer from 'react-virtualized-auto-sizer';
+// Due to performance issues with the virtual list in the existing Ant Design 
(antd)-based tree view,
+// it has been replaced with react-arborist solution.
+import { Tree, TreeApi, NodeRendererProps, NodeApi } from 'react-arborist';
+import {
+  Icons,
+  Skeleton,
+  Input,
+  Tooltip,
+  Empty,
+  Typography,
+  Button,
+} from '@superset-ui/core/components';
+import RefreshLabel from '@superset-ui/core/components/RefreshLabel';
+import type { SqlLabRootState } from 'src/SqlLab/types';
+import ColumnElement, {
+  type ColumnKeyTypeType,
+} from 'src/SqlLab/components/ColumnElement';
+import {
+  Table,
+  TableMetaData,
+  useSchemas,
+  useLazyTablesQuery,
+  useLazyTableMetadataQuery,
+  useLazyTableExtendedMetadataQuery,
+} from 'src/hooks/apiResources';
+import useQueryEditor from 'src/SqlLab/hooks/useQueryEditor';
+import { addTable } from 'src/SqlLab/actions/sqlLab';
+import IconButton from 'src/dashboard/components/IconButton';
+import PanelToolbar from 'src/components/PanelToolbar';
+import { ViewContribution } from 'src/SqlLab/contributions';
+
+type Props = {
+  queryEditorId: string;
+};
+
+interface TreeNodeData {
+  id: string;
+  name: string;
+  type: 'schema' | 'table' | 'column' | 'empty';
+  tableType?: string;
+  columnData?: {
+    name: string;
+    keys?: { type: ColumnKeyTypeType }[];
+    type: string;
+  };
+  children?: TreeNodeData[];
+  disableCheckbox?: boolean;
+}
+
+const EMPTY_NODE_ID_PREFIX = 'empty:';
+
+const StyledTreeContainer = styled.div`
+  flex: 1 1 auto;
+  .tree-node {
+    display: flex;
+    align-items: center;
+    padding: 0 ${({ theme }) => theme.sizeUnit}px;
+    position: relative;
+    cursor: pointer;
+
+    &:hover {
+      background-color: ${({ theme }) => theme.colorBgTextHover};
+
+      .side-action-container {
+        opacity: 1;
+      }
+    }
+
+    &[data-selected='true'] {
+      background-color: ${({ theme }) => theme.colorBgTextActive};
+
+      .side-action-container {
+        opacity: 1;
+      }
+    }
+  }
+
+  .tree-node-icon {
+    margin-right: ${({ theme }) => theme.sizeUnit}px;
+    display: flex;
+    align-items: center;
+    gap: ${({ theme }) => theme.sizeUnit}px;
+  }
+
+  .tree-node-title {
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    flex: 1;
+  }
+
+  .highlighted {
+    background-color: ${({ theme }) => theme.colorWarningBg};
+    font-weight: bold;
+  }
+
+  .side-action-container {
+    opacity: 0;
+    position: absolute;
+    right: ${({ theme }) => theme.sizeUnit * 1.5}px;
+    top: 50%;
+    transform: translateY(-50%);
+    z-index: ${({ theme }) => theme.zIndexPopupBase};
+  }
+`;
+
+const StyledColumnNode = styled.div`
+  & > .ant-flex {
+    flex: 1;
+    margin-right: ${({ theme }) => theme.sizeUnit * 1.5}px;
+    cursor: default;
+  }
+`;
+
+const ROW_HEIGHT = 28;
+
+const getOpacity = (disableCheckbox: boolean | undefined) => ({
+  opacity: disableCheckbox ? 0.6 : 1,
+});
+
+const highlightText = (text: string, keyword: string): React.ReactNode => {
+  if (!keyword) {
+    return text;
+  }
+
+  const lowerText = text.toLowerCase();
+  const lowerKeyword = keyword.toLowerCase();
+  const index = lowerText.indexOf(lowerKeyword);
+
+  if (index === -1) {
+    return text;
+  }
+
+  const beforeStr = text.substring(0, index);
+  const matchStr = text.substring(index, index + keyword.length);
+  const afterStr = text.slice(index + keyword.length);
+
+  return (
+    <>
+      {beforeStr}
+      <span className="highlighted">{matchStr}</span>
+      {afterStr}
+    </>
+  );
+};
+
+const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {

Review Comment:
   Maybe break this component (736 lines) into smaller sub-components (e.g., 
`TreeNodeRenderer`, `useTreeData` hook)?



##########
superset-frontend/packages/superset-ui-core/src/components/Segmented/index.tsx:
##########
@@ -0,0 +1,22 @@
+/**
+ * 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 type { SegmentedProps } from './types';
+
+export { Segmented } from 'antd';

Review Comment:
   It looks like this component is not being used anywhere and it's safe to 
remove?



##########
superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx:
##########
@@ -0,0 +1,736 @@
+/**
+ * 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 {
+  useMemo,
+  useCallback,
+  useState,
+  useRef,
+  type ChangeEvent,
+} from 'react';
+import { useSelector, useDispatch, shallowEqual } from 'react-redux';
+import { css, styled, t } from '@apache-superset/core';
+import AutoSizer from 'react-virtualized-auto-sizer';
+// Due to performance issues with the virtual list in the existing Ant Design 
(antd)-based tree view,
+// it has been replaced with react-arborist solution.
+import { Tree, TreeApi, NodeRendererProps, NodeApi } from 'react-arborist';
+import {
+  Icons,
+  Skeleton,
+  Input,
+  Tooltip,
+  Empty,
+  Typography,
+  Button,
+} from '@superset-ui/core/components';
+import RefreshLabel from '@superset-ui/core/components/RefreshLabel';
+import type { SqlLabRootState } from 'src/SqlLab/types';
+import ColumnElement, {
+  type ColumnKeyTypeType,
+} from 'src/SqlLab/components/ColumnElement';
+import {
+  Table,
+  TableMetaData,
+  useSchemas,
+  useLazyTablesQuery,
+  useLazyTableMetadataQuery,
+  useLazyTableExtendedMetadataQuery,
+} from 'src/hooks/apiResources';
+import useQueryEditor from 'src/SqlLab/hooks/useQueryEditor';
+import { addTable } from 'src/SqlLab/actions/sqlLab';
+import IconButton from 'src/dashboard/components/IconButton';
+import PanelToolbar from 'src/components/PanelToolbar';
+import { ViewContribution } from 'src/SqlLab/contributions';
+
+type Props = {
+  queryEditorId: string;
+};
+
+interface TreeNodeData {
+  id: string;
+  name: string;
+  type: 'schema' | 'table' | 'column' | 'empty';
+  tableType?: string;
+  columnData?: {
+    name: string;
+    keys?: { type: ColumnKeyTypeType }[];
+    type: string;
+  };
+  children?: TreeNodeData[];
+  disableCheckbox?: boolean;
+}
+
+const EMPTY_NODE_ID_PREFIX = 'empty:';
+
+const StyledTreeContainer = styled.div`
+  flex: 1 1 auto;
+  .tree-node {
+    display: flex;
+    align-items: center;
+    padding: 0 ${({ theme }) => theme.sizeUnit}px;
+    position: relative;
+    cursor: pointer;
+
+    &:hover {
+      background-color: ${({ theme }) => theme.colorBgTextHover};
+
+      .side-action-container {
+        opacity: 1;
+      }
+    }
+
+    &[data-selected='true'] {
+      background-color: ${({ theme }) => theme.colorBgTextActive};
+
+      .side-action-container {
+        opacity: 1;
+      }
+    }
+  }
+
+  .tree-node-icon {
+    margin-right: ${({ theme }) => theme.sizeUnit}px;
+    display: flex;
+    align-items: center;
+    gap: ${({ theme }) => theme.sizeUnit}px;
+  }
+
+  .tree-node-title {
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    flex: 1;
+  }
+
+  .highlighted {
+    background-color: ${({ theme }) => theme.colorWarningBg};
+    font-weight: bold;
+  }
+
+  .side-action-container {
+    opacity: 0;
+    position: absolute;
+    right: ${({ theme }) => theme.sizeUnit * 1.5}px;
+    top: 50%;
+    transform: translateY(-50%);
+    z-index: ${({ theme }) => theme.zIndexPopupBase};
+  }
+`;
+
+const StyledColumnNode = styled.div`
+  & > .ant-flex {
+    flex: 1;
+    margin-right: ${({ theme }) => theme.sizeUnit * 1.5}px;
+    cursor: default;
+  }
+`;
+
+const ROW_HEIGHT = 28;
+
+const getOpacity = (disableCheckbox: boolean | undefined) => ({
+  opacity: disableCheckbox ? 0.6 : 1,
+});
+
+const highlightText = (text: string, keyword: string): React.ReactNode => {
+  if (!keyword) {
+    return text;
+  }
+
+  const lowerText = text.toLowerCase();
+  const lowerKeyword = keyword.toLowerCase();
+  const index = lowerText.indexOf(lowerKeyword);
+
+  if (index === -1) {
+    return text;
+  }
+
+  const beforeStr = text.substring(0, index);
+  const matchStr = text.substring(index, index + keyword.length);
+  const afterStr = text.slice(index + keyword.length);
+
+  return (
+    <>
+      {beforeStr}
+      <span className="highlighted">{matchStr}</span>
+      {afterStr}
+    </>
+  );
+};
+
+const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
+  const dispatch = useDispatch();
+  const treeRef = useRef<TreeApi<TreeNodeData>>(null);
+  const tables = useSelector(
+    ({ sqlLab }: SqlLabRootState) => sqlLab.tables,
+    shallowEqual,
+  );
+  const queryEditor = useQueryEditor(queryEditorId, [
+    'dbId',
+    'schema',
+    'catalog',
+  ]);
+  const { dbId, catalog, schema: selectedSchema } = queryEditor;
+  const pinnedTables = useMemo(
+    () =>
+      Object.fromEntries(
+        tables.map(({ queryEditorId, dbId, schema, name, persistData }) => [
+          queryEditor.id === queryEditorId ? `${dbId}:${schema}:${name}` : '',
+          persistData,
+        ]),
+      ),
+    [tables, queryEditor.id],
+  );
+  const {
+    currentData: schemaData,
+    isFetching,
+    refetch,
+  } = useSchemas({ dbId, catalog: catalog || undefined });
+  const [tableData, setTableData] = useState<
+    Record<string, { options: Table[] }>
+  >({});
+  const [tableSchemaData, setTableSchemaData] = useState<
+    Record<string, TableMetaData>
+  >({});
+  const [fetchLazyTables] = useLazyTablesQuery();
+  const [fetchTableMetadata] = useLazyTableMetadataQuery();
+  const [fetchTableExtendedMetadata] = useLazyTableExtendedMetadataQuery();
+
+  const handlePinTable = useCallback(
+    (tableName: string, schemaName: string, catalogName: string | null) =>
+      dispatch(addTable(queryEditor, tableName, catalogName, schemaName)),
+    [dispatch, queryEditor],
+  );
+  const [searchTerm, setSearchTerm] = useState('');
+  const handleSearchChange = useCallback(
+    ({ target }: ChangeEvent<HTMLInputElement>) => setSearchTerm(target.value),
+    [],
+  );
+
+  // Track manually opened nodes (not auto-expanded by search)
+  const [manuallyOpenedNodes, setManuallyOpenedNodes] = useState<
+    Record<string, boolean>
+  >({});
+
+  // Track nodes that are currently loading
+  const [loadingNodes, setLoadingNodes] = useState<Record<string, 
boolean>>({});
+
+  // Version counter to force tree re-render when data changes during search
+  const [dataVersion, setDataVersion] = useState(0);

Review Comment:
   Maybe consolidate multiple `useState` calls into `useReducer`?



-- 
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