datatable-tree 0.0.0-stage → 0.1.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +240 -2
  3. package/dist/DataTable.d.ts +583 -0
  4. package/dist/DataTable.js +620 -0
  5. package/dist/Draggable.d.ts +35 -0
  6. package/dist/Draggable.js +91 -0
  7. package/dist/ListBox.d.ts +132 -0
  8. package/dist/ListBox.js +243 -0
  9. package/dist/ListVirtualizer.d.ts +59 -0
  10. package/dist/ListVirtualizer.js +180 -0
  11. package/dist/TreeList.d.ts +196 -0
  12. package/dist/TreeList.js +300 -0
  13. package/dist/config.d.ts +55 -0
  14. package/dist/config.js +33 -0
  15. package/dist/datatable.css +161 -0
  16. package/dist/hooks.d.ts +27 -0
  17. package/dist/hooks.js +115 -0
  18. package/dist/index.d.ts +12 -0
  19. package/dist/index.js +15 -0
  20. package/dist/interfaces.d.ts +269 -0
  21. package/dist/interfaces.js +3 -0
  22. package/dist/mobx-adapter.d.ts +12 -0
  23. package/dist/mobx-adapter.js +21 -0
  24. package/dist/reactivity.d.ts +112 -0
  25. package/dist/reactivity.js +155 -0
  26. package/dist/styles.d.ts +64 -0
  27. package/dist/styles.js +86 -0
  28. package/dist/theme.d.ts +160 -0
  29. package/dist/theme.js +239 -0
  30. package/dist/util.d.ts +28 -0
  31. package/dist/util.js +45 -0
  32. package/package.json +137 -4
  33. package/src/DataTable.tsx +1332 -0
  34. package/src/Draggable.tsx +133 -0
  35. package/src/ListBox.tsx +423 -0
  36. package/src/ListVirtualizer.ts +234 -0
  37. package/src/TreeList.tsx +590 -0
  38. package/src/config.tsx +96 -0
  39. package/src/css.d.ts +1 -0
  40. package/src/datatable.css +161 -0
  41. package/src/hooks.ts +138 -0
  42. package/src/index.ts +15 -0
  43. package/src/interfaces.ts +309 -0
  44. package/src/mobx-adapter.ts +24 -0
  45. package/src/reactivity.ts +222 -0
  46. package/src/styles.tsx +102 -0
  47. package/src/theme.ts +346 -0
  48. package/src/util.ts +60 -0
