@lenso/primitives 0.8.0 → 0.9.0

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.
@@ -1,178 +0,0 @@
1
- "use client";
2
- import * as React from "react";
3
- import { cellSelectionFeature, columnResizingFeature, columnSizingFeature, createSortedRowModel, functionalUpdate, makeStateUpdater, rowSelectionFeature, rowSortingFeature, sortFn_alphanumeric, sortFn_basic, sortFn_datetime, sortFn_text, tableFeatures, useTable } from "@tanstack/react-table";
4
- // src/data-grid/index.tsx
5
- const dataGridFeatures = tableFeatures({
6
- cellSelectionFeature,
7
- columnSizingFeature,
8
- columnResizingFeature,
9
- rowSelectionFeature,
10
- rowSortingFeature,
11
- sortedRowModel: createSortedRowModel(),
12
- sortFns: {
13
- alphanumeric: sortFn_alphanumeric,
14
- basic: sortFn_basic,
15
- datetime: sortFn_datetime,
16
- text: sortFn_text
17
- }
18
- });
19
- function useDataGrid({ rows, columns, getRowId, readOnly = false, rowSelection = true, cellSelection = true, sorting = true, onRowsChange, onCellEditComplete, cellEvents, onRowEditComplete, onRowSelectionChange, onCellSelectionChange, onSortingChange, validationData, tableOptions }) {
20
- const tableColumns = React.useMemo(() => columns.map((column) => ({
21
- id: column.id,
22
- header: column.header,
23
- accessorFn: column.getValue,
24
- enableSorting: sorting && column.sortable !== false,
25
- enableCellSelection: cellSelection,
26
- size: column.width ?? 180,
27
- minSize: column.minWidth ?? 80,
28
- maxSize: column.maxWidth ?? 1200,
29
- ...column.tableColumn
30
- })), [
31
- cellSelection,
32
- columns,
33
- sorting
34
- ]);
35
- const table = useTable({
36
- features: dataGridFeatures,
37
- columns: tableColumns,
38
- data: rows,
39
- getRowId,
40
- enableRowSelection: rowSelection,
41
- enableCellSelection: cellSelection,
42
- enableCellSelectionDrag: cellSelection,
43
- autoResetCellSelection: false,
44
- enableSorting: sorting,
45
- ...tableOptions,
46
- onRowSelectionChange: (updater) => {
47
- const next = functionalUpdate(updater, table.state.rowSelection);
48
- (tableOptions?.onRowSelectionChange ?? makeStateUpdater("rowSelection", table))(updater);
49
- onRowSelectionChange?.(new Set(Object.keys(next).filter((id) => next[id])));
50
- },
51
- onCellSelectionChange: (updater) => {
52
- const next = functionalUpdate(updater, table.state.cellSelection);
53
- (tableOptions?.onCellSelectionChange ?? makeStateUpdater("cellSelection", table))(updater);
54
- onCellSelectionChange?.(next);
55
- },
56
- onSortingChange: (updater) => {
57
- const next = functionalUpdate(updater, table.state.sorting);
58
- (tableOptions?.onSortingChange ?? makeStateUpdater("sorting", table))(updater);
59
- onSortingChange?.(next);
60
- }
61
- });
62
- return {
63
- table,
64
- commitCells: React.useCallback((edits, reason = "edit") => {
65
- if (edits.length === 0) return {
66
- ok: true,
67
- changes: []
68
- };
69
- if (readOnly || !onRowsChange) return {
70
- ok: false,
71
- error: "This grid is read-only",
72
- edit: edits[0]
73
- };
74
- const nextRows = [...rows];
75
- const rowIndexById = new Map(rows.map((row, index) => [getRowId(row), index]));
76
- const columnById = new Map(columns.map((column) => [column.id, column]));
77
- const changes = [];
78
- const uniqueEdits = /* @__PURE__ */ new Map();
79
- for (const edit of edits) uniqueEdits.set(JSON.stringify([edit.rowId, edit.columnId]), edit);
80
- for (const edit of uniqueEdits.values()) {
81
- const rowIndex = rowIndexById.get(edit.rowId);
82
- const column = columnById.get(edit.columnId);
83
- if (rowIndex === void 0 || !column) return {
84
- ok: false,
85
- error: "Unknown row or column",
86
- edit
87
- };
88
- const row = nextRows[rowIndex];
89
- if (!(column.setValue && (typeof column.editable === "function" ? column.editable(row) : column.editable !== false))) return {
90
- ok: false,
91
- error: "This cell is read-only",
92
- edit
93
- };
94
- const previousValue = column.getValue(row);
95
- const value = edit.value;
96
- if (Object.is(previousValue, value)) continue;
97
- const updatedRow = column.setValue(row, value);
98
- nextRows[rowIndex] = updatedRow;
99
- changes.push({
100
- rowId: edit.rowId,
101
- rowIndex,
102
- columnId: column.id,
103
- previousValue,
104
- value,
105
- previousRow: row,
106
- row: updatedRow,
107
- reason
108
- });
109
- }
110
- if (changes.length === 0) return {
111
- ok: true,
112
- changes
113
- };
114
- for (const change of changes) {
115
- const validationError = columnById.get(change.columnId).validate?.(change.value, nextRows[change.rowIndex], {
116
- rowId: change.rowId,
117
- rowIndex: change.rowIndex,
118
- columnId: change.columnId,
119
- rows: nextRows,
120
- originalRows: rows,
121
- changes,
122
- reason,
123
- data: validationData,
124
- table
125
- });
126
- if (validationError) return {
127
- ok: false,
128
- error: validationError,
129
- edit: {
130
- rowId: change.rowId,
131
- columnId: change.columnId,
132
- value: change.value
133
- }
134
- };
135
- }
136
- onRowsChange(nextRows, changes);
137
- for (const change of changes) {
138
- onCellEditComplete?.(change);
139
- columnById.get(change.columnId)?.onCellEditComplete?.(change);
140
- for (const event of cellEvents ?? []) if (event.rowId === change.rowId && event.columnId === change.columnId) event.onEditComplete(change);
141
- }
142
- const changedRows = /* @__PURE__ */ new Map();
143
- for (const change of changes) {
144
- const rowChanges = changedRows.get(change.rowId) ?? [];
145
- rowChanges.push(change);
146
- changedRows.set(change.rowId, rowChanges);
147
- }
148
- for (const [rowId, rowChanges] of changedRows) {
149
- const first = rowChanges[0];
150
- const last = rowChanges[rowChanges.length - 1];
151
- onRowEditComplete?.({
152
- rowId,
153
- rowIndex: first.rowIndex,
154
- previousRow: first.previousRow,
155
- row: last.row,
156
- changes: rowChanges,
157
- reason
158
- });
159
- }
160
- return {
161
- ok: true,
162
- changes
163
- };
164
- }, [
165
- cellEvents,
166
- columns,
167
- getRowId,
168
- onCellEditComplete,
169
- onRowEditComplete,
170
- onRowsChange,
171
- readOnly,
172
- rows,
173
- table,
174
- validationData
175
- ])
176
- };
177
- }
178
- export { dataGridFeatures, useDataGrid };
@@ -1,44 +0,0 @@
1
- import * as React from "react";
2
- import * as stylex from "@stylexjs/stylex";
3
- import { useRender } from "@base-ui/react/use-render";
4
- export type ResizeHandleOrientation = "horizontal" | "vertical";
5
- export type ResizeHandleChangeReason = "keyboard" | "pointer";
6
- export type ResizeHandleInputEvent = React.KeyboardEvent<HTMLElement> | React.PointerEvent<HTMLElement>;
7
- export interface ResizeHandleChangeDetails {
8
- delta: number;
9
- event: ResizeHandleInputEvent;
10
- reason: ResizeHandleChangeReason;
11
- value: number;
12
- }
13
- export type ResizeHandleState = {
14
- disabled: boolean;
15
- dragging: boolean;
16
- orientation: ResizeHandleOrientation;
17
- value: number;
18
- };
19
- type ResizeHandleElementProps = Omit<useRender.ComponentProps<"div", ResizeHandleState>, "aria-controls" | "aria-disabled" | "aria-orientation" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "className" | "ref" | "role" | "tabIndex">;
20
- export type ResizeHandleProps = ResizeHandleElementProps & {
21
- "aria-label"?: string;
22
- "aria-labelledby"?: string;
23
- "aria-controls": string;
24
- disabled?: boolean;
25
- inverted?: boolean;
26
- max: number;
27
- min: number;
28
- onCollapseToggle?: (event: React.KeyboardEvent<HTMLElement> | React.MouseEvent<HTMLElement>) => void;
29
- onValueChange: (value: number, details: ResizeHandleChangeDetails) => void;
30
- onValueCommit?: (value: number, details: ResizeHandleChangeDetails) => void;
31
- orientation?: ResizeHandleOrientation;
32
- ref?: React.Ref<HTMLElement>;
33
- step?: number;
34
- value: number;
35
- xstyle?: stylex.StyleXStyles;
36
- };
37
- /**
38
- * A layout-independent, focusable window splitter.
39
- *
40
- * Consumers own pane layout and persistence. The handle owns pointer capture,
41
- * keyboard adjustment, bounded values, and WAI-ARIA separator semantics.
42
- */
43
- export declare function ResizeHandle({ disabled, inverted, max, min, onCollapseToggle, onValueChange, onValueCommit, orientation, ref, render, step, value, xstyle, ...props }: ResizeHandleProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>;
44
- export {};
@@ -1,179 +0,0 @@
1
- "use client";
2
- import * as React from "react";
3
- import * as stylex from "@stylexjs/stylex";
4
- import { mergeProps } from "@base-ui/react/merge-props";
5
- import { useRender } from "@base-ui/react/use-render";
6
- // src/resize-handle/index.tsx
7
- function clamp(value, min, max) {
8
- return Math.min(max, Math.max(min, value));
9
- }
10
- function coordinate(event, orientation) {
11
- return orientation === "vertical" ? event.clientX : event.clientY;
12
- }
13
- /**
14
- * A layout-independent, focusable window splitter.
15
- *
16
- * Consumers own pane layout and persistence. The handle owns pointer capture,
17
- * keyboard adjustment, bounded values, and WAI-ARIA separator semantics.
18
- */
19
- function ResizeHandle({ disabled = false, inverted = false, max, min, onCollapseToggle, onValueChange, onValueCommit, orientation = "vertical", ref, render, step = 16, value, xstyle, ...props }) {
20
- const elementRef = React.useRef(null);
21
- const dragRef = React.useRef(null);
22
- const restoreDocumentRef = React.useRef(null);
23
- const suppressClickRef = React.useRef(false);
24
- const [dragging, setDragging] = React.useState(false);
25
- const lowerBound = Math.min(min, max);
26
- const upperBound = Math.max(min, max);
27
- const currentValue = clamp(value, lowerBound, upperBound);
28
- const normalizedStep = Math.max(1, Math.abs(step));
29
- const state = React.useMemo(() => ({
30
- disabled,
31
- dragging,
32
- orientation,
33
- value: currentValue
34
- }), [
35
- currentValue,
36
- disabled,
37
- dragging,
38
- orientation
39
- ]);
40
- const restoreDocumentInteraction = React.useCallback(() => {
41
- restoreDocumentRef.current?.();
42
- restoreDocumentRef.current = null;
43
- }, []);
44
- React.useEffect(() => restoreDocumentInteraction, [restoreDocumentInteraction]);
45
- function createDetails(nextValue, previousValue, reason, event) {
46
- return {
47
- delta: nextValue - previousValue,
48
- event,
49
- reason,
50
- value: nextValue
51
- };
52
- }
53
- function changeValue(nextValue, previousValue, reason, event, commit) {
54
- const boundedValue = clamp(nextValue, lowerBound, upperBound);
55
- const details = createDetails(boundedValue, previousValue, reason, event);
56
- if (boundedValue !== previousValue) onValueChange(boundedValue, details);
57
- if (commit) onValueCommit?.(boundedValue, details);
58
- return boundedValue;
59
- }
60
- function finishPointerDrag(event) {
61
- const drag = dragRef.current;
62
- if (!drag || drag.pointerId !== event.pointerId) return;
63
- dragRef.current = null;
64
- suppressClickRef.current = drag.moved;
65
- setDragging(false);
66
- restoreDocumentInteraction();
67
- const details = createDetails(drag.lastValue, drag.startValue, "pointer", event);
68
- onValueCommit?.(drag.lastValue, details);
69
- if (drag.target.hasPointerCapture(event.pointerId)) drag.target.releasePointerCapture(event.pointerId);
70
- }
71
- const internalProps = {
72
- onClick(event) {
73
- if (disabled) return;
74
- if (suppressClickRef.current) {
75
- suppressClickRef.current = false;
76
- return;
77
- }
78
- onCollapseToggle?.(event);
79
- },
80
- onKeyDown(event) {
81
- if (disabled) return;
82
- let nextValue;
83
- const direction = inverted ? -1 : 1;
84
- if (orientation === "vertical") {
85
- if (event.key === "ArrowLeft") nextValue = currentValue - normalizedStep * direction;
86
- if (event.key === "ArrowRight") nextValue = currentValue + normalizedStep * direction;
87
- } else {
88
- if (event.key === "ArrowUp") nextValue = currentValue - normalizedStep * direction;
89
- if (event.key === "ArrowDown") nextValue = currentValue + normalizedStep * direction;
90
- }
91
- if (event.key === "Home") nextValue = lowerBound;
92
- if (event.key === "End") nextValue = upperBound;
93
- if (event.key === "Enter" && onCollapseToggle) {
94
- event.preventDefault();
95
- onCollapseToggle(event);
96
- return;
97
- }
98
- if (nextValue === void 0) return;
99
- event.preventDefault();
100
- changeValue(nextValue, currentValue, "keyboard", event, true);
101
- },
102
- onLostPointerCapture(event) {
103
- finishPointerDrag(event);
104
- },
105
- onPointerCancel(event) {
106
- finishPointerDrag(event);
107
- },
108
- onPointerDown(event) {
109
- if (disabled || event.button !== 0) return;
110
- event.preventDefault();
111
- event.currentTarget.focus({ preventScroll: true });
112
- dragRef.current = {
113
- lastValue: currentValue,
114
- moved: false,
115
- pointerId: event.pointerId,
116
- startCoordinate: coordinate(event, orientation),
117
- startValue: currentValue,
118
- target: event.currentTarget
119
- };
120
- setDragging(true);
121
- try {
122
- event.currentTarget.setPointerCapture(event.pointerId);
123
- } catch {}
124
- const body = event.currentTarget.ownerDocument.body;
125
- const previousCursor = body.style.cursor;
126
- const previousUserSelect = body.style.userSelect;
127
- body.style.cursor = orientation === "vertical" ? "col-resize" : "row-resize";
128
- body.style.userSelect = "none";
129
- restoreDocumentRef.current = () => {
130
- body.style.cursor = previousCursor;
131
- body.style.userSelect = previousUserSelect;
132
- };
133
- },
134
- onPointerMove(event) {
135
- const drag = dragRef.current;
136
- if (!drag || drag.pointerId !== event.pointerId) return;
137
- event.preventDefault();
138
- const physicalDelta = coordinate(event, orientation) - drag.startCoordinate;
139
- drag.moved ||= Math.abs(physicalDelta) >= 3;
140
- const valueDelta = physicalDelta * (inverted ? -1 : 1);
141
- const nextValue = clamp(drag.startValue + valueDelta, lowerBound, upperBound);
142
- if (nextValue === drag.lastValue) return;
143
- const previousValue = drag.lastValue;
144
- drag.lastValue = nextValue;
145
- changeValue(nextValue, previousValue, "pointer", event, false);
146
- },
147
- onPointerUp(event) {
148
- finishPointerDrag(event);
149
- }
150
- };
151
- const protectedProps = {
152
- "aria-controls": props["aria-controls"],
153
- "aria-disabled": disabled || void 0,
154
- "aria-orientation": orientation,
155
- "aria-valuemax": upperBound,
156
- "aria-valuemin": lowerBound,
157
- "aria-valuenow": currentValue,
158
- role: "separator",
159
- tabIndex: disabled ? void 0 : 0
160
- };
161
- return useRender({
162
- defaultTagName: "div",
163
- props: {
164
- ...mergeProps(internalProps, props, protectedProps),
165
- className: stylex.props(xstyle).className,
166
- "data-slot": "resize-handle"
167
- },
168
- ref: ref ? [elementRef, ref] : elementRef,
169
- render,
170
- state,
171
- stateAttributesMapping: {
172
- disabled: (isDisabled) => isDisabled ? { "data-disabled": "" } : null,
173
- dragging: (isDragging) => isDragging ? { "data-dragging": "" } : null,
174
- orientation: (currentOrientation) => ({ "data-orientation": currentOrientation }),
175
- value: () => null
176
- }
177
- });
178
- }
179
- export { ResizeHandle };