The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GDGT 1533 improve discoverability of python library in transforms UI (#68523)
Egor Grushin761a7cf01ef7
diff --git a/e2e/test/scenarios/data-studio/transforms.cy.spec.ts b/e2e/test/scenarios/data-studio/transforms.cy.spec.tsindex ed9c384fb49..07d08a168e6 100644--- a/e2e/test/scenarios/data-studio/transforms.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/transforms.cy.spec.ts@@ -2284,6 +2284,41 @@ LIMIT},);+ it(+ "should navigate to the common library when clicking 'common' in an import statement",+ { tags: ["@python"] },+ () => {+ visitTransformListPage();+ cy.button("Create a transform").click();+ H.popover().findByText("Python script").click();+ cy.get(".cm-clickable-token").should("be.visible").click();+ H.modal().button("Discard changes").click();+ cy.url().should("include", "/data-studio/transforms/library/common.py");+ cy.findByTestId("python-library-header").should("be.visible");+ },+ );++ it(+ "should open the common library in a new tab when cmd-clicking 'common' in an import statement",+ { tags: ["@python"] },+ () => {+ visitTransformListPage();+ cy.window().then((win) => {+ cy.stub(win, "open").as("windowOpen");+ });+ cy.button("Create a transform").click();+ H.popover().findByText("Python script").click();+ cy.get(".cm-clickable-token")+ .should("be.visible")+ .click({ metaKey: true });++ cy.get("@windowOpen").should(+ "have.been.calledWithMatch",+ "/data-studio/transforms/library/common.py",+ );+ },+ );+function visitCommonLibrary(path = "common.py") {cy.visit(`/data-studio/transforms/library/${path}`);}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonEditor/PythonEditor.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonEditor/PythonEditor.tsxindex 350b42c0f7e..fb130ead540 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonEditor/PythonEditor.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonEditor/PythonEditor.tsx@@ -1,4 +1,6 @@+import type { Extension } from "@uiw/react-codemirror";import cx from "classnames";+import _ from "underscore";import { CodeEditor } from "metabase/common/components/CodeEditor";@@ -12,6 +14,7 @@ export function PythonEditor({withPandasCompletions,className,readOnly,+ extensions: externalExtensions,...rest}: {value: string;@@ -21,7 +24,13 @@ export function PythonEditor({withPandasCompletions?: boolean;className?: string;readOnly?: boolean;+ extensions?: Extension[];}) {+ const extensions = _.compact([+ ...(externalExtensions ?? []),+ withPandasCompletions ? completion : undefined,+ ]);+return (<CodeEditorclassName={cx(S.editor, className)}@@ -29,7 +38,7 @@ export function PythonEditor({proposedValue={proposedValue}onChange={onChange}language="python"- extensions={withPandasCompletions ? completion : undefined}+ extensions={extensions}readOnly={readOnly}{...rest}/>diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsxindex 17dec3874eb..cc1437f9fb8 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx@@ -1,14 +1,20 @@-import { useState } from "react";+import { useCallback, useMemo, useState } from "react";import { ResizableBox } from "react-resizable";+import { push } from "react-router-redux";import { useWindowSize } from "react-use";import { t } from "ttag";+import { clickableTokens } from "metabase/common/components/CodeMirror";+import { useDispatch } from "metabase/lib/redux";+import * as Urls from "metabase/lib/urls";import RunButtonWithTooltip from "metabase/query_builder/components/RunButtonWithTooltip";import { Button, Flex, Icon, Stack, Tooltip } from "metabase/ui";+import { SHARED_LIB_IMPORT_PATH } from "metabase-enterprise/transforms-python/constants";import { PythonEditor } from "../../PythonEditor";import { ResizableBoxHandle } from "./ResizableBoxHandle";+import { createPythonImportTokenLocator } from "./utils";type PythonEditorBodyProps = {source: string;@@ -46,6 +52,33 @@ export function PythonEditorBody({}: PythonEditorBodyProps) {const [isResizing, setIsResizing] = useState(false);const editorHeight = useInitialEditorHeight(isEditMode);+ const dispatch = useDispatch();++ const navigateToCommonLibrary = useCallback(+ (e: MouseEvent) => {+ const openInNewTab = e.metaKey || e.ctrlKey || e.button === 1;+ const href = Urls.transformPythonLibrary({+ path: SHARED_LIB_IMPORT_PATH,+ });+ if (openInNewTab) {+ window.open(href, "_blank", "noopener,noreferrer");+ } else {+ dispatch(push(href));+ }+ },+ [dispatch],+ );++ const clickableTokensExtension = useMemo(+ () =>+ clickableTokens([+ {+ tokenLocator: createPythonImportTokenLocator("common"),+ onClick: (e) => navigateToCommonLibrary(e),+ },+ ]),+ [navigateToCommonLibrary],+ );return (<ResizableBox@@ -64,6 +97,7 @@ export function PythonEditorBody({onChange={onChange}withPandasCompletionsreadOnly={!isEditMode}+ extensions={[clickableTokensExtension]}data-testid="python-editor"/>diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/utils.ts b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/utils.tsindex 577de6df205..844869604df 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/utils.ts@@ -1,3 +1,6 @@+import type { EditorView } from "@codemirror/view";+import type { SyntaxNodeRef } from "@lezer/common";+export function insertImport(source: string, path: string) {const lines = source.split("\n");@@ -31,3 +34,23 @@ export function hasImport(source: string, path: string) {const regex = libImportRegex(path);return regex.test(source);}++export const createPythonImportTokenLocator =+ (moduleName: string) =>+ (view: EditorView, node: SyntaxNodeRef): boolean => {+ if (node.type.name !== "VariableName") {+ return false;+ }+ const variableName = view.state.doc.sliceString(node.from, node.to);+ if (variableName !== moduleName) {+ return false;+ }+ let cur: SyntaxNodeRef | null = node;+ while (cur) {+ if (cur.type.name === "ImportStatement") {+ return true;+ }+ cur = cur.node.parent;+ }+ return false;+ };diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformListPage/TransformListPage.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformListPage/TransformListPage.tsxindex 4b9667721a4..5a166ffd2d9 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformListPage/TransformListPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformListPage/TransformListPage.tsx@@ -16,7 +16,6 @@ import type { ColorName } from "metabase/lib/colors/types";import * as Urls from "metabase/lib/urls";import { type NamedUser, getUserName } from "metabase/lib/user";import { PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";-import type { TreeTableColumnDef } from "metabase/ui";import {Avatar,Card,@@ -26,6 +25,7 @@ import {Stack,TextInput,TreeTable,+ type TreeTableColumnDef,TreeTableSkeleton,useTreeTableInstance,} from "metabase/ui";diff --git a/frontend/src/metabase/common/components/CodeMirror/clickableTokens.ts b/frontend/src/metabase/common/components/CodeMirror/clickableTokens.tsnew file mode 100644index 00000000000..c25822d9616--- /dev/null+++ b/frontend/src/metabase/common/components/CodeMirror/clickableTokens.ts@@ -0,0 +1,103 @@+import { syntaxTree } from "@codemirror/language";+import { RangeSetBuilder } from "@codemirror/state";+import {+ Decoration,+ type DecorationSet,+ EditorView,+ ViewPlugin,+ type ViewUpdate,+} from "@codemirror/view";+import type { SyntaxNodeRef } from "@lezer/common";++const TOKEN_CLASS_NAME = "cm-clickable-token";+const TOKEN_CLASS = `.${TOKEN_CLASS_NAME}`;+const DATA_TOKEN_ATTRIBUTE = "data-token-key";++const computeTokenDecorations = (+ view: EditorView,+ tokenDefsMap: Map<string, TokenDef>,+): DecorationSet => {+ const builder = new RangeSetBuilder<Decoration>();+ const tree = syntaxTree(view.state);++ for (const { from, to } of view.visibleRanges) {+ tree.iterate({+ from,+ to,+ enter(node) {+ for (const [key, tokenDef] of tokenDefsMap.entries()) {+ if (!tokenDef.tokenLocator(view, node)) {+ continue;+ }+ builder.add(+ node.from,+ node.to,+ Decoration.mark({+ attributes: {+ class: TOKEN_CLASS_NAME,+ [DATA_TOKEN_ATTRIBUTE]: key,+ },+ }),+ );+ }+ },+ });+ }++ return builder.finish();+};++export const clickableTokens = (tokenDefs: TokenDef[]) => {+ const tokenDefsMap = new Map<string, TokenDef>();+ tokenDefs.forEach((tokenDef, index) =>+ tokenDefsMap.set(`${index}`, tokenDef),+ );++ const plugin = ViewPlugin.fromClass(+ class {+ decorations: DecorationSet;+ constructor(view: EditorView) {+ this.decorations = computeTokenDecorations(view, tokenDefsMap);+ }+ update(update: ViewUpdate) {+ if (update.docChanged || update.viewportChanged) {+ this.decorations = computeTokenDecorations(update.view, tokenDefsMap);+ }+ }+ },+ {+ decorations: (v) => v.decorations,+ eventHandlers: {+ click(e) {+ if (!(e.target instanceof Element)) {+ return false;+ }+ const el = e.target.closest(TOKEN_CLASS);+ if (!el) {+ return false;+ }+ const key = el.getAttribute(DATA_TOKEN_ATTRIBUTE);+ if (key) {+ const tokenDef = tokenDefsMap.get(key);+ if (tokenDef?.onClick) {+ tokenDef.onClick(e);+ return true;+ }+ }+ return false;+ },+ },+ },+ );++ const theme = EditorView.baseTheme({+ [TOKEN_CLASS]: { cursor: "pointer", textDecoration: "underline" },+ });++ return [plugin, theme];+};++type TokenDef = {+ tokenLocator: (view: EditorView, node: SyntaxNodeRef) => boolean;+ onClick: (e: MouseEvent) => void;+};diff --git a/frontend/src/metabase/common/components/CodeMirror/index.ts b/frontend/src/metabase/common/components/CodeMirror/index.tsindex 6cdb49d51e9..3a406e9ea20 100644--- a/frontend/src/metabase/common/components/CodeMirror/index.ts+++ b/frontend/src/metabase/common/components/CodeMirror/index.ts@@ -1,2 +1,3 @@export { CodeMirror, type CodeMirrorProps } from "./CodeMirror";export { type CodeMirrorRef } from "./types";+export { clickableTokens } from "./clickableTokens";diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsxindex e10fd069f8d..624ccb9b10b 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsx+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsx@@ -1,4 +1,5 @@import type { Row } from "@tanstack/react-table";+import type { VirtualItem } from "@tanstack/react-virtual";import cx from "classnames";import {type KeyboardEvent,@@ -9,7 +10,12 @@ import {useRef,} from "react";-import { Box, Center, Flex } from "metabase/ui";+import {+ Box,+ Center,+ Flex,+ type TreeTableRowPinnedPosition,+} from "metabase/ui";import S from "./TreeTable.module.css";import { TreeTableHeader } from "./TreeTableHeader";@@ -39,6 +45,9 @@ export function TreeTable<TData extends TreeNodeData>({const {table,rows,+ topPinnedRows,+ centerRows,+ bottomPinnedRows,virtualRows,totalSize,virtualizer,@@ -120,6 +129,39 @@ export function TreeTable<TData extends TreeNodeData>({const showEmptyState = rows.length === 0 && emptyState;+ const renderRow = (+ row: Row<TData>,+ index: number,+ virtualItemOrPinnedPosition: VirtualItem | TreeTableRowPinnedPosition,+ ) => (+ <TreeTableRow<TData>+ key={row.id}+ row={row}+ rowIndex={index}+ virtualItemOrPinnedPosition={virtualItemOrPinnedPosition}+ table={table}+ columnWidths={columnWidths}+ showCheckboxes={showCheckboxes}+ showExpandButtons={hasExpandableNodes}+ indentWidth={indentWidth}+ activeRowId={activeRowId}+ selectedRowId={selectedRowId}+ isExpanded={row.getIsExpanded()}+ canExpand={row.getCanExpand()}+ measureElement={measureElement}+ onRowClick={handleRowClick}+ onRowDoubleClick={onRowDoubleClick}+ isDisabled={isRowDisabled?.(row)}+ isChildrenLoading={isChildrenLoading?.(row)}+ getSelectionState={getSelectionState}+ onCheckboxClick={onCheckboxClick}+ classNames={classNames}+ styles={styles}+ getRowProps={getRowProps}+ href={getRowHref?.(row)}+ />+ );+return (<Flexref={rootRef}@@ -147,56 +189,60 @@ export function TreeTable<TData extends TreeNodeData>({</Center>) : (<>- <TreeTableHeader<TData>- table={table}- columnWidths={columnWidths}- showCheckboxes={showCheckboxes}- headerVariant={headerVariant}- classNames={classNames}- styles={styles}- isMeasured={isMeasured}- totalContentWidth={totalContentWidth}- />+ <Box+ pos="sticky"+ top={0}+ style={{ minWidth: totalContentWidth, zIndex: 1 }}+ >+ <TreeTableHeader+ table={table}+ columnWidths={columnWidths}+ showCheckboxes={showCheckboxes}+ headerVariant={headerVariant}+ classNames={classNames}+ styles={styles}+ isMeasured={isMeasured}+ totalContentWidth={totalContentWidth}+ />+ {topPinnedRows.length > 0 && (+ <Box+ className={classNames?.pinnedTop}+ style={{ minWidth: totalContentWidth, ...styles?.pinnedTop }}+ >+ {topPinnedRows.map((row, index) =>+ renderRow(row, index, "top"),+ )}+ </Box>+ )}+ </Box><Boxpos="relative"style={{ height: totalSize, minWidth: totalContentWidth }}>{virtualRows.map((virtualItem) => {- const row = rows[virtualItem.index];+ const row = centerRows[virtualItem.index];if (!row) {return null;}-- return (- <TreeTableRow<TData>- key={row.id}- row={row}- rowIndex={virtualItem.index}- virtualItem={virtualItem}- table={table}- columnWidths={columnWidths}- showCheckboxes={showCheckboxes}- showExpandButtons={hasExpandableNodes}- indentWidth={indentWidth}- activeRowId={activeRowId}- selectedRowId={selectedRowId}- isExpanded={row.getIsExpanded()}- canExpand={row.getCanExpand()}- measureElement={measureElement}- onRowClick={handleRowClick}- onRowDoubleClick={onRowDoubleClick}- isDisabled={isRowDisabled?.(row)}- isChildrenLoading={isChildrenLoading?.(row)}- getSelectionState={getSelectionState}- onCheckboxClick={onCheckboxClick}- classNames={classNames}- styles={styles}- getRowProps={getRowProps}- href={getRowHref?.(row)}- />- );+ const rowIndex = topPinnedRows.length + virtualItem.index;+ return renderRow(row, rowIndex, virtualItem);})}</Box>++ {bottomPinnedRows.length > 0 && (+ <Box+ pos="sticky"+ bottom={0}+ className={classNames?.pinnedBottom}+ style={{ minWidth: totalContentWidth, ...styles?.pinnedBottom }}+ >+ {bottomPinnedRows.map((row, index) => {+ const rowIndex =+ topPinnedRows.length + centerRows.length + index;+ return renderRow(row, rowIndex, "bottom");+ })}+ </Box>+ )}</>)}</Box>diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsxindex 5ec1817e032..79fbbfb4bfe 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsx+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsx@@ -17,7 +17,6 @@ export function TreeTableHeader<TData extends TreeNodeData>({classNames,styles,isMeasured = true,- totalContentWidth,headerVariant = "pill",}: TreeTableHeaderProps<TData>) {const headerGroups = table.getHeaderGroups();@@ -27,8 +26,6 @@ export function TreeTableHeader<TData extends TreeNodeData>({className={cx(S.header, classNames?.header, {[S.measuring]: !isMeasured,})}- pos="sticky"- top={0}style={styles?.header}>{headerGroups.map((headerGroup) => (@@ -36,7 +33,7 @@ export function TreeTableHeader<TData extends TreeNodeData>({key={headerGroup.id}className={cx(S.headerRow, classNames?.headerRow)}w="100%"- style={{ minWidth: totalContentWidth, ...styles?.headerRow }}+ style={styles?.headerRow}>{showCheckboxes && (<Flexdiff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.module.css b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.module.cssindex 2efca6f1c93..acb9d3ab3b0 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.module.css+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.module.css@@ -9,6 +9,24 @@}}+.pinned {+ position: relative;+ background-color: var(--mb-color-background-primary);++ --border-style: 1px solid var(--mb-color-border);++ &[data-position="top"]:not(:last-child),+ &[data-position="top"].hasCenterRows {+ border-bottom: var(--border-style);+ }++ &[data-position="bottom"]:not(:first-child),+ &[data-position="bottom"].hasCenterRows,+ &[data-position="bottom"].hasTopPinned {+ border-top: var(--border-style);+ }+}+.content {display: flex;cursor: pointer;diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsxindex e4ac7a2a874..27ad9753919 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsx+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsx@@ -199,7 +199,7 @@ const TreeTableRowContent = memo(function TreeTableRowContent<export function TreeTableRow<TData extends TreeNodeData>({row,rowIndex,- virtualItem,+ virtualItemOrPinnedPosition,table,columnWidths,showCheckboxes,@@ -247,21 +247,38 @@ export function TreeTableRow<TData extends TreeNodeData>({rowProps={rowProps}/>);+ const renderContent = () =>+ href ? (+ <Link to={href} className={S.link}>+ {content}+ </Link>+ ) : (+ content+ );+ if (typeof virtualItemOrPinnedPosition === "string") {+ return (+ <div+ data-position={virtualItemOrPinnedPosition}+ className={cx(S.root, S.pinned, {+ [S.hasCenterRows]: table.getCenterRows().length > 0,+ [S.hasTopPinned]: table.getTopRows().length > 0,+ })}+ >+ {renderContent()}+ </div>+ );+ }return (<divref={measureElement}- data-index={virtualItem.index}+ data-index={virtualItemOrPinnedPosition.index}className={S.root}- style={{ transform: `translateY(${virtualItem.start}px)` }}+ style={{+ transform: `translateY(${virtualItemOrPinnedPosition.start}px)`,+ }}>- {href ? (- <Link to={href} className={S.link}>- {content}- </Link>- ) : (- content- )}+ {renderContent()}</div>);}diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.tsindex 9f7c212105a..4960f57a4be 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts@@ -38,6 +38,7 @@ export function useTreeTableInstance<TData extends TreeNodeData>(rowSelection: controlledRowSelection,onRowSelectionChange,enableSorting = true,+ enableRowPinning = false,sorting: controlledSorting,onSortingChange,manualSorting = false,@@ -49,6 +50,7 @@ export function useTreeTableInstance<TData extends TreeNodeData>(overscan = DEFAULT_OVERSCAN,onRowActivate,selectedRowId,+ initialState,} = options;const containerRef = useRef<HTMLDivElement>(null);@@ -191,22 +193,27 @@ export function useTreeTableInstance<TData extends TreeNodeData>(enableSubRowSelection,enableSorting,manualSorting,+ enableRowPinning,getCoreRowModel: getCoreRowModel(),getExpandedRowModel: getExpandedRowModel(),getSortedRowModel: manualSorting ? undefined : getSortedRowModel(),getFilteredRowModel: getFilteredRowModel(),filterFromLeafRows: true,globalFilterFn: effectiveFilterFn,+ initialState,});const rows = table.getRowModel().rows;+ const topPinnedRows = table.getTopRows();+ const centerRows = table.getCenterRows();+ const bottomPinnedRows = table.getBottomRows();const virtualizer = useVirtualizer({- count: rows.length,+ count: centerRows.length,getScrollElement: () => containerRef.current,estimateSize: () => defaultRowHeight,overscan,- getItemKey: (index) => rows[index]?.id ?? index,+ getItemKey: (index) => centerRows[index]?.id ?? index,});const virtualRows = virtualizer.getVirtualItems();@@ -220,6 +227,9 @@ export function useTreeTableInstance<TData extends TreeNodeData>(const keyboard = useTreeTableKeyboard({table,virtualizer,+ topPinnedRows,+ centerRows,+ bottomPinnedRows,enableRowSelection: Boolean(enableRowSelection),onRowActivate,});@@ -229,12 +239,13 @@ export function useTreeTableInstance<TData extends TreeNodeData>(rowId: string,options?: { align?: "start" | "center" | "end" | "auto" },) => {- const index = rows.findIndex((r) => r.id === rowId);+ // Only scroll to center rows - pinned rows are always visible+ const index = centerRows.findIndex((r) => r.id === rowId);if (index >= 0) {virtualizer.scrollToIndex(index, options);}},- [rows, virtualizer],+ [centerRows, virtualizer],);const scrollToNode = useCallback(@@ -247,6 +258,9 @@ export function useTreeTableInstance<TData extends TreeNodeData>(return {table,rows,+ topPinnedRows,+ centerRows,+ bottomPinnedRows,virtualizer,containerRef,virtualRows,diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableKeyboard.ts b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableKeyboard.tsindex 2432aed51ee..325a96bead6 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableKeyboard.ts+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableKeyboard.ts@@ -1,13 +1,15 @@import type { Row, Table } from "@tanstack/react-table";import type { Virtualizer } from "@tanstack/react-virtual";-import type { KeyboardEvent } from "react";-import { useCallback, useState } from "react";+import { type KeyboardEvent, useCallback, useMemo, useState } from "react";import type { TreeNodeData } from "../types";interface UseTreeTableKeyboardOptions<TData extends TreeNodeData> {table: Table<TData>;virtualizer: Virtualizer<HTMLDivElement, Element>;+ topPinnedRows: Row<TData>[];+ centerRows: Row<TData>[];+ bottomPinnedRows: Row<TData>[];enableRowSelection?: boolean;onRowActivate?: (row: Row<TData>) => void;}@@ -21,25 +23,42 @@ interface UseTreeTableKeyboardResult {export function useTreeTableKeyboard<TData extends TreeNodeData>({table,virtualizer,+ topPinnedRows,+ centerRows,+ bottomPinnedRows,enableRowSelection,onRowActivate,}: UseTreeTableKeyboardOptions<TData>): UseTreeTableKeyboardResult {const [activeRowId, setActiveRowId] = useState<string | null>(null);+ /**+ * we can't use table.getRowModel().rows because it respects the original+ * data order, not the visual order when rows are pinned+ */+ const allRows = useMemo(+ () => [...topPinnedRows, ...centerRows, ...bottomPinnedRows],+ [topPinnedRows, centerRows, bottomPinnedRows],+ );const handleKeyDown = useCallback((event: KeyboardEvent<HTMLElement>) => {- const rows = table.getRowModel().rows;- const currentIndex = rows.findIndex((r) => r.id === activeRowId);- const currentRow: Row<TData> | undefined = rows[currentIndex];+ const currentIndex = allRows.findIndex((r) => r.id === activeRowId);+ const currentRow: Row<TData> | undefined = allRows[currentIndex];++ const scrollToRowIfNeeded = (rowId: string) => {+ const centerIndex = centerRows.findIndex((r) => r.id === rowId);+ if (centerIndex >= 0) {+ virtualizer.scrollToIndex(centerIndex);+ }+ };switch (event.key) {case "ArrowDown": {event.preventDefault();- const nextIndex = Math.min(currentIndex + 1, rows.length - 1);- const nextRow = rows[nextIndex];+ const nextIndex = Math.min(currentIndex + 1, allRows.length - 1);+ const nextRow = allRows[nextIndex];if (nextRow) {setActiveRowId(nextRow.id);- virtualizer.scrollToIndex(nextIndex);+ scrollToRowIfNeeded(nextRow.id);}break;}@@ -47,10 +66,10 @@ export function useTreeTableKeyboard<TData extends TreeNodeData>({case "ArrowUp": {event.preventDefault();const prevIndex = Math.max(currentIndex - 1, 0);- const prevRow = rows[prevIndex];+ const prevRow = allRows[prevIndex];if (prevRow) {setActiveRowId(prevRow.id);- virtualizer.scrollToIndex(prevIndex);+ scrollToRowIfNeeded(prevRow.id);}break;}@@ -68,13 +87,10 @@ export function useTreeTableKeyboard<TData extends TreeNodeData>({if (currentRow?.getIsExpanded()) {currentRow.toggleExpanded(false);} else if (currentRow?.parentId) {- const parentRow = rows.find((r) => r.id === currentRow.parentId);+ const parentRow = allRows.find((r) => r.id === currentRow.parentId);if (parentRow) {setActiveRowId(parentRow.id);- const parentIndex = rows.indexOf(parentRow);- if (parentIndex >= 0) {- virtualizer.scrollToIndex(parentIndex);- }+ scrollToRowIfNeeded(parentRow.id);}}break;@@ -100,20 +116,20 @@ export function useTreeTableKeyboard<TData extends TreeNodeData>({case "Home": {event.preventDefault();- const firstRow = rows[0];+ const firstRow = allRows[0];if (firstRow) {setActiveRowId(firstRow.id);- virtualizer.scrollToIndex(0);+ scrollToRowIfNeeded(firstRow.id);}break;}case "End": {event.preventDefault();- const lastRow = rows[rows.length - 1];+ const lastRow = allRows[allRows.length - 1];if (lastRow) {setActiveRowId(lastRow.id);- virtualizer.scrollToIndex(rows.length - 1);+ scrollToRowIfNeeded(lastRow.id);}break;}@@ -127,7 +143,15 @@ export function useTreeTableKeyboard<TData extends TreeNodeData>({}}},- [table, virtualizer, activeRowId, enableRowSelection, onRowActivate],+ [+ table,+ virtualizer,+ centerRows,+ activeRowId,+ enableRowSelection,+ onRowActivate,+ allRows,+ ],);return { activeRowId, setActiveRowId, handleKeyDown };diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/types.ts b/frontend/src/metabase/ui/components/data-display/TreeTable/types.tsindex 1c7a56976e1..fdd6260f47a 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/types.ts+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/types.ts@@ -4,11 +4,13 @@ import type {FilterFn,OnChangeFn,Row,+ RowPinningPosition,RowSelectionState,SortingState,Table,} from "@tanstack/react-table";import type { VirtualItem, Virtualizer } from "@tanstack/react-virtual";+import type { InitialTableState } from "@tanstack/table-core/src/types";import type {CSSProperties,KeyboardEvent,@@ -91,6 +93,7 @@ export interface UseTreeTableInstanceOptions<TData extends TreeNodeData> {enableSubRowSelection?: boolean;rowSelection?: RowSelectionState;onRowSelectionChange?: OnChangeFn<RowSelectionState>;+ enableRowPinning?: boolean | ((row: Row<TData>) => boolean);enableSorting?: boolean;sorting?: SortingState;@@ -121,6 +124,8 @@ export interface UseTreeTableInstanceOptions<TData extends TreeNodeData> {* Independent from keyboard navigation focus.*/selectedRowId?: string | null;++ initialState?: InitialTableState;}/**@@ -139,6 +144,9 @@ export interface TreeTableInstance<TData extends TreeNodeData> {table: Table<TData>;rows: Row<TData>[];+ topPinnedRows: Row<TData>[];+ centerRows: Row<TData>[];+ bottomPinnedRows: Row<TData>[];virtualizer: Virtualizer<HTMLDivElement, Element>;containerRef: RefObject<HTMLDivElement>;@@ -171,11 +179,14 @@ export type TreeTableStylesNames =| "row"| "rowActive"| "rowDisabled"+ | "rowPinned"| "cell"| "treeCell"| "treeCellContent"| "expandButton"- | "checkbox";+ | "checkbox"+ | "pinnedTop"+ | "pinnedBottom";export type TreeTableHeaderVariant = "pill" | "plain";@@ -247,6 +258,8 @@ export interface TreeTableProps<TData extends TreeNodeData>ariaLabelledBy?: string;}+export type TreeTableRowPinnedPosition = Exclude<RowPinningPosition, false>;+/*** Props for TreeTableRow component.*/@@ -254,7 +267,7 @@ export interface TreeTableRowProps<TData extends TreeNodeData>extends TreeTableStylesProps {row: Row<TData>;rowIndex: number;- virtualItem: VirtualItem;+ virtualItemOrPinnedPosition: VirtualItem | TreeTableRowPinnedPosition;table: Table<TData>;columnWidths: Record<string, number>;showCheckboxes: boolean;