@@ -0,0 +1,222 @@
1
+ import React, { useEffect, useMemo } from 'react';
2
+
3
+ import { useForceUpdate } from './hooks.js';
4
+ import { ISet } from './interfaces.js';
5
+ import { nully } from './util.js';
6
+
7
+ /**
8
+ * Reactivity adapter
9
+ * ------------------
10
+ *
11
+ * The list/tree/table components in this package re-render in response to state changes:
12
+ * changes to the selection, to the set of expanded parents, to the sort order, and (in apps
13
+ * built on an observability library) changes to the row data itself. Rather than depend on a
14
+ * particular state-management library, the components route all such behavior through a
15
+ * `ReactivityAdapter`.
16
+ *
17
+ * The default adapter (`plainReactivityAdapter`) has no dependencies: components re-render
18
+ * via ordinary React state updates, and collections created by `observableSet`/
19
+ * `observableArray` are `WatchableSet`/`WatchableArray` instances that notify the components
20
+ * using them. What the default adapter cannot do is detect mutations of *plain* Sets/arrays
21
+ * you pass as props, or mutations of row data; pass new object/collection instances (or
22
+ * `WatchableSet`/`WatchableArray`) when changing them from outside, as is normal in React.
23
+ *
24
+ * If your app uses MobX, call `setReactivityAdapter(mobxReactivityAdapter)` (see the
25
+ * `datatable-tree/mobx` entry point) once at startup, before rendering. Then all components
26
+ * behave as `observer`s: rows re-render when observable row data mutates, and you can pass
27
+ * `observable.set`/`observable.array` for selection/expansion/sort state.
28
+ *
29
+ * Each adapter member is named after the MobX API it abstracts.
30
+ */
31
+ export interface ReactivityAdapter {
32
+ /** Wraps a component so that it re-renders when observable values read during its last
33
+ * render change (mobx-react `observer`). Default: returns the component unchanged. */
34
+ observer<C extends React.ComponentType<any>>(component: C): C;
35
+ /** Runs a group of state mutations as a single atomic action, so observers see one
36
+ * change notification rather than several (mobx `runInAction`). Default: `f()`. */
37
+ runInAction(f: () => void): void;
38
+ /** Creates the Set used for default selection/expandedParents state when the caller
39
+ * doesn't provide one (mobx `observable.set`). Default: a `WatchableSet`. */
40
+ observableSet<K>(): ISet<K>;
41
+ /** Creates the array used for default `columnsToSortBy` state when the caller doesn't
42
+ * provide one (mobx `observable.array`). Default: a `WatchableArray`. */
43
+ observableArray<T>(): WatchableArrayLike<T>;
44
+ /** Creates a lazily-(re)computed derived value (mobx `computed`). The default adapter
45
+ * does not cache: `get()` simply calls `f()`, which is correct but repeats the
46
+ * computation once per render. */
47
+ computed<T>(f: () => T): { get(): T };
48
+ }
49
+
50
+ /** The array type accepted for `columnsToSortBy`: a mutable array with a `clear()` method.
51
+ * Satisfied by MobX's `IObservableArray` and by this package's `WatchableArray`. */
52
+ export type WatchableArrayLike<T> = Array<T> & { clear(): void };
53
+
54
+ /** Interface implemented by collections that can notify components of their mutations.
55
+ * The list components subscribe (via `useWatched`) to any prop collection that has a
56
+ * `subscribe` method, so they re-render when it changes. */
57
+ export interface Watchable {
58
+ /** Registers a mutation listener and returns a function that unregisters it. */
59
+ subscribe(onChange: () => void): () => void;
60
+ }
61
+
62
+ /** A `Set` that implements `Watchable`, notifying subscribers after add/delete/clear. */
63
+ export class WatchableSet<K> extends Set<K> implements Watchable {
64
+ private listeners = new Set<() => void>();
65
+
66
+ subscribe(onChange: () => void): () => void {
67
+ this.listeners.add(onChange);
68
+ return () => this.listeners.delete(onChange);
69
+ }
70
+ protected notify() {
71
+ this.listeners.forEach(f => f());
72
+ }
73
+ override add(key: K) {
74
+ if (!super.has(key)) {
75
+ super.add(key);
76
+ this.notify();
77
+ }
78
+ return this;
79
+ }
80
+ override delete(key: K) {
81
+ const deleted = super.delete(key);
82
+ if (deleted) {
83
+ this.notify();
84
+ }
85
+ return deleted;
86
+ }
87
+ override clear() {
88
+ if (super.size > 0) {
89
+ super.clear();
90
+ this.notify();
91
+ }
92
+ }
93
+ }
94
+
95
+ /** An `Array` that implements `Watchable`, notifying subscribers after mutations made
96
+ * through the standard mutator methods (push/pop/shift/unshift/splice/sort/reverse) or
97
+ * `clear`. Note: direct writes like `a[0] = x` or `a.length = 0` do NOT notify. */
98
+ export class WatchableArray<T> extends Array<T> implements Watchable {
99
+ // Not initialized inline because Array methods (e.g. splice) construct new instances
100
+ // via this.constructor without running field initializers in some transpile targets.
101
+ private listeners?: Set<() => void>;
102
+
103
+ subscribe(onChange: () => void): () => void {
104
+ (this.listeners ??= new Set()).add(onChange);
105
+ return () => this.listeners!.delete(onChange);
106
+ }
107
+ protected notify() {
108
+ this.listeners?.forEach(f => f());
109
+ }
110
+ clear() {
111
+ this.length = 0;
112
+ this.notify();
113
+ }
114
+ override push(...items: T[]) {
115
+ const result = super.push(...items);
116
+ this.notify();
117
+ return result;
118
+ }
119
+ override pop() {
120
+ const result = super.pop();
121
+ this.notify();
122
+ return result;
123
+ }
124
+ override shift() {
125
+ const result = super.shift();
126
+ this.notify();
127
+ return result;
128
+ }
129
+ override unshift(...items: T[]) {
130
+ const result = super.unshift(...items);
131
+ this.notify();
132
+ return result;
133
+ }
134
+ override splice(start: number, deleteCount?: number, ...items: T[]) {
135
+ const result = deleteCount === undefined && items.length === 0
136
+ ? super.splice(start)
137
+ : super.splice(start, deleteCount!, ...items);
138
+ this.notify();
139
+ return result;
140
+ }
141
+ override sort(compareFn?: (a: T, b: T) => number) {
142
+ super.sort(compareFn);
143
+ this.notify();
144
+ return this;
145
+ }
146
+ override reverse() {
147
+ super.reverse();
148
+ this.notify();
149
+ return this;
150
+ }
151
+ }
152
+
153
+ /** The default adapter: plain React, no external dependencies. */
154
+ export const plainReactivityAdapter: ReactivityAdapter = {
155
+ observer: component => component,
156
+ runInAction: f => f(),
157
+ observableSet: () => new WatchableSet(),
158
+ observableArray: () => new WatchableArray(),
159
+ computed: f => ({ get: f }),
160
+ };
161
+
162
+ let adapter: ReactivityAdapter = plainReactivityAdapter;
163
+
164
+ /** Installs a `ReactivityAdapter`. Call once at app startup, before rendering any of this
165
+ * package's components (components adopt the adapter on their next render, but state
166
+ * created with a previous adapter is not converted). */
167
+ export function setReactivityAdapter(newAdapter: ReactivityAdapter) {
168
+ adapter = newAdapter;
169
+ }
170
+
171
+ export function getReactivityAdapter(): ReactivityAdapter {
172
+ return adapter;
173
+ }
174
+
175
+ /** Wraps a component with `adapter.observer` lazily, at first render rather than at module
176
+ * load time, so that `setReactivityAdapter` works no matter when the app calls it during
177
+ * startup. (A module-scope `observer(...)` call would capture the default adapter, because
178
+ * imported modules run before the importing module's own code.) */
179
+ export function reactive<C extends React.ComponentType<any>>(component: C): C {
180
+ let wrapped: React.ComponentType<any> | undefined;
181
+ let wrappedWith: ReactivityAdapter | undefined;
182
+ const Reactive = (props: any) => {
183
+ if (wrappedWith !== adapter) {
184
+ wrapped = adapter.observer(component);
185
+ wrappedWith = adapter;
186
+ }
187
+ return React.createElement(wrapped!, props);
188
+ };
189
+ Reactive.displayName = component.displayName ?? component.name;
190
+ return Reactive as unknown as C;
191
+ }
192
+
193
+ /** Wraps a function so that its body runs inside `adapter.runInAction`, preserving `this`
194
+ * and arguments (replaces mobx `action(fn)` for event handlers). */
195
+ export function asAction<F extends (...args: any[]) => void>(fn: F): F {
196
+ return function(this: unknown, ...args: unknown[]) {
197
+ adapter.runInAction(() => fn.apply(this, args));
198
+ } as F;
199
+ }
200
+
201
+ /** Re-renders the calling component when `collection` reports a mutation. Works with any
202
+ * prop value: subscribes only if the object implements `Watchable` (e.g. `WatchableSet`,
203
+ * `WatchableArray`); plain Sets/arrays and MobX collections are left to their own devices
204
+ * (MobX collections notify through `observer` instead). */
205
+ export function useWatched<T>(collection: T): T {
206
+ const forceUpdate = useForceUpdate();
207
+ const watchable = (collection as Partial<Watchable> | nully)?.subscribe
208
+ ? collection as unknown as Watchable : undefined;
209
+ useEffect(() => watchable?.subscribe(forceUpdate), [watchable, forceUpdate]);
210
+ return collection;
211
+ }
212
+
213
+ /** Combines useMemo() with the adapter's computed() so that a computation is not repeated
214
+ * every render. Keep in mind that local variables captured in the `computation` lambda will
215
+ * often be outdated since the same lambda is re-used across multiple renders.
216
+ *
217
+ * NOTE: with the MobX adapter, `computed()` can only cache inside an `observer()` component;
218
+ * with the default adapter it recomputes on every `get()`. */
219
+ export function useComputed<T>(computation: () => T, deps: ReadonlyArray<any> = []): { get(): T } {
220
+ // eslint-disable-next-line react-hooks/exhaustive-deps
221
+ return useMemo(() => adapter.computed(computation), deps);
222
+ }
package/src/styles.tsx ADDED
@@ -0,0 +1,102 @@
1
+ import { AriaRole } from 'react';
2
+
3
+ /** `style` and `class` properties. The type has a short name, deliberately, so
4
+ that it is convenient to use often. Note: `class` is a synonym for `className`;
5
+ you can't use both properties at once (or rather, className takes precedence). */
6
+ export interface Styles {
7
+ style?: React.CSSProperties;
8
+ class?: string;
9
+ className?: string;
10
+ useDefaultClass?: boolean;
11
+ role?: AriaRole;
12
+ };
13
+
14
+ /** Combines a Styles object with an optional default class and default CSSProperties
15
+ * to produce a pair { style, className }. A user-defined class name in `s` replaces
16
+ * the default class. Each individual style in `s` can replace individual styles in
17
+ * `defaultStyle`, but non-conflicting styles are merged.
18
+ *
19
+ * This function can also be used to simply convert { style, className, ... } to
20
+ * { style, className }, removing additional properties. Components that accept
21
+ * Styles can use this method to easily set their class/style, e.g.
22
+ *
23
+ * export function MyComponent(p: Styles & { children: React.ReactNode; }) {
24
+ * const styles = useStyles();
25
+ * return (<div {...classAndStyle(p, styles.mycomp)}>{p.children}</div>);
26
+ * }
27
+ *
28
+ * Using the Styles type, it is straightforward to allow components to change styles in
29
+ * grandchildren elements, e.g. the `onTable` and `onTableBody` props in this example:
30
+ *
31
+ * export function WrappedTable(p: Styles & {
32
+ * children: React.ReactNode;
33
+ * onTable?: Styles;
34
+ * onTableBody?: Styles;
35
+ * }) {
36
+ * const styles = useStyles();
37
+ * return (
38
+ * <div {...classAndStyle(p, styles.container)}>
39
+ * <Table {...classAndStyle(p.onTable, styles.table)}>
40
+ * <TableBody {...classAndStyle(p.onTableBody)}>
41
+ * {p.children}
42
+ * </TableBody>
43
+ * </Table>
44
+ * </div>
45
+ * );
46
+ * }
47
+ *
48
+ * In this example, TableBody is a MUI component that accepts className and style
49
+ * (but not `class`). Given a child component that accepts `Styles`, you can
50
+ * write <Child {...p.onChild}/> rather than <Child {...classAndStyle(p.onChild)}/>. */
51
+ export function classAndStyle(s?: Styles|null, defaultClass?: string, defaultStyle?: React.CSSProperties) {
52
+ let result: { style?: React.CSSProperties, className?: string, role?: AriaRole } | undefined;
53
+ if (s) {
54
+ let className;
55
+ if (s.useDefaultClass && defaultClass) {
56
+ className = `${defaultClass} ${s.className ?? s.class}`;
57
+ } else {
58
+ className = s.className ?? s.class ?? defaultClass;
59
+ }
60
+
61
+ result = {
62
+ style: combineStyle(s.style, defaultStyle),
63
+ className,
64
+ };
65
+ if (s.role) {
66
+ result.role = s.role;
67
+ }
68
+ return result;
69
+ } else if (defaultClass ?? defaultStyle) {
70
+ return {
71
+ style: defaultStyle,
72
+ className: defaultClass,
73
+ };
74
+ }
75
+ }
76
+
77
+ /** Same as `classAndStyle` except that other properties from `s` are also copied to the output. */
78
+ export function classAndStyleEtc(s: Styles, defaultClass?: string, defaultStyle?: React.CSSProperties) {
79
+ let className;
80
+ if (s.useDefaultClass && defaultClass) {
81
+ className = `${defaultClass} ${s.className ?? s.class}`;
82
+ } else {
83
+ className = s.className ?? s.class ?? defaultClass;
84
+ }
85
+
86
+ return {
87
+ ...s, // include any other properties
88
+ style: combineStyle(s.style, defaultStyle),
89
+ className,
90
+ };
91
+ }
92
+
93
+ /** Combines two `CSSProperties|undefined` values, with properties in the first
94
+ * overriding properties in the second. */
95
+ export function combineStyle(style?: React.CSSProperties, defaultStyle?: React.CSSProperties) {
96
+ if (style) {
97
+ return defaultStyle && style
98
+ ? { ...defaultStyle, ...style }
99
+ : style ?? defaultStyle;
100
+ }
101
+ return defaultStyle;
102
+ }
package/src/theme.ts ADDED
@@ -0,0 +1,346 @@
1
+ import { CSSProperties, useContext } from 'react';
2
+
3
+ import { TableConfigContext } from './config.js';
4
+ import { cx, nully } from './util.js';
5
+
6
+ /**
7
+ * Theming
8
+ * -------
9
+ *
10
+ * The stylesheet `datatable.css` contains all structural styling under stable, prefixed
11
+ * class names (`.dtbl-*`). Every color/spacing decision in it reads a CSS custom property
12
+ * (`--dtbl-*`) whose fallback value is the built-in default theme (`lightTheme`).
13
+ * A theme is a typed bundle of those custom properties, split into two halves that can be
14
+ * mixed and matched freely with an object spread:
15
+ *
16
+ * - `TableColors`: color scheme (backgrounds, borders, text and selection colors)
17
+ * - `TableMetrics`: everything else (cell/item padding, tree indent, resize cursor)
18
+ * - `TableTheme` is simply `TableColors & TableMetrics`, so any combination such as
19
+ * `{ ...darkColors, ...compactMetrics }` is a complete theme.
20
+ *
21
+ * Applying a theme sets the variables on the component's outer element (never on `:root`),
22
+ * so tables with different themes can coexist on one page.
23
+ *
24
+ * Ways to apply a theme:
25
+ * - App-wide/subtree default: `<TableConfig theme={darkTheme}>...</TableConfig>`
26
+ * - Whole page, including portals and `*Core` components: `applyTheme(darkTheme)`
27
+ * - Per table: `<DataTable theme={myTheme} .../>` (overrides the `TableConfig` theme)
28
+ * - Stylesheet-based: pass a string; it is added as a class to the outer element, and your
29
+ * stylesheet defines the `--dtbl-*` variables under that class, e.g.
30
+ *
31
+ * .compact-blue { --dtbl-cell-padding: 2px 4px; --dtbl-selected-bg: #cde; }
32
+ *
33
+ * When using `DataTableCore`/`TreeListCore`/`ListCore` (which render no outer element),
34
+ * apply the theme to your own container: `<table {...themeProps(myTheme)}>`.
35
+ */
36
+ export interface TableColors {
37
+ /** Sets the CSS `color-scheme` property on the container (not a --dtbl-* variable).
38
+ * `'light dark'` makes `light-dark(...)` color values (as used by the `auto*` presets)
39
+ * follow the browser's light/dark preference; `'light'`/`'dark'` also render matching
40
+ * scrollbars inside the scrollable wrapper. Note: `applyTheme` targets `<html>` by
41
+ * default, where `color-scheme: dark` affects the whole page's form controls and
42
+ * default canvas — theme a subtree or table instead if that's unwanted. */
43
+ colorScheme?: string;
44
+ /** Background of data rows and list items (--dtbl-row-bg). */
45
+ rowBackground?: string;
46
+ /** Background of the sticky header cells (--dtbl-header-bg; default: inherit, i.e. the
47
+ * row background, which the header row must repaint to cover scrolled data rows). */
48
+ headerBackground?: string;
49
+ /** Text color of rows and items (--dtbl-text; default: inherit from the page). */
50
+ textColor?: string;
51
+ /** Bottom border of all cells, as a full CSS border value (--dtbl-row-border). */
52
+ rowBorder?: string;
53
+ /** Background of selected rows/items (--dtbl-selected-bg). */
54
+ selectedBackground?: string;
55
+ /** Background of hovered selected rows (--dtbl-hover-selected-bg). */
56
+ hoverSelectedBackground?: string;
57
+ /** Background of hovered unselected rows (--dtbl-hover-unselected-bg). */
58
+ hoverUnselectedBackground?: string;
59
+ /** Background of rows whose (grand)parent row is selected, when the
60
+ * `highlightChildrenOfSelectedParents` item prop is enabled (--dtbl-parent-selected-bg). */
61
+ parentSelectedBackground?: string;
62
+ /** CSS `cursor` shown over the column-resize drag handle (--dtbl-resize-cursor).
63
+ * Can be a `url(...) x y, fallback` value; defaults to `defaultResizeCursor`. */
64
+ resizeCursor?: string;
65
+ }
66
+
67
+ export interface TableMetrics {
68
+ /** Padding of table cells, unless the `noPadding` item prop is set (--dtbl-cell-padding). */
69
+ cellPadding?: string;
70
+ /** Padding of list/tree items outside tables (--dtbl-item-padding). */
71
+ itemPadding?: string;
72
+ /** Indent per level of tree nesting (--dtbl-indent). A number means pixels. This is
73
+ * ignored by tables/trees that have an explicit `indentPerLevel` prop. */
74
+ treeIndent?: number | string;
75
+ /** Tint drawn over every other table row — the 1st, 3rd, 5th... (--dtbl-stripe-bg;
76
+ * default: transparent, i.e. no striping). Although this is a color, it lives in
77
+ * `TableMetrics` because a translucent
78
+ * value (see the `stripedRows` preset) reads correctly over any color scheme, making
79
+ * striping an independent layout choice. Selection and hover tints replace the stripe
80
+ * on their row. Note: with `virtualize`, off-screen rows collapse into placeholders, so
81
+ * stripe parity is relative to the rendered rows and can shift while scrolling. */
82
+ stripeBackground?: string;
83
+ }
84
+
85
+ /** A complete visual style for tables/lists: a color scheme plus metrics. The two halves
86
+ * are independent, so `{ ...darkColors, ...compactMetrics }` is a valid theme. */
87
+ export interface TableTheme extends TableColors, TableMetrics {
88
+ /** Extra class name(s) for the outer element, e.g. to add rules beyond the variables. */
89
+ className?: string;
90
+ }
91
+
92
+ /** The double-headed arrow drawn over a column-resize handle: a 40x30 PNG inlined as a data
93
+ * URI, so that the package ships no separate image asset and needs no bundler support for
94
+ * one. Exported for callers that want the image on their own resize affordances. */
95
+ export const resizeCursorImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAeCAYAAABe3VzdAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAGJoAABiaAZsyYXAAAAEbSURBVFhH7ZSLDsIgDAA3jf//wUZnb4GlEsbaTmUmuwSpPLobMMahI9M0zfUoSHUllPKU9kdqp+pHErwR6kJ7lr/Mvx0RkXuqFylNd8EtTsG9nIJ7aV40ta8qI3fU3Cljmjks4xiTn8Xdl8cSh1ZQJ7TA2CzqxS3olctEJV2CUblMRNJ8Bmty0paiNrV50rZM1rl1H7FJUCf4FIXIkr8U3Nzib8gBOcmd/q6yKcjb8Cafhpx5pVqYthhqK2kVr83Tcjq37iM2f8VMYkIJ7a2Shi1oAQuua4bENUkrXjlwCUJUMiIHbkHwSkblICQIPNDyUOu4NcKCv+IU3Ev4bESQs5iid+Qjkq6dF3UvDiPIalFKDrHFa/zBFg/DC/as2Q7ADo1PAAAAAElFTkSuQmCC';
96
+
97
+ /** The `resizeCursor` of every preset: `resizeCursorImage` with its hotspot on the arrow's
98
+ * pivot, degrading to the browser's own `col-resize` where images are unsupported. Kept in
99
+ * sync with the `--dtbl-resize-cursor` fallback in datatable.css. */
100
+ export const defaultResizeCursor = `url(${resizeCursorImage}) 30 15, col-resize`;
101
+
102
+ /** The dark scheme: near-black rows with green selection. */
103
+ export const darkColors: TableColors = {
104
+ colorScheme: 'dark',
105
+ rowBackground: '#121212',
106
+ headerBackground: 'inherit',
107
+ textColor: 'rgba(255, 255, 255, 0.87)',
108
+ rowBorder: '1px solid #2d2d2d',
109
+ selectedBackground: 'rgba(11, 58, 46, 0.85)',
110
+ hoverSelectedBackground: 'rgba(11, 58, 46, 1)',
111
+ hoverUnselectedBackground: 'rgba(11, 58, 46, 0.2)',
112
+ parentSelectedBackground: 'rgba(11, 58, 46, 0.2)',
113
+ resizeCursor: defaultResizeCursor,
114
+ };
115
+
116
+ /** The light counterpart of `darkColors` (green-tinted selection on white). These values
117
+ * equal the `var()` fallbacks in datatable.css except that the fallback text color is
118
+ * `inherit`, so this is (nearly) the appearance of an un-themed table. */
119
+ export const lightColors: TableColors = {
120
+ colorScheme: 'light',
121
+ rowBackground: '#ffffff',
122
+ headerBackground: 'inherit',
123
+ textColor: '#1d2321',
124
+ rowBorder: '1px solid #d9e0dd',
125
+ selectedBackground: 'rgba(11, 58, 46, 0.22)',
126
+ hoverSelectedBackground: 'rgba(11, 58, 46, 0.32)',
127
+ hoverUnselectedBackground: 'rgba(11, 58, 46, 0.08)',
128
+ parentSelectedBackground: 'rgba(11, 58, 46, 0.08)',
129
+ resizeCursor: defaultResizeCursor,
130
+ };
131
+
132
+ /** A cooler light scheme: gray header band, gray borders, blue selection. */
133
+ export const lightGrayColors: TableColors = {
134
+ colorScheme: 'light',
135
+ rowBackground: '#fbfcfd',
136
+ headerBackground: '#e9edf1',
137
+ textColor: '#1c1c1c',
138
+ rowBorder: '1px solid #c9d1d9',
139
+ selectedBackground: '#cee2f5',
140
+ hoverSelectedBackground: '#bdd7f0',
141
+ hoverUnselectedBackground: 'rgba(30, 60, 90, 0.06)',
142
+ parentSelectedBackground: 'rgba(30, 60, 90, 0.06)',
143
+ resizeCursor: defaultResizeCursor,
144
+ };
145
+
146
+ /** A softer dark scheme: gray rows with blue selection. */
147
+ export const darkGrayColors: TableColors = {
148
+ colorScheme: 'dark',
149
+ rowBackground: '#1c1c1c',
150
+ headerBackground: 'inherit',
151
+ textColor: 'rgba(255, 255, 255, 0.87)',
152
+ rowBorder: '1px solid #3a3a3a',
153
+ selectedBackground: '#2a4a68',
154
+ hoverSelectedBackground: '#345a7e',
155
+ hoverUnselectedBackground: 'rgba(255, 255, 255, 0.08)',
156
+ parentSelectedBackground: 'rgba(255, 255, 255, 0.08)',
157
+ resizeCursor: defaultResizeCursor,
158
+ };
159
+
160
+ /** A warm light scheme: cream rows, amber selection. */
161
+ export const lightAmberColors: TableColors = {
162
+ colorScheme: 'light',
163
+ rowBackground: '#fff8ec',
164
+ headerBackground: 'inherit',
165
+ textColor: '#4a3210',
166
+ rowBorder: '1px solid #e8d9bd',
167
+ selectedBackground: '#ffd9a0',
168
+ hoverSelectedBackground: '#f5c87e',
169
+ hoverUnselectedBackground: 'rgba(200, 140, 0, 0.10)',
170
+ parentSelectedBackground: 'rgba(200, 140, 0, 0.10)',
171
+ resizeCursor: defaultResizeCursor,
172
+ };
173
+
174
+ /** A warm dark scheme: deep-brown rows, amber selection. */
175
+ export const darkAmberColors: TableColors = {
176
+ colorScheme: 'dark',
177
+ rowBackground: '#211709',
178
+ headerBackground: 'inherit',
179
+ textColor: 'rgba(255, 243, 224, 0.9)',
180
+ rowBorder: '1px solid #4a3a1e',
181
+ selectedBackground: 'rgba(196, 128, 28, 0.5)',
182
+ hoverSelectedBackground: 'rgba(196, 128, 28, 0.65)',
183
+ hoverUnselectedBackground: 'rgba(255, 190, 92, 0.12)',
184
+ parentSelectedBackground: 'rgba(255, 190, 92, 0.12)',
185
+ resizeCursor: defaultResizeCursor,
186
+ };
187
+
188
+ /* The `auto*` schemes below follow the browser's light/dark preference, with no JavaScript
189
+ * listener: every color is a CSS `light-dark()` pair (supported by all major browsers since
190
+ * mid-2024), and `colorScheme: 'light dark'` is what tells the browser to pick a side based
191
+ * on the user's preference. Each pairs the light/dark presets of the same name. */
192
+
193
+ /** `lightColors` or `darkColors`, following the browser's light/dark preference. */
194
+ export const autoColors: TableColors = {
195
+ colorScheme: 'light dark',
196
+ rowBackground: 'light-dark(#ffffff, #121212)',
197
+ headerBackground: 'inherit',
198
+ textColor: 'light-dark(#1d2321, rgba(255, 255, 255, 0.87))',
199
+ rowBorder: '1px solid light-dark(#d9e0dd, #2d2d2d)',
200
+ selectedBackground: 'light-dark(rgba(11, 58, 46, 0.22), rgba(11, 58, 46, 0.85))',
201
+ hoverSelectedBackground: 'light-dark(rgba(11, 58, 46, 0.32), rgba(11, 58, 46, 1))',
202
+ hoverUnselectedBackground: 'light-dark(rgba(11, 58, 46, 0.08), rgba(11, 58, 46, 0.2))',
203
+ parentSelectedBackground: 'light-dark(rgba(11, 58, 46, 0.08), rgba(11, 58, 46, 0.2))',
204
+ resizeCursor: defaultResizeCursor,
205
+ };
206
+
207
+ /** `lightGrayColors` or `darkGrayColors`, following the browser's light/dark preference. */
208
+ export const autoGrayColors: TableColors = {
209
+ colorScheme: 'light dark',
210
+ rowBackground: 'light-dark(#fbfcfd, #1c1c1c)',
211
+ headerBackground: 'light-dark(#e9edf1, #1c1c1c)',
212
+ textColor: 'light-dark(#1c1c1c, rgba(255, 255, 255, 0.87))',
213
+ rowBorder: '1px solid light-dark(#c9d1d9, #3a3a3a)',
214
+ selectedBackground: 'light-dark(#cee2f5, #2a4a68)',
215
+ hoverSelectedBackground: 'light-dark(#bdd7f0, #345a7e)',
216
+ hoverUnselectedBackground: 'light-dark(rgba(30, 60, 90, 0.06), rgba(255, 255, 255, 0.08))',
217
+ parentSelectedBackground: 'light-dark(rgba(30, 60, 90, 0.06), rgba(255, 255, 255, 0.08))',
218
+ resizeCursor: defaultResizeCursor,
219
+ };
220
+
221
+ /** `lightAmberColors` or `darkAmberColors`, following the browser's light/dark preference. */
222
+ export const autoAmberColors: TableColors = {
223
+ colorScheme: 'light dark',
224
+ rowBackground: 'light-dark(#fff8ec, #211709)',
225
+ headerBackground: 'inherit',
226
+ textColor: 'light-dark(#4a3210, rgba(255, 243, 224, 0.9))',
227
+ rowBorder: '1px solid light-dark(#e8d9bd, #4a3a1e)',
228
+ selectedBackground: 'light-dark(#ffd9a0, rgba(196, 128, 28, 0.5))',
229
+ hoverSelectedBackground: 'light-dark(#f5c87e, rgba(196, 128, 28, 0.65))',
230
+ hoverUnselectedBackground: 'light-dark(rgba(200, 140, 0, 0.10), rgba(255, 190, 92, 0.12))',
231
+ parentSelectedBackground: 'light-dark(rgba(200, 140, 0, 0.10), rgba(255, 190, 92, 0.12))',
232
+ resizeCursor: defaultResizeCursor,
233
+ };
234
+
235
+ /** The default spacing, equal to the `var()` fallbacks in datatable.css. */
236
+ export const defaultMetrics: TableMetrics = {
237
+ cellPadding: '6px 6px',
238
+ itemPadding: '6px 10px',
239
+ treeIndent: 20,
240
+ };
241
+
242
+ /** Denser spacing, for information-heavy screens. */
243
+ export const compactMetrics: TableMetrics = {
244
+ cellPadding: '2px 6px',
245
+ itemPadding: '2px 8px',
246
+ treeIndent: 14,
247
+ };
248
+
249
+ /** Add-on: gives every other table row (starting with the first) a faint tint. Translucent,
250
+ * so it works over any color
251
+ * scheme — combine it with any theme, e.g. `{ ...darkTheme, ...stripedRows }`. */
252
+ export const stripedRows: TableMetrics = {
253
+ stripeBackground: 'rgba(128, 128, 128, 0.15)',
254
+ };
255
+
256
+ /** The default theme: `lightColors` with default spacing. */
257
+ export const lightTheme: TableTheme = { ...lightColors, ...defaultMetrics };
258
+ /** Dark theme (near-black rows, green selection). */
259
+ export const darkTheme: TableTheme = { ...darkColors, ...defaultMetrics };
260
+ /** Cooler light theme (gray header band, blue selection). */
261
+ export const lightGrayTheme: TableTheme = { ...lightGrayColors, ...defaultMetrics };
262
+ /** Softer dark theme (gray rows, blue selection). */
263
+ export const darkGrayTheme: TableTheme = { ...darkGrayColors, ...defaultMetrics };
264
+ /** Warm light theme (cream rows, amber selection). */
265
+ export const lightAmberTheme: TableTheme = { ...lightAmberColors, ...defaultMetrics };
266
+ /** Warm dark theme (deep-brown rows, amber selection). */
267
+ export const darkAmberTheme: TableTheme = { ...darkAmberColors, ...defaultMetrics };
268
+ /** `lightTheme` or `darkTheme`, following the browser's light/dark preference. */
269
+ export const autoTheme: TableTheme = { ...autoColors, ...defaultMetrics };
270
+ /** `lightGrayTheme` or `darkGrayTheme`, following the browser's light/dark preference. */
271
+ export const autoGrayTheme: TableTheme = { ...autoGrayColors, ...defaultMetrics };
272
+ /** `lightAmberTheme` or `darkAmberTheme`, following the browser's light/dark preference. */
273
+ export const autoAmberTheme: TableTheme = { ...autoAmberColors, ...defaultMetrics };
274
+
275
+ const themeVarNames: Record<Exclude<keyof TableTheme, 'className' | 'colorScheme'>, string> = {
276
+ rowBackground: '--dtbl-row-bg',
277
+ headerBackground: '--dtbl-header-bg',
278
+ textColor: '--dtbl-text',
279
+ rowBorder: '--dtbl-row-border',
280
+ cellPadding: '--dtbl-cell-padding',
281
+ itemPadding: '--dtbl-item-padding',
282
+ treeIndent: '--dtbl-indent',
283
+ stripeBackground: '--dtbl-stripe-bg',
284
+ selectedBackground: '--dtbl-selected-bg',
285
+ hoverSelectedBackground: '--dtbl-hover-selected-bg',
286
+ hoverUnselectedBackground: '--dtbl-hover-unselected-bg',
287
+ parentSelectedBackground: '--dtbl-parent-selected-bg',
288
+ resizeCursor: '--dtbl-resize-cursor',
289
+ };
290
+
291
+ /** Converts a theme to CSS custom properties, for the `style` of a container element. */
292
+ export function themeToCssVars(theme: TableTheme | string | nully): CSSProperties | undefined {
293
+ if (theme == null || typeof theme === 'string') {
294
+ return undefined;
295
+ }
296
+ let style: Record<string, string> = {};
297
+ if (theme.colorScheme != null) {
298
+ style.colorScheme = theme.colorScheme;
299
+ }
300
+ for (let key of Object.keys(themeVarNames) as Array<keyof typeof themeVarNames>) {
301
+ let value = theme[key];
302
+ if (value != null) {
303
+ style[themeVarNames[key]] = typeof value === 'number' ? `${value}px` : value;
304
+ }
305
+ }
306
+ return style as CSSProperties;
307
+ }
308
+
309
+ /** Applies a theme to a DOM element ― by default `<html>`, theming every table on the page
310
+ * (including tables inside portals and ones using the `*Core` components, which render no
311
+ * outer element of their own to carry the variables). Variables the theme doesn't specify
312
+ * are removed from the element, so the theme replaces any previously-applied one.
313
+ *
314
+ * This basically does `Object.assign(document.documentElement.style, themeToCssVars(theme))`
315
+ * except that `Object.assign` doesn't work on that `style`, so `setProperty` is used instead. */
316
+ export function applyTheme(theme: TableTheme | string | nully, element?: HTMLElement) {
317
+ const vars = themeToCssVars(theme) as Record<string, string> | undefined;
318
+ if (vars) {
319
+ const style = (element ?? document.documentElement).style;
320
+ for (let name of [...Object.values(themeVarNames), 'color-scheme']) {
321
+ const value = name === 'color-scheme' ? vars.colorScheme : vars[name];
322
+ if (value != null) {
323
+ style.setProperty(name, String(value));
324
+ } else {
325
+ style.removeProperty(name);
326
+ }
327
+ }
328
+ }
329
+ }
330
+
331
+ /** Converts a theme to `{ className, style }` for spreading onto a container element. */
332
+ export function themeProps(theme: TableTheme | string | nully) {
333
+ return {
334
+ className: typeof theme === 'string' ? theme : theme?.className,
335
+ style: themeToCssVars(theme),
336
+ };
337
+ }
338
+
339
+ /** Resolves the effective theme (the `theme` prop of a component if given, otherwise the
340
+ * `TableConfig` theme) into a class name and style to merge into a container element. */
341
+ export function useThemeProps(themeProp: TableTheme | string | nully): { className?: string, style?: CSSProperties } {
342
+ const config = useContext(TableConfigContext);
343
+ const theme = themeProp ?? config.theme;
344
+ const { className, style } = themeProps(theme);
345
+ return { className: cx(className) || undefined, style };
346
+ }