@gears-frontx/ui-kit 0.4.10 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/grid.BvRXPN-7.css +1 -0
- package/dist/chunks/switch.BYqd9jlJ.css +1 -0
- package/dist/components/data-grid/plugins/actions-menu/menu-items/export-menu-items/export-service.d.ts.map +1 -1
- package/dist/components/data-grid/plugins/drag-drop/drag-drop-plugin.d.ts.map +1 -1
- package/dist/components/grid/grid-config.d.ts +29 -0
- package/dist/components/grid/grid-config.d.ts.map +1 -0
- package/dist/components/grid/grid-default-config.json.d.ts +19 -0
- package/dist/components/grid/grid-solver.d.ts +30 -0
- package/dist/components/grid/grid-solver.d.ts.map +1 -0
- package/dist/components/grid/grid.d.ts +24 -0
- package/dist/components/grid/grid.d.ts.map +1 -0
- package/dist/components/grid/public.d.ts +5 -0
- package/dist/components/grid/public.d.ts.map +1 -0
- package/dist/data-grid/actions-menu.js +90 -90
- package/dist/data-grid/actions-menu.js.map +1 -1
- package/dist/data-grid/drag-drop.js +76 -67
- package/dist/data-grid/drag-drop.js.map +1 -1
- package/dist/data-grid/table-tree.js +1 -1
- package/dist/data-grid/table-tree.js.map +1 -1
- package/dist/docs/data-grid.md +3 -2
- package/dist/docs/grid.md +127 -0
- package/dist/frontx-ui-grid-css.mjs +82 -0
- package/dist/grid-config-check.mjs +78 -0
- package/dist/grid-css.mjs +32 -0
- package/dist/grid-default-config.json +16 -0
- package/dist/grid.d.ts +1 -0
- package/dist/grid.js +227 -0
- package/dist/grid.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +264 -260
- package/dist/index.js.map +1 -1
- package/dist/switch.js +10 -10
- package/llms.txt +9 -0
- package/package.json +6 -3
- package/dist/chunks/switch.D3_ZyuVP.css +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"drag-drop.js","sources":["../../src/components/data-grid/plugins/drag-drop/components/data-grid-drag-drop-body-cell.tsx","../../src/components/data-grid/plugins/drag-drop/drag-data.ts","../../src/components/data-grid/plugins/drag-drop/components/data-grid-drag-drop-content.tsx","../../src/components/data-grid/plugins/drag-drop/drag-preview.ts","../../src/components/data-grid/plugins/drag-drop/components/data-grid-drag-drop-row.tsx","../../src/components/data-grid/plugins/drag-drop/drag-drop-plugin.tsx"],"sourcesContent":["import { cx } from 'class-variance-authority';\nimport { GripVerticalIcon } from 'lucide-react';\nimport { Spinner } from '../../../../spinner/public.js';\nimport { messages } from '../../../messages';\nimport { useDataGrid } from '../../../services/core/data-grid-context';\nimport { IGNORE_CLICK_ATTRIBUTE } from '../../../services/table/ignore-row-click';\nimport { useDataGridRecord } from '../../../services/table/data-grid-record-context';\nimport type { DataGridDragDropPluginApi } from '../drag-drop-types';\nimport styles from './data-grid-drag-drop.module.css';\n\nexport function DataGridDragDropBodyCell() {\n const grid = useDataGrid();\n const record = useDataGridRecord();\n\n const { useDropLoadingStore } = grid.getPlugin<DataGridDragDropPluginApi>('dragDrop')!;\n\n const isLoading = useDropLoadingStore((s) => !!s.loading[record.id]);\n\n return (\n <div\n className={cx(styles.dragHandler, isLoading && styles.dragHandlerLoading)}\n {...{ [IGNORE_CLICK_ATTRIBUTE]: '' }}\n data-drag-handle=\"\"\n aria-label={messages.dragDrop.dragHandle}\n >\n {isLoading ? <Spinner /> : <GripVerticalIcon />}\n </div>\n );\n}\n","import type { DataGridItemId, DataGridRecord } from '../../services/storage/storage-types';\nimport { isRecord } from '../../utils/is-record';\n\n// What a row puts in the drag data (`getInitialData`) and a drop target reads back is typed\n// `unknown` by the drag library, so each read goes through one of these guards instead of a cast.\n\nfunction isDataGridItemId(value: unknown): value is DataGridItemId {\n return typeof value === 'string' || typeof value === 'number';\n}\n\nfunction isDataGridRecord(value: unknown): value is DataGridRecord {\n return isRecord(value) && isDataGridItemId(value.id) && isRecord(value.item);\n}\n\n/** The record a dragged row or a row used as a drop target carries, or nothing for any other data. */\nexport function readRecord(data: Record<string | symbol, unknown>): DataGridRecord | undefined {\n return isDataGridRecord(data.record) ? data.record : undefined;\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';\nimport {\n dropTargetForElements,\n monitorForElements,\n} from '@atlaskit/pragmatic-drag-and-drop/element/adapter';\nimport { extractClosestEdge } from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge';\nimport { cx } from 'class-variance-authority';\nimport type { ReactNode } from 'react';\nimport { useEffect, useRef } from 'react';\nimport { useDataGridContext } from '../../../services/core/data-grid-context';\nimport { readRecord } from '../drag-data';\nimport type { DataGridDragDropPluginApi } from '../drag-drop-types';\nimport styles from './data-grid-drag-drop.module.css';\n\ninterface DataGridDragDropContentProps {\n children?: ReactNode;\n}\n\nexport function DataGridDragDropContent({ children }: DataGridDragDropContentProps) {\n const contentRef = useRef<HTMLDivElement>(null);\n\n const context = useDataGridContext();\n const { useDragDropStore, handleDrop } =\n context.plugins.getPlugin<DataGridDragDropPluginApi>('dragDrop')!;\n\n const isDragging = useDragDropStore((s) => s.isDragging);\n const isRootDropTarget = useDragDropStore((s) => s.isRootDropTarget);\n\n useEffect(() => {\n if (!contentRef.current) return;\n\n return combine(\n dropTargetForElements({\n element: contentRef.current,\n getData: () => ({ type: 'data-grid-root' }),\n }),\n monitorForElements({\n // A page can hold several grids with this plugin, and another grid's rows are drag\n // sources too: only a drag that began in this plugin instance is this one's to track.\n canMonitor: ({ source }) => source.data.pluginStore === useDragDropStore,\n onDragStart: ({ source }) => {\n const record = readRecord(source.data);\n if (!record) return;\n\n useDragDropStore.setState({ isDragging: true, draggedRecordId: record.id });\n },\n onDropTargetChange: ({ location }) => {\n const targets = location.current.dropTargets;\n const rowTarget = targets.find((t) => t.data.type === 'data-grid-row');\n const rootTarget = targets.find((t) => t.data.type === 'data-grid-root');\n const dropEdge = rowTarget ? extractClosestEdge(rowTarget.data) : null;\n const targetRecord = rowTarget ? readRecord(rowTarget.data) : undefined;\n\n useDragDropStore.setState({\n dropTargetRecordId: targetRecord?.id,\n dropEdge: dropEdge === 'top' || dropEdge === 'bottom' ? dropEdge : undefined,\n isRootDropTarget: !rowTarget && !!rootTarget,\n });\n },\n onDrop: ({ source, location }) => {\n const targets = location.current.dropTargets;\n const sourceRecord = readRecord(source.data);\n\n if (targets.length > 0 && sourceRecord) {\n const rowTarget = targets.find((t) => t.data.type === 'data-grid-row');\n handleDrop(sourceRecord, rowTarget ? readRecord(rowTarget.data) : undefined);\n }\n\n useDragDropStore.setState({\n isDragging: false,\n draggedRecordId: undefined,\n dropTargetRecordId: undefined,\n dropEdge: undefined,\n isRootDropTarget: false,\n });\n },\n }),\n );\n }, [useDragDropStore, handleDrop]);\n\n return (\n <div\n ref={contentRef}\n className={cx(\n styles.content,\n isDragging && styles.contentDragging,\n isDragging && isRootDropTarget && styles.contentRootDropping,\n )}\n >\n {children}\n </div>\n );\n}\n","export function buildClonedRowPreview(row: HTMLElement, className: string): HTMLTableElement {\n const table = document.createElement('table');\n const sourceTable = row.closest('table');\n table.className = [sourceTable?.className, className].filter(Boolean).join(' ');\n table.style.width = `${row.getBoundingClientRect().width}px`;\n\n const tbody = document.createElement('tbody');\n tbody.appendChild(row.cloneNode(true));\n table.appendChild(tbody);\n\n return table;\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';\nimport {\n draggable,\n dropTargetForElements,\n} from '@atlaskit/pragmatic-drag-and-drop/element/adapter';\nimport { pointerOutsideOfPreview } from '@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview';\nimport { setCustomNativeDragPreview } from '@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview';\nimport { attachClosestEdge } from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge';\nimport { cx } from 'class-variance-authority';\nimport { useEffect, useRef, useState } from 'react';\nimport { createPortal, flushSync } from 'react-dom';\nimport { TableRow } from '../../../../table/public.js';\nimport type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGridContext } from '../../../services/core/data-grid-context';\nimport type { DataGridRecord } from '../../../services/storage/storage-types';\nimport { DataGridCell } from '../../../services/table/components/data-grid-cell';\nimport { DataGridExtraBodyColumns } from '../../../services/table/components/data-grid-extra-body-columns';\nimport { DataGridRecordProvider } from '../../../services/table/data-grid-record-context';\nimport { resolveBodyCellProps } from '../../../services/table/resolve-body-cell-props';\nimport type { DataGridTableColumn } from '../../../services/table/table-types';\nimport { useLatest } from '../../../utils/use-latest';\nimport type { DataGridDragDropPluginApi } from '../drag-drop-types';\nimport { buildClonedRowPreview } from '../drag-preview';\nimport styles from './data-grid-drag-drop.module.css';\n\ninterface DataGridDragDropRowProps<TItem extends DataGridItem> {\n record: DataGridRecord<TItem>;\n}\n\nexport function DataGridDragDropRow<TItem extends DataGridItem>({\n record,\n}: DataGridDragDropRowProps<TItem>) {\n const rowRef = useRef<HTMLTableRowElement>(null);\n // The drag and drop callbacks are registered once per record id and read the record when the\n // event fires, so a refreshed record is what they see.\n const recordRef = useLatest(record);\n\n const [previewContainer, setPreviewContainer] = useState<HTMLElement | null>(null);\n\n const context = useDataGridContext<TItem>();\n const tableService = context.table;\n const columns = tableService.useVisibleColumns();\n const tableLayout = tableService.useTableLayout();\n\n const { useDragDropStore, renderDragPreview } =\n context.plugins.getPlugin<DataGridDragDropPluginApi<TItem>>('dragDrop')!;\n\n const isDragging = useDragDropStore((s) => s.draggedRecordId === record.id);\n const isDropping = useDragDropStore((s) => s.dropTargetRecordId === record.id);\n const dropEdge = useDragDropStore((s) =>\n s.dropTargetRecordId === record.id ? s.dropEdge : undefined,\n );\n\n const BodyCellContent = tableService.useComponent<{\n column: DataGridTableColumn<TItem>;\n item: TItem;\n }>('body-cell-content');\n\n useEffect(() => {\n if (!rowRef.current) return;\n\n const handleEl = rowRef.current.querySelector<HTMLElement>('[data-drag-handle]');\n\n return combine(\n draggable({\n element: rowRef.current,\n dragHandle: handleEl ?? undefined,\n getInitialData: () => ({\n type: 'data-grid-row',\n pluginStore: useDragDropStore,\n recordId: recordRef.current.id,\n record: recordRef.current,\n }),\n onGenerateDragPreview: ({ nativeSetDragImage }) => {\n setCustomNativeDragPreview({\n nativeSetDragImage,\n getOffset: pointerOutsideOfPreview({ x: '8px', y: '8px' }),\n render: ({ container }) => {\n if (renderDragPreview) {\n // Render the consumer's preview inside the live React tree (so it\n // keeps context); flushSync commits the portal before the browser\n // snapshots the preview image.\n flushSync(() => setPreviewContainer(container));\n return () => setPreviewContainer(null);\n }\n const row = rowRef.current;\n if (!row) return undefined;\n container.appendChild(buildClonedRowPreview(row, styles.dragPreview));\n return undefined;\n },\n });\n },\n }),\n dropTargetForElements({\n element: rowRef.current,\n canDrop: ({ source }) =>\n source.data.pluginStore === useDragDropStore &&\n source.data.recordId !== recordRef.current.id,\n getData: ({ input, element }) =>\n attachClosestEdge(\n {\n type: 'data-grid-row',\n recordId: recordRef.current.id,\n record: recordRef.current,\n },\n { input, element, allowedEdges: ['top', 'bottom'] },\n ),\n }),\n );\n }, [record.id, useDragDropStore, renderDragPreview, recordRef]);\n\n return (\n <DataGridRecordProvider value={record}>\n <TableRow\n ref={rowRef}\n className={cx(\n styles.dragRow,\n isDragging && styles.dragRowDragging,\n isDropping && styles.dragRowDropping,\n dropEdge === 'top' && styles.dragRowDropIndicatorTop,\n dropEdge === 'bottom' && styles.dragRowDropIndicatorBottom,\n )}\n >\n <DataGridExtraBodyColumns position=\"start\" />\n {columns.map((col) => {\n const dynamicClassName = col.getClassName?.(record.item);\n const bodyCellProps = resolveBodyCellProps(col, record.item, tableLayout);\n\n return (\n <DataGridCell<TItem>\n key={col.id}\n columnId={col.id}\n className={dynamicClassName}\n {...bodyCellProps}\n >\n <BodyCellContent column={col} item={record.item} />\n </DataGridCell>\n );\n })}\n <DataGridExtraBodyColumns position=\"end\" />\n </TableRow>\n {previewContainer && renderDragPreview\n ? createPortal(renderDragPreview(record.item), previewContainer)\n : null}\n </DataGridRecordProvider>\n );\n}\n","// Load-bearing: a plugin is rendered as a child of <DataGrid>, so a Server Component can import\n// and render it, and the component it returns calls hooks. This directive puts the banner on the\n// plugin's own entry chunk (dist/data-grid/<plugin>.js). client-boundaries.test.ts only scans a\n// component's top-level files, so scripts/verify-consumer.sh is what checks the built banner of\n// every plugin entry.\n'use client';\n\nimport { create } from 'zustand';\n// The `.js` on the type imports below is for the shipped declaration file: this file's\n// `createDataGridDragDropPlugin(config: DataGridDragDropPluginProps)` is a signature a consumer\n// types a callback by, and `moduleResolution: \"nodenext\"` rejects an extensionless relative\n// specifier in it, which turns the parameter into an untyped one.\nimport type { DataGridItem } from '../../data-grid-types.js';\nimport { createDataGridPlugin } from '../../services/plugins/plugins-helpers';\nimport type { DataGridItemId, DataGridRecord } from '../../services/storage/storage-types.js';\nimport { DataGridDragDropBodyCell } from './components/data-grid-drag-drop-body-cell';\nimport { DataGridDragDropContent } from './components/data-grid-drag-drop-content';\nimport { DataGridDragDropRow } from './components/data-grid-drag-drop-row';\nimport type {\n DataGridDragDropPluginApi,\n DataGridDragDropPluginProps,\n DataGridDragDropState,\n DataGridDropLoadingState,\n} from './drag-drop-types.js';\n\n/**\n * Creates a drag-and-drop plugin component for reordering a DataGrid's rows. It is a factory\n * because the callbacks are the plugin's own configuration, not props of the component it\n * returns: create it once, outside render, and render the result as a child of the grid.\n */\nexport function createDataGridDragDropPlugin<TItem extends DataGridItem = DataGridItem>(\n config: DataGridDragDropPluginProps<TItem>,\n) {\n return createDataGridPlugin<TItem, 'dragDrop', Record<string, never>, DataGridDragDropPluginApi<TItem>>(\n 'dragDrop',\n (context) => {\n const useDragDropStore = create<DataGridDragDropState>(() => ({\n isDragging: false,\n draggedRecordId: undefined,\n dropTargetRecordId: undefined,\n dropEdge: undefined,\n isRootDropTarget: false,\n }));\n\n const useDropLoadingStore = create<DataGridDropLoadingState>(() => ({\n loading: {},\n }));\n\n context.registerComponent('content', DataGridDragDropContent);\n context.registerExtraColumn({\n id: 'drag-drop',\n body: DataGridDragDropBodyCell,\n position: 'start',\n order: 0,\n width: '37px',\n });\n context.registerComponent('row', DataGridDragDropRow);\n\n return {\n renderDragPreview: config.renderDragPreview,\n useDragDropStore,\n useDropLoadingStore,\n setDropLoading,\n clearDropLoading,\n handleDrop,\n };\n\n function setDropLoading(id: DataGridItemId, value: boolean) {\n useDropLoadingStore.setState((state) => ({ loading: { ...state.loading, [id]: value } }));\n }\n\n function clearDropLoading(id: DataGridItemId) {\n useDropLoadingStore.setState((state) => {\n const next = { ...state.loading };\n delete next[id];\n return { loading: next };\n });\n }\n\n function handleDrop(\n sourceRecord: DataGridRecord<TItem>,\n targetRecord: DataGridRecord<TItem> | undefined,\n ) {\n executeHandleDrop({\n sourceRecord,\n targetRecord,\n onDrop: (item, target) => config.onDrop({ ...context, item, target }),\n setDropLoading,\n clearDropLoading,\n });\n }\n },\n );\n}\n\n/** @internal Extracted for testability. */\nexport function executeHandleDrop<TItem extends DataGridItem>({\n sourceRecord,\n targetRecord,\n onDrop,\n setDropLoading,\n clearDropLoading,\n}: {\n sourceRecord: Pick<DataGridRecord<TItem>, 'id' | 'item'>;\n targetRecord: Pick<DataGridRecord<TItem>, 'item'> | undefined;\n onDrop: (item: TItem, target: TItem | null) => void | Promise<void>;\n setDropLoading: (id: DataGridItemId, value: boolean) => void;\n clearDropLoading: (id: DataGridItemId) => void;\n}) {\n const target = targetRecord?.item ?? null;\n const drop = onDrop(sourceRecord.item, target);\n\n if (drop instanceof Promise) {\n setDropLoading(sourceRecord.id, true);\n drop\n .catch(() => {\n // Swallow rejection — cleanup happens in finally\n })\n .finally(() => {\n clearDropLoading(sourceRecord.id);\n });\n }\n}\n"],"names":["DataGridDragDropBodyCell","grid","useDataGrid","record","useDataGridRecord","useDropLoadingStore","isLoading","s","jsx","cx","styles","IGNORE_CLICK_ATTRIBUTE","messages","Spinner","GripVerticalIcon","isDataGridItemId","value","isDataGridRecord","isRecord","readRecord","data","DataGridDragDropContent","children","contentRef","useRef","context","useDataGridContext","useDragDropStore","handleDrop","isDragging","isRootDropTarget","useEffect","combine","dropTargetForElements","monitorForElements","source","location","targets","rowTarget","t","rootTarget","dropEdge","extractClosestEdge","targetRecord","sourceRecord","buildClonedRowPreview","row","className","table","sourceTable","tbody","DataGridDragDropRow","rowRef","recordRef","useLatest","previewContainer","setPreviewContainer","useState","tableService","columns","tableLayout","renderDragPreview","isDropping","BodyCellContent","handleEl","draggable","nativeSetDragImage","setCustomNativeDragPreview","pointerOutsideOfPreview","container","flushSync","input","element","attachClosestEdge","jsxs","DataGridRecordProvider","TableRow","DataGridExtraBodyColumns","col","dynamicClassName","_a","bodyCellProps","resolveBodyCellProps","DataGridCell","createPortal","createDataGridDragDropPlugin","config","createDataGridPlugin","create","setDropLoading","clearDropLoading","id","state","next","executeHandleDrop","item","target","onDrop","drop"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,SAASA,KAA2B;AACzC,QAAMC,IAAOC,EAAA,GACPC,IAASC,EAAA,GAET,EAAE,qBAAAC,EAAA,IAAwBJ,EAAK,UAAqC,UAAU,GAE9EK,IAAYD,EAAoB,CAACE,MAAM,CAAC,CAACA,EAAE,QAAQJ,EAAO,EAAE,CAAC;AAEnE,SACE,gBAAAK;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAWC,EAAGC,EAAO,aAAaJ,KAAaI,EAAO,kBAAkB;AAAA,MAClE,CAACC,CAAsB,GAAG;AAAA,MAChC,oBAAiB;AAAA,MACjB,cAAYC,EAAS,SAAS;AAAA,MAE7B,UAAAN,IAAY,gBAAAE,EAACK,GAAA,CAAA,CAAQ,sBAAMC,GAAA,CAAA,CAAiB;AAAA,IAAA;AAAA,EAAA;AAGnD;ACtBA,SAASC,GAAiBC,GAAyC;AACjE,SAAO,OAAOA,KAAU,YAAY,OAAOA,KAAU;AACvD;AAEA,SAASC,GAAiBD,GAAyC;AACjE,SAAOE,EAASF,CAAK,KAAKD,GAAiBC,EAAM,EAAE,KAAKE,EAASF,EAAM,IAAI;AAC7E;AAGO,SAASG,EAAWC,G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GAAG3E,EAAA,IAAU;AAAA,MAC1F;AAEA,eAAS0E,EAAiBC,GAAoB;AAC5C,QAAAtF,EAAoB,SAAS,CAACuF,MAAU;AACtC,gBAAMC,IAAO,EAAE,GAAGD,EAAM,QAAA;AACxB,wBAAOC,EAAKF,CAAE,GACP,EAAE,SAASE,EAAA;AAAA,QACpB,CAAC;AAAA,MACH;AAEA,eAASjE,EACPgB,GACAD,GACA;AACA,QAAAmD,GAAkB;AAAA,UAChB,cAAAlD;AAAA,UACA,cAAAD;AAAA,UACA,QAAQ,CAACoD,GAAMC,MAAWV,EAAO,OAAO,EAAE,GAAG7D,GAAS,MAAAsE,GAAM,QAAAC,GAAQ;AAAA,UACpE,gBAAAP;AAAA,UACA,kBAAAC;AAAA,QAAA,CACD;AAAA,MACH;AAAA,IACF;AAAA,EAAA;AAEJ;AAGO,SAASI,GAA8C;AAAA,EAC5D,cAAAlD;AAAA,EACA,cAAAD;AAAA,EACA,QAAAsD;AAAA,EACA,gBAAAR;AAAA,EACA,kBAAAC;AACF,GAMG;AACD,QAAMM,KAASrD,KAAA,gBAAAA,EAAc,SAAQ,MAC/BuD,IAAOD,EAAOrD,EAAa,MAAMoD,CAAM;AAE7C,EAAIE,aAAgB,YAClBT,EAAe7C,EAAa,IAAI,EAAI,GACpCsD,EACG,MAAM,MAAM;AAAA,EAEb,CAAC,EACA,QAAQ,MAAM;AACb,IAAAR,EAAiB9C,EAAa,EAAE;AAAA,EAClC,CAAC;AAEP;"}
|
|
1
|
+
{"version":3,"file":"drag-drop.js","sources":["../../src/components/data-grid/plugins/drag-drop/components/data-grid-drag-drop-body-cell.tsx","../../src/components/data-grid/plugins/drag-drop/drag-data.ts","../../src/components/data-grid/plugins/drag-drop/components/data-grid-drag-drop-content.tsx","../../src/components/data-grid/plugins/drag-drop/drag-preview.ts","../../src/components/data-grid/plugins/drag-drop/components/data-grid-drag-drop-row.tsx","../../src/components/data-grid/plugins/drag-drop/drag-drop-plugin.tsx"],"sourcesContent":["import { cx } from 'class-variance-authority';\nimport { GripVerticalIcon } from 'lucide-react';\nimport { Spinner } from '../../../../spinner/public.js';\nimport { messages } from '../../../messages';\nimport { useDataGrid } from '../../../services/core/data-grid-context';\nimport { IGNORE_CLICK_ATTRIBUTE } from '../../../services/table/ignore-row-click';\nimport { useDataGridRecord } from '../../../services/table/data-grid-record-context';\nimport type { DataGridDragDropPluginApi } from '../drag-drop-types';\nimport styles from './data-grid-drag-drop.module.css';\n\nexport function DataGridDragDropBodyCell() {\n const grid = useDataGrid();\n const record = useDataGridRecord();\n\n const { useDropLoadingStore } = grid.getPlugin<DataGridDragDropPluginApi>('dragDrop')!;\n\n const isLoading = useDropLoadingStore((s) => !!s.loading[record.id]);\n\n return (\n <div\n className={cx(styles.dragHandler, isLoading && styles.dragHandlerLoading)}\n {...{ [IGNORE_CLICK_ATTRIBUTE]: '' }}\n data-drag-handle=\"\"\n aria-label={messages.dragDrop.dragHandle}\n >\n {isLoading ? <Spinner /> : <GripVerticalIcon />}\n </div>\n );\n}\n","import type { DataGridItemId, DataGridRecord } from '../../services/storage/storage-types';\nimport { isRecord } from '../../utils/is-record';\n\n// What a row puts in the drag data (`getInitialData`) and a drop target reads back is typed\n// `unknown` by the drag library, so each read goes through one of these guards instead of a cast.\n\nfunction isDataGridItemId(value: unknown): value is DataGridItemId {\n return typeof value === 'string' || typeof value === 'number';\n}\n\nfunction isDataGridRecord(value: unknown): value is DataGridRecord {\n return isRecord(value) && isDataGridItemId(value.id) && isRecord(value.item);\n}\n\n/** The record a dragged row or a row used as a drop target carries, or nothing for any other data. */\nexport function readRecord(data: Record<string | symbol, unknown>): DataGridRecord | undefined {\n return isDataGridRecord(data.record) ? data.record : undefined;\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';\nimport {\n dropTargetForElements,\n monitorForElements,\n} from '@atlaskit/pragmatic-drag-and-drop/element/adapter';\nimport { extractClosestEdge } from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge';\nimport { cx } from 'class-variance-authority';\nimport type { ReactNode } from 'react';\nimport { useEffect, useRef } from 'react';\nimport { useDataGridContext } from '../../../services/core/data-grid-context';\nimport { readRecord } from '../drag-data';\nimport type { DataGridDragDropPluginApi } from '../drag-drop-types';\nimport styles from './data-grid-drag-drop.module.css';\n\ninterface DataGridDragDropContentProps {\n children?: ReactNode;\n}\n\nexport function DataGridDragDropContent({ children }: DataGridDragDropContentProps) {\n const contentRef = useRef<HTMLDivElement>(null);\n\n const context = useDataGridContext();\n const { useDragDropStore, handleDrop } =\n context.plugins.getPlugin<DataGridDragDropPluginApi>('dragDrop')!;\n\n const isDragging = useDragDropStore((s) => s.isDragging);\n const isRootDropTarget = useDragDropStore((s) => s.isRootDropTarget);\n\n useEffect(() => {\n if (!contentRef.current) return;\n\n return combine(\n dropTargetForElements({\n element: contentRef.current,\n getData: () => ({ type: 'data-grid-root' }),\n }),\n monitorForElements({\n // A page can hold several grids with this plugin, and another grid's rows are drag\n // sources too: only a drag that began in this plugin instance is this one's to track.\n canMonitor: ({ source }) => source.data.pluginStore === useDragDropStore,\n onDragStart: ({ source }) => {\n const record = readRecord(source.data);\n if (!record) return;\n\n useDragDropStore.setState({ isDragging: true, draggedRecordId: record.id });\n },\n onDropTargetChange: ({ location }) => {\n const targets = location.current.dropTargets;\n const rowTarget = targets.find((t) => t.data.type === 'data-grid-row');\n const rootTarget = targets.find((t) => t.data.type === 'data-grid-root');\n const dropEdge = rowTarget ? extractClosestEdge(rowTarget.data) : null;\n const targetRecord = rowTarget ? readRecord(rowTarget.data) : undefined;\n\n useDragDropStore.setState({\n dropTargetRecordId: targetRecord?.id,\n dropEdge: dropEdge === 'top' || dropEdge === 'bottom' ? dropEdge : undefined,\n isRootDropTarget: !rowTarget && !!rootTarget,\n });\n },\n onDrop: ({ source, location }) => {\n const targets = location.current.dropTargets;\n const sourceRecord = readRecord(source.data);\n\n if (targets.length > 0 && sourceRecord) {\n const rowTarget = targets.find((t) => t.data.type === 'data-grid-row');\n handleDrop(sourceRecord, rowTarget ? readRecord(rowTarget.data) : undefined);\n }\n\n useDragDropStore.setState({\n isDragging: false,\n draggedRecordId: undefined,\n dropTargetRecordId: undefined,\n dropEdge: undefined,\n isRootDropTarget: false,\n });\n },\n }),\n );\n }, [useDragDropStore, handleDrop]);\n\n return (\n <div\n ref={contentRef}\n className={cx(\n styles.content,\n isDragging && styles.contentDragging,\n isDragging && isRootDropTarget && styles.contentRootDropping,\n )}\n >\n {children}\n </div>\n );\n}\n","export function buildClonedRowPreview(row: HTMLElement, className: string): HTMLTableElement {\n const table = document.createElement('table');\n const sourceTable = row.closest('table');\n table.className = [sourceTable?.className, className].filter(Boolean).join(' ');\n table.style.width = `${row.getBoundingClientRect().width}px`;\n\n const tbody = document.createElement('tbody');\n tbody.appendChild(row.cloneNode(true));\n table.appendChild(tbody);\n\n return table;\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';\nimport {\n draggable,\n dropTargetForElements,\n} from '@atlaskit/pragmatic-drag-and-drop/element/adapter';\nimport { pointerOutsideOfPreview } from '@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview';\nimport { setCustomNativeDragPreview } from '@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview';\nimport { attachClosestEdge } from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge';\nimport { cx } from 'class-variance-authority';\nimport { useEffect, useRef, useState } from 'react';\nimport { createPortal, flushSync } from 'react-dom';\nimport { TableRow } from '../../../../table/public.js';\nimport type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGridContext } from '../../../services/core/data-grid-context';\nimport type { DataGridRecord } from '../../../services/storage/storage-types';\nimport { DataGridCell } from '../../../services/table/components/data-grid-cell';\nimport { DataGridExtraBodyColumns } from '../../../services/table/components/data-grid-extra-body-columns';\nimport { DataGridRecordProvider } from '../../../services/table/data-grid-record-context';\nimport { resolveBodyCellProps } from '../../../services/table/resolve-body-cell-props';\nimport type { DataGridTableColumn } from '../../../services/table/table-types';\nimport { useLatest } from '../../../utils/use-latest';\nimport type { DataGridDragDropPluginApi } from '../drag-drop-types';\nimport { buildClonedRowPreview } from '../drag-preview';\nimport styles from './data-grid-drag-drop.module.css';\n\ninterface DataGridDragDropRowProps<TItem extends DataGridItem> {\n record: DataGridRecord<TItem>;\n}\n\nexport function DataGridDragDropRow<TItem extends DataGridItem>({\n record,\n}: DataGridDragDropRowProps<TItem>) {\n const rowRef = useRef<HTMLTableRowElement>(null);\n // The drag and drop callbacks are registered once per record id and read the record when the\n // event fires, so a refreshed record is what they see.\n const recordRef = useLatest(record);\n\n const [previewContainer, setPreviewContainer] = useState<HTMLElement | null>(null);\n\n const context = useDataGridContext<TItem>();\n const tableService = context.table;\n const columns = tableService.useVisibleColumns();\n const tableLayout = tableService.useTableLayout();\n\n const { useDragDropStore, renderDragPreview } =\n context.plugins.getPlugin<DataGridDragDropPluginApi<TItem>>('dragDrop')!;\n\n const isDragging = useDragDropStore((s) => s.draggedRecordId === record.id);\n const isDropping = useDragDropStore((s) => s.dropTargetRecordId === record.id);\n const dropEdge = useDragDropStore((s) =>\n s.dropTargetRecordId === record.id ? s.dropEdge : undefined,\n );\n\n const BodyCellContent = tableService.useComponent<{\n column: DataGridTableColumn<TItem>;\n item: TItem;\n }>('body-cell-content');\n\n useEffect(() => {\n if (!rowRef.current) return;\n\n const handleEl = rowRef.current.querySelector<HTMLElement>('[data-drag-handle]');\n\n return combine(\n draggable({\n element: rowRef.current,\n dragHandle: handleEl ?? undefined,\n getInitialData: () => ({\n type: 'data-grid-row',\n pluginStore: useDragDropStore,\n recordId: recordRef.current.id,\n record: recordRef.current,\n }),\n onGenerateDragPreview: ({ nativeSetDragImage }) => {\n setCustomNativeDragPreview({\n nativeSetDragImage,\n getOffset: pointerOutsideOfPreview({ x: '8px', y: '8px' }),\n render: ({ container }) => {\n if (renderDragPreview) {\n // Render the consumer's preview inside the live React tree (so it\n // keeps context); flushSync commits the portal before the browser\n // snapshots the preview image.\n flushSync(() => setPreviewContainer(container));\n return () => setPreviewContainer(null);\n }\n const row = rowRef.current;\n if (!row) return undefined;\n container.appendChild(buildClonedRowPreview(row, styles.dragPreview));\n return undefined;\n },\n });\n },\n }),\n dropTargetForElements({\n element: rowRef.current,\n canDrop: ({ source }) =>\n source.data.pluginStore === useDragDropStore &&\n source.data.recordId !== recordRef.current.id,\n getData: ({ input, element }) =>\n attachClosestEdge(\n {\n type: 'data-grid-row',\n recordId: recordRef.current.id,\n record: recordRef.current,\n },\n { input, element, allowedEdges: ['top', 'bottom'] },\n ),\n }),\n );\n }, [record.id, useDragDropStore, renderDragPreview, recordRef]);\n\n return (\n <DataGridRecordProvider value={record}>\n <TableRow\n ref={rowRef}\n className={cx(\n styles.dragRow,\n isDragging && styles.dragRowDragging,\n isDropping && styles.dragRowDropping,\n dropEdge === 'top' && styles.dragRowDropIndicatorTop,\n dropEdge === 'bottom' && styles.dragRowDropIndicatorBottom,\n )}\n >\n <DataGridExtraBodyColumns position=\"start\" />\n {columns.map((col) => {\n const dynamicClassName = col.getClassName?.(record.item);\n const bodyCellProps = resolveBodyCellProps(col, record.item, tableLayout);\n\n return (\n <DataGridCell<TItem>\n key={col.id}\n columnId={col.id}\n className={dynamicClassName}\n {...bodyCellProps}\n >\n <BodyCellContent column={col} item={record.item} />\n </DataGridCell>\n );\n })}\n <DataGridExtraBodyColumns position=\"end\" />\n </TableRow>\n {previewContainer && renderDragPreview\n ? createPortal(renderDragPreview(record.item), previewContainer)\n : null}\n </DataGridRecordProvider>\n );\n}\n","// Load-bearing: a plugin is rendered as a child of <DataGrid>, so a Server Component can import\n// and render it, and the component it returns calls hooks. This directive puts the banner on the\n// plugin's own entry chunk (dist/data-grid/<plugin>.js). client-boundaries.test.ts only scans a\n// component's top-level files, so scripts/verify-consumer.sh is what checks the built banner of\n// every plugin entry.\n'use client';\n\nimport { create } from 'zustand';\n// The `.js` on the type imports below is for the shipped declaration file: this file's\n// `createDataGridDragDropPlugin(config: DataGridDragDropPluginProps)` is a signature a consumer\n// types a callback by, and `moduleResolution: \"nodenext\"` rejects an extensionless relative\n// specifier in it, which turns the parameter into an untyped one.\nimport type { DataGridItem } from '../../data-grid-types.js';\nimport { createDataGridPlugin } from '../../services/plugins/plugins-helpers';\nimport type { DataGridItemId, DataGridRecord } from '../../services/storage/storage-types.js';\nimport { DataGridDragDropBodyCell } from './components/data-grid-drag-drop-body-cell';\nimport { DataGridDragDropContent } from './components/data-grid-drag-drop-content';\nimport { DataGridDragDropRow } from './components/data-grid-drag-drop-row';\nimport type {\n DataGridDragDropPluginApi,\n DataGridDragDropPluginProps,\n DataGridDragDropState,\n DataGridDropLoadingState,\n} from './drag-drop-types.js';\n\n/**\n * Creates a drag-and-drop plugin component for reordering a DataGrid's rows. It is a factory\n * because the callbacks are the plugin's own configuration, not props of the component it\n * returns: create it once, outside render, and render the result as a child of the grid.\n */\nexport function createDataGridDragDropPlugin<TItem extends DataGridItem = DataGridItem>(\n config: DataGridDragDropPluginProps<TItem>,\n) {\n return createDataGridPlugin<TItem, 'dragDrop', Record<string, never>, DataGridDragDropPluginApi<TItem>>(\n 'dragDrop',\n (context) => {\n const useDragDropStore = create<DataGridDragDropState>(() => ({\n isDragging: false,\n draggedRecordId: undefined,\n dropTargetRecordId: undefined,\n dropEdge: undefined,\n isRootDropTarget: false,\n }));\n\n const useDropLoadingStore = create<DataGridDropLoadingState>(() => ({\n loading: {},\n }));\n\n context.registerComponent('content', DataGridDragDropContent);\n context.registerExtraColumn({\n id: 'drag-drop',\n body: DataGridDragDropBodyCell,\n position: 'start',\n order: 0,\n width: '37px',\n });\n context.registerComponent('row', DataGridDragDropRow);\n\n return {\n renderDragPreview: config.renderDragPreview,\n useDragDropStore,\n useDropLoadingStore,\n setDropLoading,\n clearDropLoading,\n handleDrop,\n };\n\n function setDropLoading(id: DataGridItemId, value: boolean) {\n useDropLoadingStore.setState((state) => ({ loading: { ...state.loading, [id]: value } }));\n }\n\n function clearDropLoading(id: DataGridItemId) {\n useDropLoadingStore.setState((state) => {\n const next = { ...state.loading };\n delete next[id];\n return { loading: next };\n });\n }\n\n function handleDrop(\n sourceRecord: DataGridRecord<TItem>,\n targetRecord: DataGridRecord<TItem> | undefined,\n ) {\n executeHandleDrop({\n sourceRecord,\n targetRecord,\n onDrop: (item, target) => config.onDrop({ ...context, item, target }),\n setDropLoading,\n clearDropLoading,\n });\n }\n },\n );\n}\n\n/** @internal Extracted for testability. */\nexport function executeHandleDrop<TItem extends DataGridItem>({\n sourceRecord,\n targetRecord,\n onDrop,\n setDropLoading,\n clearDropLoading,\n}: {\n sourceRecord: Pick<DataGridRecord<TItem>, 'id' | 'item'>;\n targetRecord: Pick<DataGridRecord<TItem>, 'item'> | undefined;\n onDrop: (item: TItem, target: TItem | null) => void | Promise<void>;\n setDropLoading: (id: DataGridItemId, value: boolean) => void;\n clearDropLoading: (id: DataGridItemId) => void;\n}) {\n const target = targetRecord?.item ?? null;\n let drop: void | Promise<void>;\n try {\n drop = onDrop(sourceRecord.item, target);\n } catch (error) {\n // Thrown out of the library's drop handler, it would leave the library mid-drag, so no\n // later drag starts; it is reported on its own instead.\n queueMicrotask(() => {\n throw error;\n });\n return;\n }\n\n if (drop instanceof Promise) {\n setDropLoading(sourceRecord.id, true);\n drop\n .catch(() => {\n // Swallow rejection — cleanup happens in finally\n })\n .finally(() => {\n clearDropLoading(sourceRecord.id);\n });\n }\n}\n"],"names":["DataGridDragDropBodyCell","grid","useDataGrid","record","useDataGridRecord","useDropLoadingStore","isLoading","s","jsx","cx","styles","IGNORE_CLICK_ATTRIBUTE","messages","Spinner","GripVerticalIcon","isDataGridItemId","value","isDataGridRecord","isRecord","readRecord","data","DataGridDragDropContent","children","contentRef","useRef","context","useDataGridContext","useDragDropStore","handleDrop","isDragging","isRootDropTarget","useEffect","combine","dropTargetForElements","monitorForElements","source","location","targets","rowTarget","t","rootTarget","dropEdge","extractClosestEdge","targetRecord","sourceRecord","buildClonedRowPreview","row","className","table","sourceTable","tbody","DataGridDragDropRow","rowRef","recordRef","useLatest","previewContainer","setPreviewContainer","useState","tableService","columns","tableLayout","renderDragPreview","isDropping","BodyCellContent","handleEl","draggable","nativeSetDragImage","setCustomNativeDragPreview","pointerOutsideOfPreview","container","flushSync","input","element","attachClosestEdge","jsxs","DataGridRecordProvider","TableRow","DataGridExtraBodyColumns","col","dynamicClassName","_a","bodyCellProps","resolveBodyCellProps","DataGridCell","createPortal","createDataGridDragDropPlugin","config","createDataGridPlugin","create","setDropLoading","clearDropLoading","id","state","next","executeHandleDrop","item","target","onDrop","drop","error"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,SAASA,KAA2B;AACzC,QAAMC,IAAOC,EAAA,GACPC,IAASC,EAAA,GAET,EAAE,qBAAAC,EAAA,IAAwBJ,EAAK,UAAqC,UAAU,GAE9EK,IAAYD,EAAoB,CAACE,MAAM,CAAC,CAACA,EAAE,QAAQJ,EAAO,EAAE,CAAC;AAEnE,SACE,gBAAAK;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAWC,EAAGC,EAAO,aAAaJ,KAAaI,EAAO,kBAAkB;AAAA,MAClE,CAACC,CAAsB,GAAG;AAAA,MAChC,oBAAiB;AAAA,MACjB,cAAYC,EAAS,SAAS;AAAA,MAE7B,UAAAN,IAAY,gBAAAE,EAACK,GAAA,CAAA,CAAQ,sBAAMC,GAAA,CAAA,CAAiB;AAAA,IAAA;AAAA,EAAA;AAGnD;ACtBA,SAASC,GAAiBC,GAAyC;AACjE,SAAO,OAAOA,KAAU,YAAY,OAAOA,KAAU;AACvD;AAEA,SAASC,GAAiBD,GAAyC;AACjE,SAAOE,EAASF,CAAK,KAAKD,GAAiBC,EAAM,EAAE,KAAKE,EAASF,EAAM,IAAI;AAC7E;AAGO,SAASG,EAAWC,GAAoE;AAC7F,SAAOH,GAAiBG,EAAK,MAAM,IAAIA,EAAK,SAAS;AACvD;ACCO,SAASC,GAAwB,EAAE,UAAAC,KAA0C;AAClF,QAAMC,IAAaC,EA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AE,GAAGD,EAAM,QAAA;AACxB,wBAAOC,EAAKF,CAAE,GACP,EAAE,SAASE,EAAA;AAAA,QACpB,CAAC;AAAA,MACH;AAEA,eAASjE,EACPgB,GACAD,GACA;AACA,QAAAmD,GAAkB;AAAA,UAChB,cAAAlD;AAAA,UACA,cAAAD;AAAA,UACA,QAAQ,CAACoD,GAAMC,MAAWV,EAAO,OAAO,EAAE,GAAG7D,GAAS,MAAAsE,GAAM,QAAAC,GAAQ;AAAA,UACpE,gBAAAP;AAAA,UACA,kBAAAC;AAAA,QAAA,CACD;AAAA,MACH;AAAA,IACF;AAAA,EAAA;AAEJ;AAGO,SAASI,GAA8C;AAAA,EAC5D,cAAAlD;AAAA,EACA,cAAAD;AAAA,EACA,QAAAsD;AAAA,EACA,gBAAAR;AAAA,EACA,kBAAAC;AACF,GAMG;AACD,QAAMM,KAASrD,KAAA,gBAAAA,EAAc,SAAQ;AACrC,MAAIuD;AACJ,MAAI;AACF,IAAAA,IAAOD,EAAOrD,EAAa,MAAMoD,CAAM;AAAA,EACzC,SAASG,GAAO;AAGd,mBAAe,MAAM;AACnB,YAAMA;AAAA,IACR,CAAC;AACD;AAAA,EACF;AAEA,EAAID,aAAgB,YAClBT,EAAe7C,EAAa,IAAI,EAAI,GACpCsD,EACG,MAAM,MAAM;AAAA,EAEb,CAAC,EACA,QAAQ,MAAM;AACb,IAAAR,EAAiB9C,EAAa,EAAE;AAAA,EAClC,CAAC;AAEP;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-tree.js","sources":["../../src/components/data-grid/plugins/table-tree/components/data-grid-table-tree-expand.tsx","../../src/components/data-grid/plugins/table-tree/components/data-grid-table-tree-body-cell-content.tsx","../../src/components/data-grid/plugins/table-tree/components/data-grid-table-tree-row.tsx","../../src/components/data-grid/plugins/table-tree/table-tree-helpers.ts","../../src/components/data-grid/plugins/table-tree/table-tree-plugin.tsx"],"sourcesContent":["import { ChevronDownIcon } from 'lucide-react';\nimport { Button } from '../../../../button/public.js';\nimport type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGrid } from '../../../services/core/data-grid-context';\nimport { IGNORE_CLICK_ATTRIBUTE } from '../../../services/table/ignore-row-click';\nimport { useDataGridRecord } from '../../../services/table/data-grid-record-context';\nimport type { DataGridTableTreePluginApi } from '../table-tree-types';\nimport styles from './data-grid-table-tree.module.css';\n\nexport function DataGridTableTreeExpand<TItem extends DataGridItem>() {\n const grid = useDataGrid<TItem>();\n const record = useDataGridRecord<TItem>();\n const treePlugin = grid.getPlugin<DataGridTableTreePluginApi<TItem>>('tableTree')!;\n const isExpanded = treePlugin.useIsExpanded(record.id);\n\n const iconClassName = isExpanded\n ? styles.expandIcon\n : `${styles.expandIcon} ${styles.expandIconCollapsed}`;\n\n return (\n <div className={styles.expand} {...{ [IGNORE_CLICK_ATTRIBUTE]: '' }}>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className={styles.toggle}\n icon={<ChevronDownIcon className={iconClassName} />}\n onClick={() => treePlugin.toggle(record.id)}\n />\n </div>\n );\n}\n","import type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGrid } from '../../../services/core/data-grid-context';\nimport { DataGridBodyCellContent } from '../../../services/table/components/data-grid-body-cell-content';\nimport { useDataGridRecord } from '../../../services/table/data-grid-record-context';\nimport { useTableService } from '../../../services/table/table-context';\nimport type { DataGridTableColumn } from '../../../services/table/table-types';\nimport type { DataGridTableTreePluginApi } from '../table-tree-types';\nimport { DataGridTableTreeExpand } from './data-grid-table-tree-expand';\nimport styles from './data-grid-table-tree.module.css';\n\ninterface DataGridTableTreeBodyCellContentProps<TItem extends DataGridItem> {\n column: DataGridTableColumn<TItem>;\n item: TItem;\n}\n\nexport function DataGridTableTreeBodyCellContent<TItem extends DataGridItem>({\n column,\n item,\n}: DataGridTableTreeBodyCellContentProps<TItem>) {\n const grid = useDataGrid<TItem>();\n const record = useDataGridRecord<TItem>();\n const tableService = useTableService<TItem>();\n const treePlugin = grid.getPlugin<DataGridTableTreePluginApi<TItem>>('tableTree')!;\n const visibleColumns = tableService.useVisibleColumns();\n const isFirstColumn = visibleColumns[0]?.id === column.id;\n const isExpandable = treePlugin.useIsExpandable(record);\n const level = treePlugin.useLevel(record.section);\n\n if ((isExpandable || level > 0) && isFirstColumn) {\n return (\n <div className={styles.treeCellContent}>\n {level > 0 && (\n <div\n className={styles.indentSpacer}\n style={{ inlineSize: `calc(var(--_data-grid-table-tree-indent) * ${level})` }}\n />\n )}\n {isExpandable && <DataGridTableTreeExpand />}\n <div className={styles.label}>\n <DataGridBodyCellContent column={column} item={item} />\n </div>\n </div>\n );\n }\n\n return <DataGridBodyCellContent column={column} item={item} />;\n}\n","import type { KeyboardEvent } from 'react';\nimport { TableRow } from '../../../../table/public.js';\nimport type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGridContext } from '../../../services/core/data-grid-context';\nimport type { DataGridRecord } from '../../../services/storage/storage-types';\nimport { DataGridCell } from '../../../services/table/components/data-grid-cell';\nimport { DataGridExtraBodyColumns } from '../../../services/table/components/data-grid-extra-body-columns';\nimport { DataGridTableRecords } from '../../../services/table/components/data-grid-table-records';\nimport { DataGridRecordProvider } from '../../../services/table/data-grid-record-context';\nimport { resolveBodyCellProps } from '../../../services/table/resolve-body-cell-props';\nimport type { DataGridTableColumn } from '../../../services/table/table-types';\nimport type { DataGridRowClickPluginApi } from '../../row-click/row-click-plugin';\nimport { getClickListener } from '../../row-click/row-click-utils';\nimport type { DataGridTableTreePluginApi } from '../table-tree-types';\nimport styles from './data-grid-table-tree.module.css';\n\ninterface DataGridTableTreeRowProps<TItem extends DataGridItem> {\n record: DataGridRecord<TItem>;\n}\n\nexport function DataGridTableTreeRow<TItem extends DataGridItem>({\n record,\n}: DataGridTableTreeRowProps<TItem>) {\n const context = useDataGridContext<TItem>();\n const tableService = context.table;\n const columns = tableService.useVisibleColumns();\n const tableLayout = tableService.useTableLayout();\n const treePlugin = context.plugins.getPlugin<DataGridTableTreePluginApi<TItem>>('tableTree')!;\n const rowClickApi = context.plugins.getPlugin<DataGridRowClickPluginApi<TItem>>('rowClick');\n const isExpanded = treePlugin.useIsExpanded(record.id);\n const childRecords = context.storage.getRecordsByParentId(record.id);\n\n const BodyCellContent = tableService.useComponent<{\n column: DataGridTableColumn<TItem>;\n item: TItem;\n }>('body-cell-content');\n\n // This row replaces the row-click plugin's, so it has to do what that row does when the plugin\n // is registered.\n const hasRowClick = !!rowClickApi;\n const onClick = hasRowClick ? getClickListener(record.item, () => rowClickApi?.click) : undefined;\n const onDblClick = hasRowClick\n ? getClickListener(record.item, () => rowClickApi?.dblclick)\n : undefined;\n const onKeyDown = hasRowClick\n ? (event: KeyboardEvent) => {\n if (event.key === 'Enter') {\n onClick?.(event);\n }\n }\n : undefined;\n\n return (\n <DataGridRecordProvider value={record}>\n <TableRow\n className={hasRowClick ? styles.clickableRow : undefined}\n tabIndex={hasRowClick ? 0 : undefined}\n onClick={onClick}\n onDoubleClick={onDblClick}\n onKeyDown={onKeyDown}\n >\n <DataGridExtraBodyColumns position=\"start\" />\n {columns.map((col) => {\n const dynamicClassName = col.getClassName?.(record.item);\n const bodyCellProps = resolveBodyCellProps(col, record.item, tableLayout);\n\n return (\n <DataGridCell<TItem>\n key={col.id}\n columnId={col.id}\n className={dynamicClassName}\n {...bodyCellProps}\n >\n <BodyCellContent column={col} item={record.item} />\n </DataGridCell>\n );\n })}\n <DataGridExtraBodyColumns position=\"end\" />\n </TableRow>\n {isExpanded && childRecords.length > 0 && (\n <DataGridTableRecords<TItem> records={childRecords} />\n )}\n </DataGridRecordProvider>\n );\n}\n","import type { DataGridItem } from '../../data-grid-types';\nimport { getItemKeyValue } from '../../services/storage/storage-helpers';\nimport type { DataGridDataKey, DataGridParentId } from '../../services/storage/storage-types';\n\nexport function createTreeDataFromFlattenedArray<TItem extends DataGridItem = DataGridItem>(\n items: TItem[],\n parentKey: DataGridDataKey<TItem>,\n): Map<DataGridParentId, TItem[]> {\n const results = new Map<DataGridParentId, TItem[]>();\n\n for (const item of items) {\n const parentId = getItemKeyValue(item, parentKey) ?? null;\n const group = results.get(parentId);\n if (group) {\n group.push(item);\n } else {\n results.set(parentId, [item]);\n }\n }\n\n return results;\n}\n","// Load-bearing: a plugin is rendered as a child of <DataGrid>, so a Server Component can import\n// and render it, and the component it returns calls hooks. This directive puts the banner on the\n// plugin's own entry chunk (dist/data-grid/<plugin>.js). client-boundaries.test.ts only scans a\n// component's top-level files, so scripts/verify-consumer.sh is what checks the built banner of\n// every plugin entry.\n'use client';\n\nimport type { ReactNode } from 'react';\nimport { create } from 'zustand';\n// `.js` on each relative type import: they land verbatim in the shipped declaration file, where\n// `moduleResolution: \"nodenext\"` rejects an extensionless one and every type from it goes untyped\n// (the `expandable` callback's `item` among them).\nimport type { DataGridItem } from '../../data-grid-types.js';\nimport type { LoadInstance } from '../../services/load/load-types.js';\nimport { createDataGridPlugin } from '../../services/plugins/plugins-helpers';\nimport type {\n DataGridItemId,\n DataGridRecord,\n DataGridSection,\n} from '../../services/storage/storage-types.js';\nimport { DataGridTableTreeBodyCellContent } from './components/data-grid-table-tree-body-cell-content';\nimport { DataGridTableTreeRow } from './components/data-grid-table-tree-row';\nimport { createTreeDataFromFlattenedArray } from './table-tree-helpers';\nimport type {\n DataGridTableTreePluginApi,\n DataGridTableTreePluginConfig,\n TableTreeConfigStore,\n TableTreePersistentState,\n TableTreeStore,\n} from './table-tree-types.js';\n\n// Ids from every visited page accumulate in the stored list (a row that is not\n// on screen cannot be collapsed), and rows deleted server-side never come back\n// to be collapsed either — so the list is bounded, dropping the oldest first.\nconst maxPersistedExpandedIds = 200;\n\nconst DataGridTableTreePluginRaw = createDataGridPlugin<\n DataGridItem,\n 'tableTree',\n DataGridTableTreePluginConfig,\n DataGridTableTreePluginApi\n>('tableTree', (context) => {\n const useTreeStore = create<TableTreeStore>(() => ({\n expandedIds: new Set(),\n }));\n\n const useConfigStore = create<TableTreeConfigStore>(() => ({\n parentKey: undefined,\n expandable: undefined,\n }));\n\n const resetIds = new Set<DataGridItemId>();\n // One-shot work queue, not observable state: ids restored from storage whose\n // children still need a lazy load. A restored id alone cannot tell whether the\n // row exists or is expandable, so the load waits until its record arrives.\n const restoredIds = new Set<DataGridItemId>();\n // Expand state is stored next to the page, filters and order, under whichever\n // backend the grid was configured with — except the URL: the list grows to the\n // persistence cap and keeps ids of rows deleted server-side, and every copied\n // URL would seed all of that into whichever grid opens the link.\n const persistentState = context.registerPersistentState<TableTreePersistentState>('tree', {\n schema: { expanded: 'object' },\n router: false,\n });\n\n context.hook('load:prepare', onBeforeLoad);\n context.hook('load:context', ({ loadContext }) => ({\n tree: { parentId: loadContext.tree?.parentId ?? null },\n }));\n context.hook('load:store', onLoadStore);\n context.registerComponent('row', DataGridTableTreeRow);\n context.registerComponent('body-cell-content', DataGridTableTreeBodyCellContent);\n\n return {\n useIsExpandable,\n useIsExpanded,\n useLevel: getLevel,\n toggle,\n isExpandable,\n onPropsChange,\n };\n\n function onPropsChange(props: DataGridTableTreePluginConfig) {\n useConfigStore.setState({\n parentKey: props.parentKey,\n expandable: props.expandable,\n });\n }\n\n function useIsExpandable(record: DataGridRecord): boolean {\n const expandable = useConfigStore((s) => s.expandable);\n const parentKey = useConfigStore((s) => s.parentKey);\n\n if (expandable) {\n return expandable(record.item);\n }\n\n if (parentKey) {\n return !!context.getSectionsByParentId(record.id).length;\n }\n\n return false;\n }\n\n function useIsExpanded(itemId: DataGridItemId): boolean {\n return useTreeStore((s) => s.expandedIds.has(itemId));\n }\n\n function getLevel(section: DataGridSection<DataGridItem>): number {\n const { parentId } = section;\n\n if (!parentId) {\n return 0;\n }\n\n const parentRecord = context.getRecord(parentId);\n return 1 + (parentRecord ? getLevel(parentRecord.section) : 0);\n }\n\n function toggle(itemId: DataGridItemId) {\n const state = useTreeStore.getState();\n const isCurrentlyExpanded = state.expandedIds.has(itemId);\n\n const newExpandedIds = new Set(state.expandedIds);\n if (isCurrentlyExpanded) {\n newExpandedIds.delete(itemId);\n } else {\n newExpandedIds.add(itemId);\n }\n useTreeStore.setState({ expandedIds: newExpandedIds });\n syncPersistent();\n\n if (!isCurrentlyExpanded) {\n triggerLoadChildren(itemId);\n }\n }\n\n // --- Private helpers ---\n\n function seedFromPersistent() {\n // Storage is user-editable, so the value is narrowed to the id type\n // instead of being trusted as-is, and capped the same way the write side\n // caps it — the plugin itself never stores more, so an oversized list is\n // external. The slice keeps the tail: storage order is oldest-first.\n const stored = persistentState.value?.expanded;\n const expanded = Array.isArray(stored)\n ? stored\n .filter((id): id is DataGridItemId => typeof id === 'string' || typeof id === 'number')\n .slice(-maxPersistedExpandedIds)\n : [];\n if (!expanded.length) {\n return;\n }\n\n const { parentKey } = useConfigStore.getState();\n const expandedIds = new Set(useTreeStore.getState().expandedIds);\n\n for (const id of expanded) {\n expandedIds.add(id);\n if (!parentKey) {\n restoredIds.add(id);\n }\n }\n\n useTreeStore.setState({ expandedIds });\n }\n\n function syncPersistent() {\n // Writes the whole object rather than a delta, because the accessor stores\n // whatever it is given: a partial write would drop the ids it omits. The\n // empty list is written too, so a fully collapsed hierarchy is stored as\n // such instead of as an absent entry. Set iterates in insertion order —\n // seeded ids first, fresh toggles last — so the slice drops the oldest.\n const expanded = [...useTreeStore.getState().expandedIds].slice(-maxPersistedExpandedIds);\n persistentState.setValue({ expanded });\n }\n\n // Drains the restored ids against sections that have just been stored,\n // starting a children load only for rows that actually arrived.\n function loadRestoredChildren(sections: DataGridSection<DataGridItem>[]) {\n if (!restoredIds.size) {\n return;\n }\n\n const { expandedIds } = useTreeStore.getState();\n\n for (const section of sections) {\n for (const record of section.records) {\n if (!restoredIds.delete(record.id) || !expandedIds.has(record.id)) {\n continue;\n }\n\n if (isExpandable(record)) {\n triggerLoadChildren(record.id);\n } else {\n // The row arrived and cannot be expanded, so the stored id is dropped\n // instead of leaving the row marked expanded with nothing under it.\n toggle(record.id);\n }\n }\n }\n }\n\n function triggerLoadChildren(parentId: DataGridItemId) {\n const loadInstance = findLoadInstance(parentId);\n if (loadInstance) {\n return;\n }\n\n const loadedSections = context.getSectionsByParentId(parentId);\n if (!loadedSections.length) {\n context.triggerLoad({ loadContext: { tree: { parentId } } });\n }\n }\n\n function findLoadInstance(parentId: DataGridItemId) {\n return context\n .getLoadInstances()\n .find((instance) => instance.loadContext.tree?.parentId === parentId);\n }\n\n function onBeforeLoad() {\n resetIds.clear();\n\n for (const section of context.getSections()) {\n for (const record of section.records) {\n if (useTreeStore.getState().expandedIds.has(record.id)) {\n resetIds.add(record.id);\n }\n }\n }\n }\n\n function onLoadStore(instance: LoadInstance<DataGridItem>) {\n const { parentKey } = useConfigStore.getState();\n const pageChanged = isPageChanged(instance.loadContext.pagination?.page);\n\n if (instance.refresh || pageChanged) {\n context.clearSections();\n }\n if (pageChanged) {\n // Two cases reach this branch, and the reseed serves both.\n //\n // A real page change: the in-memory expansion belongs to the page being\n // left, so it is reset, but the stored ids are kept and re-applied. A row\n // expanded on page 1 is expanded again when the user comes back to it, and\n // ids belonging to other pages sit in the set harmlessly, because children\n // load only for records that arrived and pass isExpandable.\n //\n // The very first load, where isPageChanged() is also true because no root\n // section exists yet: here the reset would erase the state just restored\n // from storage, so it has to be seeded again.\n useTreeStore.setState({ expandedIds: new Set() });\n seedFromPersistent();\n }\n\n const newSections: DataGridSection<DataGridItem>[] = [];\n\n if (parentKey) {\n const results = createTreeDataFromFlattenedArray(instance.processResult!.results, parentKey);\n\n for (const [parentId, items] of results) {\n const newSection = context.createSection(\n { loadContext: instance.loadContext, parentId },\n items,\n );\n newSections.push(newSection);\n }\n } else {\n const newSection = context.createSection(\n { loadContext: instance.loadContext, parentId: instance.loadContext.tree!.parentId },\n instance.processResult!.results,\n );\n newSections.push(newSection);\n }\n\n if (resetIds.size) {\n const { expandedIds } = useTreeStore.getState();\n const toLoadRecords = newSections.flatMap((section) => {\n return section.records.filter(\n (record) => resetIds.has(record.id) && isExpandable(record) && expandedIds.has(record.id),\n );\n });\n\n if (toLoadRecords.length) {\n for (const record of toLoadRecords) {\n resetIds.delete(record.id);\n triggerLoadChildren(record.id);\n }\n } else {\n resetIds.clear();\n }\n }\n\n loadRestoredChildren(newSections);\n\n return true;\n }\n\n function isPageChanged(newPage?: number) {\n const sections = context.getSectionsByParentId(null);\n return sections.length === 0\n ? true\n : (newPage ?? 1) !== (sections[0].loadContext.pagination?.page ?? 1);\n }\n\n function isExpandable(record: DataGridRecord): boolean {\n const { expandable, parentKey } = useConfigStore.getState();\n\n if (expandable) {\n return expandable(record.item);\n }\n\n if (parentKey) {\n return !!context.getSectionsByParentId(record.id).length;\n }\n\n return false;\n }\n});\n\n// The plugin is built for the base item type; the cast hands the consumer a generic component, so\n// `<DataGridTableTreePlugin<Category> parentKey=\"parent_id\" />` types `parentKey` and `expandable`\n// against the consumer's item.\nexport const DataGridTableTreePlugin = DataGridTableTreePluginRaw as <\n TItem extends DataGridItem = DataGridItem,\n>(\n props: DataGridTableTreePluginConfig<TItem>,\n) => ReactNode;\n"],"names":["DataGridTableTreeExpand","grid","useDataGrid","record","useDataGridRecord","treePlugin","iconClassName","styles","jsx","IGNORE_CLICK_ATTRIBUTE","Button","ChevronDownIcon","DataGridTableTreeBodyCellContent","column","item","tableService","useTableService","isFirstColumn","_a","isExpandable","level","jsxs","DataGridBodyCellContent","DataGridTableTreeRow","context","useDataGridContext","columns","tableLayout","rowClickApi","isExpanded","childRecords","BodyCellContent","hasRowClick","onClick","getClickListener","onDblClick","onKeyDown","event","DataGridRecordProvider","TableRow","DataGridExtraBodyColumns","col","dynamicClassName","bodyCellProps","resolveBodyCellProps","DataGridCell","DataGridTableRecords","createTreeDataFromFlattenedArray","items","parentKey","results","parentId","getItemKeyValue","group","DataGridTableTreePluginRaw","createDataGridPlugin","useTreeStore","create","useConfigStore","resetIds","restoredIds","persistentState","onBeforeLoad","loadContext","onLoadStore","useIsExpandable","useIsExpanded","getLevel","toggle","onPropsChange","props","expandable","s","itemId","section","parentRecord","state","isCurrentlyExpanded","newExpandedIds","syncPersistent","triggerLoadChildren","seedFromPersistent","stored","expanded","id","expandedIds","loadRestoredChildren","sections","findLoadInstance","instance","pageChanged","isPageChanged","newSections","newSection","toLoadRecords","newPage","DataGridTableTreePlugin"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AASO,SAASA,KAAsD;AACpE,QAAMC,IAAOC,EAAA,GACPC,IAASC,EAAA,GACTC,IAAaJ,EAAK,UAA6C,WAAW,GAG1EK,IAFaD,EAAW,cAAcF,EAAO,EAAE,IAGjDI,EAAO,aACP,GAAGA,EAAO,UAAU,IAAIA,EAAO,mBAAmB;AAEtD,SACE,gBAAAC,EAAC,OAAA,EAAI,WAAWD,EAAO,QAAc,CAACE,CAAsB,GAAG,IAC7D,UAAA,gBAAAD;AAAA,IAACE;AAAA,IAAA;AAAA,MACC,SAAQ;AAAA,MACR,MAAK;AAAA,MACL,WAAWH,EAAO;AAAA,MAClB,MAAM,gBAAAC,EAACG,GAAA,EAAgB,WAAWL,EAAA,CAAe;AAAA,MACjD,SAAS,MAAMD,EAAW,OAAOF,EAAO,EAAE;AAAA,IAAA;AAAA,EAAA,GAE9C;AAEJ;ACfO,SAASS,GAA6D;AAAA,EAC3E,QAAAC;AAAA,EACA,MAAAC;AACF,GAAiD;;AAC/C,QAAMb,IAAOC,EAAA,GACPC,IAASC,EAAA,GACTW,IAAeC,EAAA,GACfX,IAAaJ,EAAK,UAA6C,WAAW,GAE1EgB,MAAgBC,IADCH,EAAa,kBAAA,EACC,CAAC,MAAhB,gBAAAG,EAAmB,QAAOL,EAAO,IACjDM,IAAed,EAAW,gBAAgBF,CAAM,GAChDiB,IAAQf,EAAW,SAASF,EAAO,OAAO;AAEhD,UAAKgB,KAAgBC,IAAQ,MAAMH,IAE/B,gBAAAI,EAAC,OAAA,EAAI,WAAWd,EAAO,iBACpB,UAAA;AAAA,IAAAa,IAAQ,KACP,gBAAAZ;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,WAAWD,EAAO;AAAA,QAClB,OAAO,EAAE,YAAY,8CAA8Ca,CAAK,IAA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plugins/table-tree/components/data-grid-table-tree-expand.tsx","../../src/components/data-grid/plugins/table-tree/components/data-grid-table-tree-body-cell-content.tsx","../../src/components/data-grid/plugins/table-tree/components/data-grid-table-tree-row.tsx","../../src/components/data-grid/plugins/table-tree/table-tree-helpers.ts","../../src/components/data-grid/plugins/table-tree/table-tree-plugin.tsx"],"sourcesContent":["import { ChevronDownIcon } from 'lucide-react';\nimport { Button } from '../../../../button/public.js';\nimport type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGrid } from '../../../services/core/data-grid-context';\nimport { IGNORE_CLICK_ATTRIBUTE } from '../../../services/table/ignore-row-click';\nimport { useDataGridRecord } from '../../../services/table/data-grid-record-context';\nimport type { DataGridTableTreePluginApi } from '../table-tree-types';\nimport styles from './data-grid-table-tree.module.css';\n\nexport function DataGridTableTreeExpand<TItem extends DataGridItem>() {\n const grid = useDataGrid<TItem>();\n const record = useDataGridRecord<TItem>();\n const treePlugin = grid.getPlugin<DataGridTableTreePluginApi<TItem>>('tableTree')!;\n const isExpanded = treePlugin.useIsExpanded(record.id);\n\n const iconClassName = isExpanded\n ? styles.expandIcon\n : `${styles.expandIcon} ${styles.expandIconCollapsed}`;\n\n return (\n <div className={styles.expand} {...{ [IGNORE_CLICK_ATTRIBUTE]: '' }}>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className={styles.toggle}\n icon={<ChevronDownIcon className={iconClassName} />}\n onClick={() => treePlugin.toggle(record.id)}\n />\n </div>\n );\n}\n","import type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGrid } from '../../../services/core/data-grid-context';\nimport { DataGridBodyCellContent } from '../../../services/table/components/data-grid-body-cell-content';\nimport { useDataGridRecord } from '../../../services/table/data-grid-record-context';\nimport { useTableService } from '../../../services/table/table-context';\nimport type { DataGridTableColumn } from '../../../services/table/table-types';\nimport type { DataGridTableTreePluginApi } from '../table-tree-types';\nimport { DataGridTableTreeExpand } from './data-grid-table-tree-expand';\nimport styles from './data-grid-table-tree.module.css';\n\ninterface DataGridTableTreeBodyCellContentProps<TItem extends DataGridItem> {\n column: DataGridTableColumn<TItem>;\n item: TItem;\n}\n\nexport function DataGridTableTreeBodyCellContent<TItem extends DataGridItem>({\n column,\n item,\n}: DataGridTableTreeBodyCellContentProps<TItem>) {\n const grid = useDataGrid<TItem>();\n const record = useDataGridRecord<TItem>();\n const tableService = useTableService<TItem>();\n const treePlugin = grid.getPlugin<DataGridTableTreePluginApi<TItem>>('tableTree')!;\n const visibleColumns = tableService.useVisibleColumns();\n const isFirstColumn = visibleColumns[0]?.id === column.id;\n const isExpandable = treePlugin.useIsExpandable(record);\n const level = treePlugin.useLevel(record.section);\n\n if ((isExpandable || level > 0) && isFirstColumn) {\n return (\n <div className={styles.treeCellContent}>\n {level > 0 && (\n <div\n className={styles.indentSpacer}\n style={{ inlineSize: `calc(var(--_data-grid-table-tree-indent) * ${level})` }}\n />\n )}\n {isExpandable && <DataGridTableTreeExpand />}\n <div className={styles.label}>\n <DataGridBodyCellContent column={column} item={item} />\n </div>\n </div>\n );\n }\n\n return <DataGridBodyCellContent column={column} item={item} />;\n}\n","import type { KeyboardEvent } from 'react';\nimport { TableRow } from '../../../../table/public.js';\nimport type { DataGridItem } from '../../../data-grid-types';\nimport { useDataGridContext } from '../../../services/core/data-grid-context';\nimport type { DataGridRecord } from '../../../services/storage/storage-types';\nimport { DataGridCell } from '../../../services/table/components/data-grid-cell';\nimport { DataGridExtraBodyColumns } from '../../../services/table/components/data-grid-extra-body-columns';\nimport { DataGridTableRecords } from '../../../services/table/components/data-grid-table-records';\nimport { DataGridRecordProvider } from '../../../services/table/data-grid-record-context';\nimport { resolveBodyCellProps } from '../../../services/table/resolve-body-cell-props';\nimport type { DataGridTableColumn } from '../../../services/table/table-types';\nimport type { DataGridRowClickPluginApi } from '../../row-click/row-click-plugin';\nimport { getClickListener } from '../../row-click/row-click-utils';\nimport type { DataGridTableTreePluginApi } from '../table-tree-types';\nimport styles from './data-grid-table-tree.module.css';\n\ninterface DataGridTableTreeRowProps<TItem extends DataGridItem> {\n record: DataGridRecord<TItem>;\n}\n\nexport function DataGridTableTreeRow<TItem extends DataGridItem>({\n record,\n}: DataGridTableTreeRowProps<TItem>) {\n const context = useDataGridContext<TItem>();\n const tableService = context.table;\n const columns = tableService.useVisibleColumns();\n const tableLayout = tableService.useTableLayout();\n const treePlugin = context.plugins.getPlugin<DataGridTableTreePluginApi<TItem>>('tableTree')!;\n const rowClickApi = context.plugins.getPlugin<DataGridRowClickPluginApi<TItem>>('rowClick');\n const isExpanded = treePlugin.useIsExpanded(record.id);\n const childRecords = context.storage.getRecordsByParentId(record.id);\n\n const BodyCellContent = tableService.useComponent<{\n column: DataGridTableColumn<TItem>;\n item: TItem;\n }>('body-cell-content');\n\n // This row replaces the row-click plugin's, so it has to do what that row does when the plugin\n // is registered.\n const hasRowClick = !!rowClickApi;\n const onClick = hasRowClick ? getClickListener(record.item, () => rowClickApi?.click) : undefined;\n const onDblClick = hasRowClick\n ? getClickListener(record.item, () => rowClickApi?.dblclick)\n : undefined;\n const onKeyDown = hasRowClick\n ? (event: KeyboardEvent) => {\n if (event.key === 'Enter') {\n onClick?.(event);\n }\n }\n : undefined;\n\n return (\n <DataGridRecordProvider value={record}>\n <TableRow\n className={hasRowClick ? styles.clickableRow : undefined}\n tabIndex={hasRowClick ? 0 : undefined}\n onClick={onClick}\n onDoubleClick={onDblClick}\n onKeyDown={onKeyDown}\n >\n <DataGridExtraBodyColumns position=\"start\" />\n {columns.map((col) => {\n const dynamicClassName = col.getClassName?.(record.item);\n const bodyCellProps = resolveBodyCellProps(col, record.item, tableLayout);\n\n return (\n <DataGridCell<TItem>\n key={col.id}\n columnId={col.id}\n className={dynamicClassName}\n {...bodyCellProps}\n >\n <BodyCellContent column={col} item={record.item} />\n </DataGridCell>\n );\n })}\n <DataGridExtraBodyColumns position=\"end\" />\n </TableRow>\n {isExpanded && childRecords.length > 0 && (\n <DataGridTableRecords<TItem> records={childRecords} />\n )}\n </DataGridRecordProvider>\n );\n}\n","import type { DataGridItem } from '../../data-grid-types';\nimport { getItemKeyValue } from '../../services/storage/storage-helpers';\nimport type { DataGridDataKey, DataGridParentId } from '../../services/storage/storage-types';\n\nexport function createTreeDataFromFlattenedArray<TItem extends DataGridItem = DataGridItem>(\n items: TItem[],\n parentKey: DataGridDataKey<TItem>,\n): Map<DataGridParentId, TItem[]> {\n const results = new Map<DataGridParentId, TItem[]>();\n\n for (const item of items) {\n const parentId = getItemKeyValue(item, parentKey) ?? null;\n const group = results.get(parentId);\n if (group) {\n group.push(item);\n } else {\n results.set(parentId, [item]);\n }\n }\n\n return results;\n}\n","// Load-bearing: a plugin is rendered as a child of <DataGrid>, so a Server Component can import\n// and render it, and the component it returns calls hooks. This directive puts the banner on the\n// plugin's own entry chunk (dist/data-grid/<plugin>.js). client-boundaries.test.ts only scans a\n// component's top-level files, so scripts/verify-consumer.sh is what checks the built banner of\n// every plugin entry.\n'use client';\n\nimport type { ReactNode } from 'react';\nimport { create } from 'zustand';\n// `.js` on each relative type import: they land verbatim in the shipped declaration file, where\n// `moduleResolution: \"nodenext\"` rejects an extensionless one and every type from it goes untyped\n// (the `expandable` callback's `item` among them).\nimport type { DataGridItem } from '../../data-grid-types.js';\nimport type { LoadInstance } from '../../services/load/load-types.js';\nimport { createDataGridPlugin } from '../../services/plugins/plugins-helpers';\nimport type {\n DataGridItemId,\n DataGridRecord,\n DataGridSection,\n} from '../../services/storage/storage-types.js';\nimport { DataGridTableTreeBodyCellContent } from './components/data-grid-table-tree-body-cell-content';\nimport { DataGridTableTreeRow } from './components/data-grid-table-tree-row';\nimport { createTreeDataFromFlattenedArray } from './table-tree-helpers';\nimport type {\n DataGridTableTreePluginApi,\n DataGridTableTreePluginConfig,\n TableTreeConfigStore,\n TableTreePersistentState,\n TableTreeStore,\n} from './table-tree-types.js';\n\n// Ids from every visited page accumulate in the stored list (a row that is not\n// on screen cannot be collapsed), and rows deleted server-side never come back\n// to be collapsed either — so the list is bounded, dropping the oldest first.\nconst maxPersistedExpandedIds = 200;\n\nconst DataGridTableTreePluginRaw = createDataGridPlugin<\n DataGridItem,\n 'tableTree',\n DataGridTableTreePluginConfig,\n DataGridTableTreePluginApi\n>('tableTree', (context) => {\n const useTreeStore = create<TableTreeStore>(() => ({\n expandedIds: new Set(),\n }));\n\n const useConfigStore = create<TableTreeConfigStore>(() => ({\n parentKey: undefined,\n expandable: undefined,\n }));\n\n const resetIds = new Set<DataGridItemId>();\n // One-shot work queue, not observable state: ids restored from storage whose\n // children still need a lazy load. A restored id alone cannot tell whether the\n // row exists or is expandable, so the load waits until its record arrives.\n const restoredIds = new Set<DataGridItemId>();\n // Expand state is stored next to the page, filters and order, under whichever\n // backend the grid was configured with — except the URL: the list grows to the\n // persistence cap and keeps ids of rows deleted server-side, and every copied\n // URL would seed all of that into whichever grid opens the link.\n const persistentState = context.registerPersistentState<TableTreePersistentState>('tree', {\n schema: { expanded: 'object' },\n router: false,\n });\n\n context.hook('load:prepare', onBeforeLoad);\n context.hook('load:context', ({ loadContext }) => ({\n tree: { parentId: loadContext.tree?.parentId ?? null },\n }));\n context.hook('load:store', onLoadStore);\n context.registerComponent('row', DataGridTableTreeRow);\n context.registerComponent('body-cell-content', DataGridTableTreeBodyCellContent);\n\n return {\n useIsExpandable,\n useIsExpanded,\n useLevel: getLevel,\n toggle,\n isExpandable,\n onPropsChange,\n };\n\n function onPropsChange(props: DataGridTableTreePluginConfig) {\n useConfigStore.setState({\n parentKey: props.parentKey,\n expandable: props.expandable,\n });\n }\n\n function useIsExpandable(record: DataGridRecord): boolean {\n const expandable = useConfigStore((s) => s.expandable);\n const parentKey = useConfigStore((s) => s.parentKey);\n\n if (expandable) {\n return expandable(record.item);\n }\n\n if (parentKey) {\n return !!context.getSectionsByParentId(record.id).length;\n }\n\n return false;\n }\n\n function useIsExpanded(itemId: DataGridItemId): boolean {\n return useTreeStore((s) => s.expandedIds.has(itemId));\n }\n\n function getLevel(section: DataGridSection<DataGridItem>): number {\n const { parentId } = section;\n\n if (parentId === null) {\n return 0;\n }\n\n const parentRecord = context.getRecord(parentId);\n return 1 + (parentRecord ? getLevel(parentRecord.section) : 0);\n }\n\n function toggle(itemId: DataGridItemId) {\n const state = useTreeStore.getState();\n const isCurrentlyExpanded = state.expandedIds.has(itemId);\n\n const newExpandedIds = new Set(state.expandedIds);\n if (isCurrentlyExpanded) {\n newExpandedIds.delete(itemId);\n } else {\n newExpandedIds.add(itemId);\n }\n useTreeStore.setState({ expandedIds: newExpandedIds });\n syncPersistent();\n\n if (!isCurrentlyExpanded) {\n triggerLoadChildren(itemId);\n }\n }\n\n // --- Private helpers ---\n\n function seedFromPersistent() {\n // Storage is user-editable, so the value is narrowed to the id type\n // instead of being trusted as-is, and capped the same way the write side\n // caps it — the plugin itself never stores more, so an oversized list is\n // external. The slice keeps the tail: storage order is oldest-first.\n const stored = persistentState.value?.expanded;\n const expanded = Array.isArray(stored)\n ? stored\n .filter((id): id is DataGridItemId => typeof id === 'string' || typeof id === 'number')\n .slice(-maxPersistedExpandedIds)\n : [];\n if (!expanded.length) {\n return;\n }\n\n const { parentKey } = useConfigStore.getState();\n const expandedIds = new Set(useTreeStore.getState().expandedIds);\n\n for (const id of expanded) {\n expandedIds.add(id);\n if (!parentKey) {\n restoredIds.add(id);\n }\n }\n\n useTreeStore.setState({ expandedIds });\n }\n\n function syncPersistent() {\n // Writes the whole object rather than a delta, because the accessor stores\n // whatever it is given: a partial write would drop the ids it omits. The\n // empty list is written too, so a fully collapsed hierarchy is stored as\n // such instead of as an absent entry. Set iterates in insertion order —\n // seeded ids first, fresh toggles last — so the slice drops the oldest.\n const expanded = [...useTreeStore.getState().expandedIds].slice(-maxPersistedExpandedIds);\n persistentState.setValue({ expanded });\n }\n\n // Drains the restored ids against sections that have just been stored,\n // starting a children load only for rows that actually arrived.\n function loadRestoredChildren(sections: DataGridSection<DataGridItem>[]) {\n if (!restoredIds.size) {\n return;\n }\n\n const { expandedIds } = useTreeStore.getState();\n\n for (const section of sections) {\n for (const record of section.records) {\n if (!restoredIds.delete(record.id) || !expandedIds.has(record.id)) {\n continue;\n }\n\n if (isExpandable(record)) {\n triggerLoadChildren(record.id);\n } else {\n // The row arrived and cannot be expanded, so the stored id is dropped\n // instead of leaving the row marked expanded with nothing under it.\n toggle(record.id);\n }\n }\n }\n }\n\n function triggerLoadChildren(parentId: DataGridItemId) {\n const loadInstance = findLoadInstance(parentId);\n if (loadInstance) {\n return;\n }\n\n const loadedSections = context.getSectionsByParentId(parentId);\n if (!loadedSections.length) {\n context.triggerLoad({ loadContext: { tree: { parentId } } });\n }\n }\n\n function findLoadInstance(parentId: DataGridItemId) {\n return context\n .getLoadInstances()\n .find((instance) => instance.loadContext.tree?.parentId === parentId);\n }\n\n function onBeforeLoad() {\n resetIds.clear();\n\n for (const section of context.getSections()) {\n for (const record of section.records) {\n if (useTreeStore.getState().expandedIds.has(record.id)) {\n resetIds.add(record.id);\n }\n }\n }\n }\n\n function onLoadStore(instance: LoadInstance<DataGridItem>) {\n const { parentKey } = useConfigStore.getState();\n const pageChanged = isPageChanged(instance.loadContext.pagination?.page);\n\n if (instance.refresh || pageChanged) {\n context.clearSections();\n }\n if (pageChanged) {\n // Two cases reach this branch, and the reseed serves both.\n //\n // A real page change: the in-memory expansion belongs to the page being\n // left, so it is reset, but the stored ids are kept and re-applied. A row\n // expanded on page 1 is expanded again when the user comes back to it, and\n // ids belonging to other pages sit in the set harmlessly, because children\n // load only for records that arrived and pass isExpandable.\n //\n // The very first load, where isPageChanged() is also true because no root\n // section exists yet: here the reset would erase the state just restored\n // from storage, so it has to be seeded again.\n useTreeStore.setState({ expandedIds: new Set() });\n seedFromPersistent();\n }\n\n const newSections: DataGridSection<DataGridItem>[] = [];\n\n if (parentKey) {\n const results = createTreeDataFromFlattenedArray(instance.processResult!.results, parentKey);\n\n for (const [parentId, items] of results) {\n const newSection = context.createSection(\n { loadContext: instance.loadContext, parentId },\n items,\n );\n newSections.push(newSection);\n }\n } else {\n const newSection = context.createSection(\n { loadContext: instance.loadContext, parentId: instance.loadContext.tree!.parentId },\n instance.processResult!.results,\n );\n newSections.push(newSection);\n }\n\n if (resetIds.size) {\n const { expandedIds } = useTreeStore.getState();\n const toLoadRecords = newSections.flatMap((section) => {\n return section.records.filter(\n (record) => resetIds.has(record.id) && isExpandable(record) && expandedIds.has(record.id),\n );\n });\n\n if (toLoadRecords.length) {\n for (const record of toLoadRecords) {\n resetIds.delete(record.id);\n triggerLoadChildren(record.id);\n }\n } else {\n resetIds.clear();\n }\n }\n\n loadRestoredChildren(newSections);\n\n return true;\n }\n\n function isPageChanged(newPage?: number) {\n const sections = context.getSectionsByParentId(null);\n return sections.length === 0\n ? true\n : (newPage ?? 1) !== (sections[0].loadContext.pagination?.page ?? 1);\n }\n\n function isExpandable(record: DataGridRecord): boolean {\n const { expandable, parentKey } = useConfigStore.getState();\n\n if (expandable) {\n return expandable(record.item);\n }\n\n if (parentKey) {\n return !!context.getSectionsByParentId(record.id).length;\n }\n\n return false;\n }\n});\n\n// The plugin is built for the base item type; the cast hands the consumer a generic component, so\n// `<DataGridTableTreePlugin<Category> parentKey=\"parent_id\" />` types `parentKey` and `expandable`\n// against the consumer's item.\nexport const DataGridTableTreePlugin = DataGridTableTreePluginRaw as <\n TItem extends DataGridItem = DataGridItem,\n>(\n props: DataGridTableTreePluginConfig<TItem>,\n) => ReactNode;\n"],"names":["DataGridTableTreeExpand","grid","useDataGrid","record","useDataGridRecord","treePlugin","iconClassName","styles","jsx","IGNORE_CLICK_ATTRIBUTE","Button","ChevronDownIcon","DataGridTableTreeBodyCellContent","column","item","tableService","useTableService","isFirstColumn","_a","isExpandable","level","jsxs","DataGridBodyCellContent","DataGridTableTreeRow","context","useDataGridContext","columns","tableLayout","rowClickApi","isExpanded","childRecords","BodyCellContent","hasRowClick","onClick","getClickListener","onDblClick","onKeyDown","event","DataGridRecordProvider","TableRow","DataGridExtraBodyColumns","col","dynamicClassName","bodyCellProps","resolveBodyCellProps","DataGridCell","DataGridTableRecords","createTreeDataFromFlattenedArray","items","parentKey","results","parentId","getItemKeyValue","group","DataGridTableTreePluginRaw","createDataGridPlugin","useTreeStore","create","useConfigStore","resetIds","restoredIds","persistentState","onBeforeLoad","loadContext","onLoadStore","useIsExpandable","useIsExpanded","getLevel","toggle","onPropsChange","props","expandable","s","itemId","section","parentRecord","state","isCurrentlyExpanded","newExpandedIds","syncPersistent","triggerLoadChildren","seedFromPersistent","stored","expanded","id","expandedIds","loadRestoredChildren","sections","findLoadInstance","instance","pageChanged","isPageChanged","newSections","newSection","toLoadRecords","newPage","DataGridTableTreePlugin"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AASO,SAASA,KAAsD;AACpE,QAAMC,IAAOC,EAAA,GACPC,IAASC,EAAA,GACTC,IAAaJ,EAAK,UAA6C,WAAW,GAG1EK,IAFaD,EAAW,cAAcF,EAAO,EAAE,IAGjDI,EAAO,aACP,GAAGA,EAAO,UAAU,IAAIA,EAAO,mBAAmB;AAEtD,SACE,gBAAAC,EAAC,OAAA,EAAI,WAAWD,EAAO,QAAc,CAACE,CAAsB,GAAG,IAC7D,UAAA,gBAAAD;AAAA,IAACE;AAAA,IAAA;AAAA,MACC,SAAQ;AAAA,MACR,MAAK;AAAA,MACL,WAAWH,EAAO;AAAA,MAClB,MAAM,gBAAAC,EAACG,GAAA,EAAgB,WAAWL,EAAA,CAAe;AAAA,MACjD,SAAS,MAAMD,EAAW,OAAOF,EAAO,EAAE;AAAA,IAAA;AAAA,EAAA,GAE9C;AAEJ;ACfO,SAASS,GAA6D;AAAA,EAC3E,QAAAC;AAAA,EACA,MAAAC;AACF,GAAiD;;AAC/C,QAAMb,IAAOC,EAAA,GACPC,IAASC,EAAA,GACTW,IAAeC,EAAA,GACfX,IAAaJ,EAAK,UAA6C,WAAW,GAE1EgB,MAAgBC,IADCH,EAAa,kBAAA,EACC,CAAC,MAAhB,gBAAAG,EAAmB,QAAOL,EAAO,IACjDM,IAAed,EAAW,gBAAgBF,CAAM,GAChDiB,IAAQf,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AM,EAAE,YAAAoE,GAAY,WAAAtB,MAAcS,EAAe,SAAA;AAEjD,WAAIa,IACKA,EAAWpE,EAAO,IAAI,IAG3B8C,IACK,CAAC,CAACzB,EAAQ,sBAAsBrB,EAAO,EAAE,EAAE,SAG7C;AAAA,EACT;AACF,CAAC,GAKY6F,KAA0B1C;"}
|
package/dist/docs/data-grid.md
CHANGED
|
@@ -826,7 +826,7 @@ need nothing installed either.
|
|
|
826
826
|
|
|
827
827
|
| Option | Type | Default |
|
|
828
828
|
|--------|------|---------|
|
|
829
|
-
| `filename` | `string \| () => string` | `Report`; the extension
|
|
829
|
+
| `filename` | `string \| () => string` | `Report`; a string gets the extension when it is missing, a function's result is used as is |
|
|
830
830
|
| `includeHeaders` | `boolean` | `true` |
|
|
831
831
|
| `delimiter` | `string` | `,` (CSV) |
|
|
832
832
|
| `sheetName` | `string` | `Sheet` (Excel) |
|
|
@@ -1107,7 +1107,8 @@ whole grid. A drop outside the grid does nothing.
|
|
|
1107
1107
|
|
|
1108
1108
|
When `onDrop` returns a promise, the handle of the dragged row shows a spinner until it settles.
|
|
1109
1109
|
A rejection is swallowed and the spinner stops: handle errors inside `onDrop`. A callback that
|
|
1110
|
-
returns anything else is done at once.
|
|
1110
|
+
returns anything else is done at once. One that throws has its error reported as uncaught, on
|
|
1111
|
+
its own, and the next drag works as usual.
|
|
1111
1112
|
|
|
1112
1113
|
The handle, which fills its cell, is marked `data-grid-row-ignore-click`; the rest of the cell
|
|
1113
1114
|
around it is not, since there is none. Only this entry loads the drag
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# Grid
|
|
2
|
+
|
|
3
|
+
## When to use
|
|
4
|
+
|
|
5
|
+
Use `Grid` for an ordered group of blocks whose widths follow size classes. Use one `Grid` per group. Each `GridItem` declares a unique `layoutId`, a size class, and an optional height class. The solver keeps DOM, focus, and segment order equal to input order.
|
|
6
|
+
|
|
7
|
+
## When not to use
|
|
8
|
+
|
|
9
|
+
Use a plain CSS grid when callers already know exact spans or need manual placement. Grid does not render dashboard data or support drag and resize editing.
|
|
10
|
+
|
|
11
|
+
## Props
|
|
12
|
+
|
|
13
|
+
| Component | Prop | Meaning |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| Grid | `config` | `GridConfig` shared with the generated step CSS. Defaults to `defaultGridConfig`. |
|
|
16
|
+
| Grid | `flexible` | `false` (default): every item takes its size class's preferred span. `true`: spans may move inside each class's range to fill rows. |
|
|
17
|
+
| Grid | `className`, div props | Applied to the named container wrapper. |
|
|
18
|
+
| GridItem | `layoutId` | Required placement identity, unique within this Grid. Separate from HTML `id`. |
|
|
19
|
+
| GridItem | `size` | `small`, `medium`, or `large`. |
|
|
20
|
+
| GridItem | `height` | `low` (default, one row track) or `high` (two row tracks). |
|
|
21
|
+
| GridItem | `className`, div props | Applied to the item. Caller style is preserved; placement variables win on conflict. |
|
|
22
|
+
|
|
23
|
+
`Grid` accepts direct `GridItem` elements, arrays, and empty conditional entries (`null`, `undefined`, booleans). Fragments, wrappers, portals, and text throw. Keep a stable `layoutId` when content changes: a `key` on a GridItem is ignored, because Grid keys items by `layoutId`, and changing `layoutId` is what remounts an item. The solver is pure and runs during rendering, so the server and client get the same layout.
|
|
24
|
+
|
|
25
|
+
## Names
|
|
26
|
+
|
|
27
|
+
The step CSS is a global stylesheet matched by attribute, so its selectors and the container keep the `fx-` prefix: `data-fx-grid`, `data-fx-grid-item`, `data-fx-grid-flexible`, and the `fx-grid` container name. An unprefixed `data-grid` is already in use by other libraries (react-grid-layout puts `data-grid` on its children), and a global rule that matched it would style foreign markup. The custom properties need no prefix: Grid sets `--_grid-columns` and the per-step `--_grid-col-<step>` / `--_grid-row-<step>` only on its own elements. `--grid-gap` and `--grid-row-height` are consumer hooks that Grid only reads, and they inherit like any custom property, so a value declared on any ancestor, `:root` included, applies to every Grid below it.
|
|
28
|
+
|
|
29
|
+
## Layout and styling
|
|
30
|
+
|
|
31
|
+
The default config has 12 columns and four container steps: base 0px, sm 480px, md 768px, lg 1200px. Each size class has a preferred span per step, and with the default config every span is 12, 6 or 3 columns:
|
|
32
|
+
|
|
33
|
+
| Size | base | sm | md | lg |
|
|
34
|
+
| --- | --- | --- | --- | --- |
|
|
35
|
+
| `small` | 6 | 6 | 3 | 3 |
|
|
36
|
+
| `medium` | 12 | 6 | 6 | 6 |
|
|
37
|
+
| `large` | 12 | 12 | 12 | 12 |
|
|
38
|
+
|
|
39
|
+
By default a Grid places exactly these spans; a row they do not fill keeps its hole at the inline end, so `medium` + `small` at lg is 6 + 3 with three empty columns. A `flexible` Grid lets each span move inside its class's range in `defaultGridConfig` (at lg `small` 2..4, `medium` 4..8, `large` 7..12) to fill rows, so the same pair becomes 8 + 4. Flexible is set per Grid, that is per group. In both modes the solver minimizes internal holes, final holes, width deviation, and band count in that order, never reorders items, and leaves empty columns at the inline end.
|
|
40
|
+
|
|
41
|
+
### Row tracks and heights
|
|
42
|
+
|
|
43
|
+
Heights are fixed by the model. Row tracks have the size of the config's `rowHeight`, a positive length in px, rem or em (`10rem` in the default config): a `low` item is one track, a `high` item is two tracks and the row gap between them, so a high item is exactly as tall as two stacked lows with their gap. A two-track band holds high items and pairs of adjacent lows stacked in one column beside them; a low never stretches over two tracks, and a low that finds no partner beside a high goes to the next band. With the default config a high `medium` takes two smalls stacked beside it from sm on, and four smalls as two stacks at md and lg (`6 + 3 + 3`). An item is a one-column grid, so a single child (a Card) fills it.
|
|
44
|
+
|
|
45
|
+
### Scrolling and clipping
|
|
46
|
+
|
|
47
|
+
Content taller than its item scrolls inside the item and never overlaps a neighbour. The item is a scroll container, so it also clips what a child draws outside its own box (an outer shadow or outline). The default kit Card draws neither and its focus ring is inset; the `panel` Card's outer shadow and the forced-colors focus outline of an interactive Card are clipped at the item edge.
|
|
48
|
+
|
|
49
|
+
### Track override
|
|
50
|
+
|
|
51
|
+
The track size and the spans of the default config are not final; the config is the single place to change them (`rowHeight` for the track), and `--grid-row-height` overrides the track at runtime.
|
|
52
|
+
|
|
53
|
+
### Direction
|
|
54
|
+
|
|
55
|
+
Direction follows CSS grid lines, so `dir="rtl"` mirrors the layout without changing DOM order.
|
|
56
|
+
|
|
57
|
+
The wrapper is the named inline-size container. Size containment gives it no width of its own content, so it needs a width from outside: a block in normal flow or a stretched flex or grid child gets one; inside a shrink-to-fit box (an inline-block, a float, a `max-content` track, a flex item that does not grow) give the Grid a width. The grid element carries `data-fx-grid="<config.name>"`; each item carries `data-fx-grid-item`; a flexible Grid's grid element also carries `data-fx-grid-flexible`. The default generated CSS ships with the component, and nested Grids query their nearest `fx-grid` wrapper. Print uses block flow and a token gap.
|
|
58
|
+
|
|
59
|
+
## Config
|
|
60
|
+
|
|
61
|
+
A custom config starts from a copy of the shipped default config, `@gears-frontx/ui-kit/grid-default-config.json` in the install (`node_modules/@gears-frontx/ui-kit/dist/grid-default-config.json`), written as JSON:
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"name": "report",
|
|
66
|
+
"columns": 8,
|
|
67
|
+
"rowHeight": "120px",
|
|
68
|
+
"steps": [
|
|
69
|
+
{ "name": "base", "minWidth": 0, "gap": "--space-4" },
|
|
70
|
+
{ "name": "wide", "minWidth": 960, "gap": "--space-6" }
|
|
71
|
+
],
|
|
72
|
+
"sizes": {
|
|
73
|
+
"small": { "base": { "min": 2, "preferred": 2, "max": 4 }, "wide": { "min": 1, "preferred": 2, "max": 2 } },
|
|
74
|
+
"medium": { "base": { "min": 4, "preferred": 4, "max": 8 }, "wide": { "min": 2, "preferred": 4, "max": 4 } },
|
|
75
|
+
"large": { "base": { "min": 8, "preferred": 8, "max": 8 }, "wide": { "min": 4, "preferred": 8, "max": 8 } }
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The example is valid JSON and passes the config validator unchanged:
|
|
81
|
+
|
|
82
|
+
- `name` is a lowercase CSS-safe name and not `default`, which is the kit's own scope and Grid refuses for any other config object.
|
|
83
|
+
- `columns` is an integer from 1 to 48.
|
|
84
|
+
- `rowHeight` is a positive length in px, rem or em.
|
|
85
|
+
- `steps[]` carries `name`, `minWidth` in px with the first step at 0 and the widths strictly increasing, and `gap`, a spacing token name such as `--space-4`.
|
|
86
|
+
- `sizes.<small|medium|large>.<step>` carries the span range with `1 <= min <= preferred <= max <= columns`.
|
|
87
|
+
|
|
88
|
+
Generate the step CSS and import it once beside the kit's own:
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
frontx-ui-grid-css ./grid-config.json ./grid-steps.css
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The command also reads a `.mjs` or `.js` module with a default export. A `.js` config is loaded with `import()`, so Node decides its module type from the nearest `package.json` `"type"` field, or by syntax detection when there is none; a CommonJS `module.exports` object is accepted as the default export. Use `.mjs` or `.json` when unsure. The output path must not be the config file, under any name.
|
|
95
|
+
|
|
96
|
+
Pass that same config object to `Grid`. CSS selectors are scoped by config name, so two configs can coexist, and a custom stylesheet is needed for each custom config. The generated CSS and the passed config must use the same name and steps. The CSS has no viewport queries and resizing does not run JavaScript. For Shadow DOM, include the kit component CSS and generated CSS inside the shadow root.
|
|
97
|
+
|
|
98
|
+
`--grid-gap` overrides the configured spacing token at every step, and `--grid-row-height` the configured row track. `--_grid-columns` and the per-step `--_grid-col-<step>` / `--_grid-row-<step>` are set by Grid.
|
|
99
|
+
|
|
100
|
+
## Accessibility
|
|
101
|
+
|
|
102
|
+
Grid adds no role or focus behavior. Put meaningful content inside each item. DOM and focus order remain the input order. A paired stack reads as the first low followed by the second low. An item whose content overflows is a scroll container and becomes a tab stop in browsers with focusable scrollers, so content that must stay reachable everywhere should fit or carry its own focusable control.
|
|
103
|
+
|
|
104
|
+
## Anti-patterns
|
|
105
|
+
|
|
106
|
+
- A fragment or wrapper between Grid and GridItem: Grid throws instead of dropping items.
|
|
107
|
+
- A reused `layoutId` in one Grid: Grid throws (`Duplicate Grid layoutId: <layoutId>`).
|
|
108
|
+
- A custom config without its generated CSS loaded: nothing reads the placement variables, and the browser auto-places the items.
|
|
109
|
+
|
|
110
|
+
## Examples
|
|
111
|
+
|
|
112
|
+
```tsx
|
|
113
|
+
<Grid>
|
|
114
|
+
<GridItem layoutId="summary" size="medium" height="high">Summary</GridItem>
|
|
115
|
+
<GridItem layoutId="trend" size="small">Trend</GridItem>
|
|
116
|
+
<GridItem layoutId="alerts" size="small">Alerts</GridItem>
|
|
117
|
+
</Grid>
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
With a custom config and the stylesheet generated for it imported once:
|
|
121
|
+
|
|
122
|
+
```tsx
|
|
123
|
+
<Grid config={reportConfig}>
|
|
124
|
+
<GridItem layoutId="table" size="large">Table</GridItem>
|
|
125
|
+
<GridItem layoutId="notes" size="small">Notes</GridItem>
|
|
126
|
+
</Grid>
|
|
127
|
+
```
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/*
|
|
3
|
+
* frontx-ui-grid-css: writes the Grid step rules for a config.
|
|
4
|
+
*
|
|
5
|
+
* frontx-ui-grid-css [--kit-default] <config.json|config.mjs|config.js> <output.css>
|
|
6
|
+
*
|
|
7
|
+
* `@container` conditions cannot read `var()`, so every container step width
|
|
8
|
+
* has to be a literal in CSS; this command turns a GridConfig into those
|
|
9
|
+
* rules. The kit's grid-steps.css is this command's output for the default
|
|
10
|
+
* config, regenerated by `npm run grid:css -w @gears-frontx/ui-kit` and kept
|
|
11
|
+
* equal by a test. Rules are scoped by the config name through `data-fx-grid`,
|
|
12
|
+
* never by a CSS Module class, so a custom config's CSS coexists with the
|
|
13
|
+
* default.
|
|
14
|
+
*
|
|
15
|
+
* `default` is the kit's own scope: the command refuses a config under that
|
|
16
|
+
* name unless --kit-default is given. The flag is public on the installed bin
|
|
17
|
+
* and is meant for regenerating the kit's own stylesheet, which the kit's
|
|
18
|
+
* `grid:css` script and the consumer acceptance do; it guards against a
|
|
19
|
+
* custom config accidentally shadowing the shipped rules, not against doing
|
|
20
|
+
* so on purpose.
|
|
21
|
+
*
|
|
22
|
+
* The generator and the config checks it runs live in the component
|
|
23
|
+
* directory. The build copies grid-css.mjs and grid-config-check.mjs flat
|
|
24
|
+
* into dist/ beside the bin and rewrites the one import specifier below to
|
|
25
|
+
* './grid-css.mjs', a rewrite buildPlugin.ts guards by refusing to copy when
|
|
26
|
+
* this specifier text moves, so the specifier stays as written unless the
|
|
27
|
+
* copy step changes with it. The command stays in scripts/ because it alone
|
|
28
|
+
* needs the Node builtins the component source may not import.
|
|
29
|
+
*/
|
|
30
|
+
import { readFile, stat, writeFile } from 'node:fs/promises';
|
|
31
|
+
import { extname, resolve } from 'node:path';
|
|
32
|
+
import { pathToFileURL } from 'node:url';
|
|
33
|
+
|
|
34
|
+
import { generateGridCss } from './grid-css.mjs';
|
|
35
|
+
|
|
36
|
+
const USAGE = 'Usage: frontx-ui-grid-css [--kit-default] <config.json|config.mjs|config.js> <output.css>';
|
|
37
|
+
|
|
38
|
+
async function main() {
|
|
39
|
+
const args = process.argv.slice(2);
|
|
40
|
+
const kitDefault = args.includes('--kit-default');
|
|
41
|
+
const positionals = args.filter(argument => argument !== '--kit-default');
|
|
42
|
+
// An explicit help request succeeds: the usage text on stdout, exit 0.
|
|
43
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
44
|
+
console.log(USAGE);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
// One option and two positionals: any other --word is a mistyped invocation,
|
|
48
|
+
// and any other arity has no reading, so both stop here instead of surfacing
|
|
49
|
+
// later as a missing or misread file. Apart from -h, a single dash stays a
|
|
50
|
+
// path character; a path that starts with -- is passed as ./--name.
|
|
51
|
+
if (args.some(argument => argument.startsWith('--') && argument !== '--kit-default') || positionals.length !== 2) {
|
|
52
|
+
throw new Error(USAGE);
|
|
53
|
+
}
|
|
54
|
+
const [input, output] = positionals;
|
|
55
|
+
const path = resolve(input);
|
|
56
|
+
// The output is written as CSS: the same file would replace the config.
|
|
57
|
+
// Checked before anything is read or written: by path, and for an existing
|
|
58
|
+
// output by filesystem identity (dev + ino), which catches a symlink, a hard
|
|
59
|
+
// link or a case alias. A missing output cannot be the config.
|
|
60
|
+
const sameFileError = new Error(`Output path ${output} is the config file; give the CSS its own path`);
|
|
61
|
+
if (path === resolve(output)) throw sameFileError;
|
|
62
|
+
const [configStat, outputStat] = await Promise.all([stat(path).catch(() => null), stat(resolve(output)).catch(() => null)]);
|
|
63
|
+
if (configStat && outputStat && configStat.dev === outputStat.dev && configStat.ino === outputStat.ino) throw sameFileError;
|
|
64
|
+
const extension = extname(path);
|
|
65
|
+
if (extension !== '.json' && extension !== '.mjs' && extension !== '.js') {
|
|
66
|
+
throw new Error('Grid config must be a .json file or an ES module (.mjs, .js) with a default export');
|
|
67
|
+
}
|
|
68
|
+
let config;
|
|
69
|
+
if (extension === '.json') {
|
|
70
|
+
config = JSON.parse(await readFile(path, 'utf8'));
|
|
71
|
+
} else {
|
|
72
|
+
const module = await import(pathToFileURL(path).href);
|
|
73
|
+
if (!('default' in module)) throw new Error(`Grid config module ${input} has no default export`);
|
|
74
|
+
config = module.default;
|
|
75
|
+
}
|
|
76
|
+
await writeFile(resolve(output), generateGridCss(config, { allowDefaultName: kitDefault }));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
main().catch(error => {
|
|
80
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
81
|
+
process.exitCode = 1;
|
|
82
|
+
});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The one Grid config validator: grid-config.ts and the generator
|
|
3
|
+
* (grid-css.mjs, behind the frontx-ui-grid-css command) both import it, so a
|
|
4
|
+
* config object and the stylesheet generated from it cannot disagree. The
|
|
5
|
+
* build copies this module flat into dist/ next to the command. Plain
|
|
6
|
+
* dependency-free ESM, so the command runs in plain Node without loading any
|
|
7
|
+
* component code (the built entries import CSS).
|
|
8
|
+
*
|
|
9
|
+
* Types: grid-config-check.d.mts.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const SIZE_CLASSES = ['small', 'medium', 'large'];
|
|
13
|
+
// Bounds the solver's width loops, which run per column.
|
|
14
|
+
const MAX_COLUMNS = 48;
|
|
15
|
+
const NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
16
|
+
const TOKEN_PATTERN = /^--[a-z][a-z0-9-]*$/;
|
|
17
|
+
const LENGTH_PATTERN = /^(?:\d+(?:\.\d+)?|\.\d+)(?:px|rem|em)$/;
|
|
18
|
+
|
|
19
|
+
function validRange(range, columns) {
|
|
20
|
+
return (
|
|
21
|
+
!!range &&
|
|
22
|
+
Number.isSafeInteger(range.min) &&
|
|
23
|
+
Number.isSafeInteger(range.preferred) &&
|
|
24
|
+
Number.isSafeInteger(range.max) &&
|
|
25
|
+
range.min >= 1 &&
|
|
26
|
+
range.min <= range.preferred &&
|
|
27
|
+
range.preferred <= range.max &&
|
|
28
|
+
range.max <= columns
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Throws with a plain message when a config cannot drive the solver or the
|
|
34
|
+
* generated CSS. `allowDefaultName` admits the reserved `default` scope, which
|
|
35
|
+
* belongs to the kit's own defaultGridConfig and its shipped stylesheet; every
|
|
36
|
+
* other caller refuses it.
|
|
37
|
+
*/
|
|
38
|
+
export function validateGridConfig(config, { allowDefaultName = false } = {}) {
|
|
39
|
+
if (!config || typeof config !== 'object') throw new Error('Grid config must be an object');
|
|
40
|
+
if (typeof config.name !== 'string' || !NAME_PATTERN.test(config.name)) {
|
|
41
|
+
throw new Error('Grid config name must be a lowercase CSS-safe name');
|
|
42
|
+
}
|
|
43
|
+
if (!allowDefaultName && config.name === 'default') {
|
|
44
|
+
throw new Error('Grid config name "default" belongs to defaultGridConfig; give a custom config its own name');
|
|
45
|
+
}
|
|
46
|
+
if (!Number.isSafeInteger(config.columns) || config.columns < 1 || config.columns > MAX_COLUMNS) {
|
|
47
|
+
throw new Error(`Grid columns must be an integer from 1 to ${MAX_COLUMNS}`);
|
|
48
|
+
}
|
|
49
|
+
if (typeof config.rowHeight !== 'string' || !LENGTH_PATTERN.test(config.rowHeight) || parseFloat(config.rowHeight) <= 0) {
|
|
50
|
+
throw new Error('Grid rowHeight must be a positive CSS length in px, rem or em');
|
|
51
|
+
}
|
|
52
|
+
if (!Array.isArray(config.steps) || config.steps.length === 0) throw new Error('Grid steps must be nonempty');
|
|
53
|
+
const names = new Set();
|
|
54
|
+
let previousWidth = -1;
|
|
55
|
+
for (const step of config.steps) {
|
|
56
|
+
if (!step || typeof step.name !== 'string' || !NAME_PATTERN.test(step.name) || names.has(step.name)) {
|
|
57
|
+
throw new Error('Grid step names must be unique lowercase CSS-safe names');
|
|
58
|
+
}
|
|
59
|
+
if (!Number.isFinite(step.minWidth) || step.minWidth < 0 || step.minWidth <= previousWidth) {
|
|
60
|
+
throw new Error('Grid step widths must be finite, nonnegative, and strictly increasing');
|
|
61
|
+
}
|
|
62
|
+
if (typeof step.gap !== 'string' || !TOKEN_PATTERN.test(step.gap)) {
|
|
63
|
+
throw new Error(`Grid step ${step.name} gap must be a CSS token reference`);
|
|
64
|
+
}
|
|
65
|
+
names.add(step.name);
|
|
66
|
+
previousWidth = step.minWidth;
|
|
67
|
+
}
|
|
68
|
+
if (config.steps[0].minWidth !== 0) throw new Error('Grid first step must start at 0');
|
|
69
|
+
for (const size of SIZE_CLASSES) {
|
|
70
|
+
const steps = config.sizes?.[size];
|
|
71
|
+
if (!steps || typeof steps !== 'object') throw new Error(`Grid size ${size} is missing`);
|
|
72
|
+
for (const name of names) {
|
|
73
|
+
if (!validRange(steps[name], config.columns)) {
|
|
74
|
+
throw new Error(`Grid size ${size} step ${name} needs 1 <= min <= preferred <= max <= columns`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|