@lt-ui/table 0.0.0-stage → 0.0.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.
Files changed (132) hide show
  1. package/cells/cells.module.css +481 -0
  2. package/cells/field-cells.d.ts +118 -0
  3. package/cells/field-cells.js +48 -0
  4. package/cells/index.d.ts +29 -0
  5. package/cells/index.js +15 -0
  6. package/cells/square-select.d.ts +19 -0
  7. package/cells/square-select.js +37 -0
  8. package/cells/square.d.ts +16 -0
  9. package/cells/square.js +78 -0
  10. package/cells/table-cell-actions.d.ts +32 -0
  11. package/cells/table-cell-actions.js +36 -0
  12. package/cells/table-cell-checkbox.d.ts +13 -0
  13. package/cells/table-cell-checkbox.js +13 -0
  14. package/cells/table-cell-copy.d.ts +18 -0
  15. package/cells/table-cell-copy.js +32 -0
  16. package/cells/table-cell-date.d.ts +20 -0
  17. package/cells/table-cell-date.js +15 -0
  18. package/cells/table-cell-expand.d.ts +18 -0
  19. package/cells/table-cell-expand.js +17 -0
  20. package/cells/table-cell-file-upload.d.ts +27 -0
  21. package/cells/table-cell-file-upload.js +22 -0
  22. package/cells/table-cell-file.d.ts +27 -0
  23. package/cells/table-cell-file.js +29 -0
  24. package/cells/table-cell-image.d.ts +22 -0
  25. package/cells/table-cell-image.js +12 -0
  26. package/cells/table-cell-input.d.ts +22 -0
  27. package/cells/table-cell-input.js +22 -0
  28. package/cells/table-cell-link.d.ts +14 -0
  29. package/cells/table-cell-link.js +28 -0
  30. package/cells/table-cell-select.d.ts +44 -0
  31. package/cells/table-cell-select.js +30 -0
  32. package/cells/table-cell-switch.d.ts +8 -0
  33. package/cells/table-cell-switch.js +5 -0
  34. package/cells/table-cell-textarea.d.ts +22 -0
  35. package/cells/table-cell-textarea.js +68 -0
  36. package/cjs/cells/cells.module.css +481 -0
  37. package/cjs/cells/field-cells.js +87 -0
  38. package/cjs/cells/index.js +36 -0
  39. package/cjs/cells/square-select.js +77 -0
  40. package/cjs/cells/square.js +117 -0
  41. package/cjs/cells/table-cell-actions.js +75 -0
  42. package/cjs/cells/table-cell-checkbox.js +19 -0
  43. package/cjs/cells/table-cell-copy.js +71 -0
  44. package/cjs/cells/table-cell-date.js +22 -0
  45. package/cjs/cells/table-cell-expand.js +23 -0
  46. package/cjs/cells/table-cell-file-upload.js +61 -0
  47. package/cjs/cells/table-cell-file.js +38 -0
  48. package/cjs/cells/table-cell-image.js +18 -0
  49. package/cjs/cells/table-cell-input.js +61 -0
  50. package/cjs/cells/table-cell-link.js +34 -0
  51. package/cjs/cells/table-cell-select.js +36 -0
  52. package/cjs/cells/table-cell-switch.js +12 -0
  53. package/cjs/cells/table-cell-textarea.js +107 -0
  54. package/cjs/column-settings.js +128 -0
  55. package/cjs/columns.js +67 -0
  56. package/cjs/context.js +14 -0
  57. package/cjs/corner-settings.js +24 -0
  58. package/cjs/empty-function.js +8 -0
  59. package/cjs/features.js +40 -0
  60. package/cjs/header-filter.js +93 -0
  61. package/cjs/index.js +44 -0
  62. package/cjs/layout.js +34 -0
  63. package/cjs/locale/index.js +8 -0
  64. package/cjs/locale/messages.js +63 -0
  65. package/cjs/locale/use-locale.js +10 -0
  66. package/cjs/row-loading-border.js +79 -0
  67. package/cjs/selection.js +34 -0
  68. package/cjs/sort-icon.js +18 -0
  69. package/cjs/styles.module.css +674 -0
  70. package/cjs/table-head.js +45 -0
  71. package/cjs/table-pagination.js +25 -0
  72. package/cjs/table-row.js +62 -0
  73. package/cjs/table-search.js +74 -0
  74. package/cjs/table-toolbar.js +22 -0
  75. package/cjs/table.js +95 -0
  76. package/cjs/tanstack.js +2 -0
  77. package/cjs/types.js +2 -0
  78. package/cjs/use-pointer-sort.js +116 -0
  79. package/cjs/use-table.js +23 -0
  80. package/column-settings.d.ts +59 -0
  81. package/column-settings.js +88 -0
  82. package/columns.d.ts +18 -0
  83. package/columns.js +59 -0
  84. package/context.d.ts +7 -0
  85. package/context.js +10 -0
  86. package/corner-settings.d.ts +11 -0
  87. package/corner-settings.js +16 -0
  88. package/empty-function.d.ts +1 -0
  89. package/empty-function.js +4 -0
  90. package/features.d.ts +38 -0
  91. package/features.js +37 -0
  92. package/header-filter.d.ts +29 -0
  93. package/header-filter.js +54 -0
  94. package/index.d.ts +22 -0
  95. package/index.js +12 -0
  96. package/layout.d.ts +5 -0
  97. package/layout.js +27 -0
  98. package/locale/index.d.ts +3 -0
  99. package/locale/index.js +2 -0
  100. package/locale/messages.d.ts +40 -0
  101. package/locale/messages.js +60 -0
  102. package/locale/use-locale.d.ts +9 -0
  103. package/locale/use-locale.js +7 -0
  104. package/package.json +33 -4
  105. package/row-loading-border.d.ts +7 -0
  106. package/row-loading-border.js +40 -0
  107. package/selection.d.ts +8 -0
  108. package/selection.js +31 -0
  109. package/sort-icon.d.ts +8 -0
  110. package/sort-icon.js +10 -0
  111. package/styles.module.css +674 -0
  112. package/table-head.d.ts +6 -0
  113. package/table-head.js +39 -0
  114. package/table-pagination.d.ts +16 -0
  115. package/table-pagination.js +19 -0
  116. package/table-row.d.ts +21 -0
  117. package/table-row.js +56 -0
  118. package/table-search.d.ts +28 -0
  119. package/table-search.js +38 -0
  120. package/table-toolbar.d.ts +18 -0
  121. package/table-toolbar.js +16 -0
  122. package/table.d.ts +15 -0
  123. package/table.js +56 -0
  124. package/tanstack.d.ts +9 -0
  125. package/tanstack.js +1 -0
  126. package/types.d.ts +161 -0
  127. package/types.js +1 -0
  128. package/use-pointer-sort.d.ts +32 -0
  129. package/use-pointer-sort.js +113 -0
  130. package/use-table.d.ts +46 -0
  131. package/use-table.js +19 -0
  132. package/README.md +0 -3
package/columns.js ADDED
@@ -0,0 +1,59 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import React from 'react';
4
+ import clsx from 'clsx';
5
+ import { Checkbox } from '@lt-ui/uikit';
6
+ import { toggleRowSelection } from './selection';
7
+ import { ChevronIcon } from './sort-icon';
8
+ import styles from './styles.module.css';
9
+ import { useLocale } from './locale';
10
+ export const SELECTION_COLUMN_ID = '__select';
11
+ export const EXPAND_COLUMN_ID = '__expand';
12
+ // Подписи берутся из словаря языка, а хуки нельзя вызывать в самой функции колонки: вынесено в компоненты
13
+ function SelectAllCheckbox({ table }) {
14
+ const { t } = useLocale();
15
+ return (_jsx(Checkbox, { "aria-label": t('table.selectAll'), checked: table.getIsAllRowsSelected(), indeterminate: table.getIsSomeRowsSelected(), disabled: table.getRowCount() === 0, animated: false, onUpdate: checked => table.toggleAllRowsSelected(checked) }));
16
+ }
17
+ function SelectRowCheckbox({ row, table }) {
18
+ const { t } = useLocale();
19
+ return (_jsx(Checkbox, { "aria-label": t('table.selectRow'), checked: row.getIsSelected(), disabled: !row.getCanSelect(), animated: false,
20
+ // С Shift выбирается диапазон от прошлой отмеченной строки
21
+ onChange: event => toggleRowSelection(table, row, event.nativeEvent) }));
22
+ }
23
+ function ExpandButton({ row, icon, }) {
24
+ const { t } = useLocale();
25
+ return (_jsx("button", { type: "button", className: clsx(styles.expander, row.getIsExpanded() && styles.expanderOpen, icon && styles.expanderCustom), "aria-expanded": row.getIsExpanded(), "aria-label": row.getIsExpanded() ? t('table.collapseRow') : t('table.expandRow'), onClick: row.getToggleExpandedHandler(), children: icon ? icon(row.getIsExpanded()) : _jsx(ChevronIcon, {}) }));
26
+ }
27
+ /**
28
+ * Колонка с чекбоксами выбора строк и «выбрать все» в шапке. Клик с Shift выбирает диапазон. Состояние — `rowSelection`
29
+ * TanStack Table (`state` или `onRowSelectionChange`), недоступные строки задаёт опция `enableRowSelection`.
30
+ */
31
+ export function selectionColumn() {
32
+ return {
33
+ id: SELECTION_COLUMN_ID,
34
+ size: 52,
35
+ enableSorting: false,
36
+ enableHiding: false,
37
+ enableResizing: false,
38
+ meta: { align: 'center' },
39
+ header: ({ table }) => _jsx(SelectAllCheckbox, { table: table }),
40
+ cell: ({ row, table }) => _jsx(SelectRowCheckbox, { row: row, table: table }),
41
+ };
42
+ }
43
+ /**
44
+ * Колонка с кнопкой раскрытия строки: обычная кнопка с обводкой, как у меню действий. Ставьте её последней, там, где
45
+ * обычно действия строки. Нужны `getRowCanExpand` (или `getSubRows`) в опциях таблицы
46
+ * и `renderExpanded` у `Table` для содержимого.
47
+ */
48
+ export function expandColumn({ icon, } = {}) {
49
+ return {
50
+ id: EXPAND_COLUMN_ID,
51
+ size: 64,
52
+ enableSorting: false,
53
+ enableHiding: false,
54
+ enableResizing: false,
55
+ meta: { align: 'end' },
56
+ header: () => null,
57
+ cell: ({ row }) => (row.getCanExpand() ? _jsx(ExpandButton, { row: row, icon: icon }) : null),
58
+ };
59
+ }
package/context.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { TableVariant } from './types';
2
+ export declare const TableVariantProvider: import("react").Provider<TableVariant>;
3
+ /**
4
+ * Вид таблицы, внутри которой рисуется ячейка. Готовые ячейки (`TableCellInput`, `TableCellSelect`...) по нему выбирают
5
+ * оформление: в таблице `cells` — «квадратные» ячейки как в электронных таблицах, в остальных — обычные компоненты.
6
+ */
7
+ export declare const useTableVariant: () => TableVariant;
package/context.js ADDED
@@ -0,0 +1,10 @@
1
+ 'use client';
2
+ import { createContext, useContext, version } from 'react';
3
+ const VariantContext = createContext('rows');
4
+ // React 19 — `<Context value>`, React 18 — `<Context.Provider>`
5
+ export const TableVariantProvider = Number.parseInt(version, 10) >= 19 ? VariantContext : VariantContext.Provider;
6
+ /**
7
+ * Вид таблицы, внутри которой рисуется ячейка. Готовые ячейки (`TableCellInput`, `TableCellSelect`...) по нему выбирают
8
+ * оформление: в таблице `cells` — «квадратные» ячейки как в электронных таблицах, в остальных — обычные компоненты.
9
+ */
10
+ export const useTableVariant = () => useContext(VariantContext);
@@ -0,0 +1,11 @@
1
+ import React from 'react';
2
+ import type { RowData, Table } from './tanstack';
3
+ import type { TableColumnSettingsProps } from './column-settings';
4
+ /** Шестерёнка (контур иконки Gear из @lt-ui/icons) для триггера настроек в углу таблицы */
5
+ export declare const ColumnSettingsIcon: () => React.JSX.Element;
6
+ export type TableCornerSettings = Omit<TableColumnSettingsProps<never>, 'table'>;
7
+ /** Шестерёнка в правом верхнем углу таблицы: настройки столбцов без отдельной панели над таблицей */
8
+ export declare function TableCornerColumnSettings<T extends RowData>({ table, options, }: Readonly<{
9
+ table: Table<T>;
10
+ options: TableCornerSettings;
11
+ }>): React.JSX.Element;
@@ -0,0 +1,16 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import React from 'react';
4
+ import { Button } from '@lt-ui/uikit';
5
+ import { TableColumnSettings } from './column-settings';
6
+ import styles from './styles.module.css';
7
+ import { useLocale } from './locale';
8
+ /** Шестерёнка (контур иконки Gear из @lt-ui/icons) для триггера настроек в углу таблицы */
9
+ export const ColumnSettingsIcon = () => (_jsxs("svg", { viewBox: "0 0 24 24", width: "24", height: "24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true, children: [_jsx("path", { d: "M12 16.5c2.49 0 4.5-2.01 4.5-4.5S14.49 7.5 12 7.5 7.5 9.51 7.5 12s2.01 4.5 4.5 4.5z" }), _jsx("path", { d: "M17.22 6.1c.24.22.46.45.68.68l2.56.36c.41.73.73 1.5.95 2.31l-1.55 2.07s.02.64 0 .96l1.55 2.07c-.21.81-.54 1.58-.95 2.31l-2.56.36s-.44.46-.68.68l-.36 2.56c-.73.41-1.5.73-2.31.95l-2.07-1.55c-.32.02-.64.02-.96 0l-2.07 1.55c-.81-.21-1.58-.54-2.31-.95l-.36-2.56a21.8 21.8 0 0 1-.68-.68l-2.56-.36c-.41-.73-.73-1.5-.95-2.31l1.55-2.07s-.02-.64 0-.96L2.59 9.45c.21-.81.54-1.58.95-2.31l2.56-.36c.22-.23.45-.46.68-.68l.36-2.56c.73-.41 1.5-.73 2.31-.95l2.07 1.55c.32-.02.64-.02.96 0l2.07-1.55c.81.21 1.58.54 2.31.95l.36 2.56z" })] }));
10
+ /** Шестерёнка в правом верхнем углу таблицы: настройки столбцов без отдельной панели над таблицей */
11
+ export function TableCornerColumnSettings({ table, options, }) {
12
+ var _a, _b;
13
+ const { t } = useLocale();
14
+ const label = (_a = options.label) !== null && _a !== void 0 ? _a : t('table.columns.label');
15
+ return (_jsx("div", { className: styles.cornerSettings, children: _jsx(TableColumnSettings, { table: table, ...options, trigger: (_b = options.trigger) !== null && _b !== void 0 ? _b : (_jsx(Button, { variant: "ghost", size: "s", iconOnly: true, compact: true, "aria-label": label, "aria-haspopup": "dialog", children: _jsx(ColumnSettingsIcon, {}) })) }) }));
16
+ }
@@ -0,0 +1 @@
1
+ export declare const emptyFunction: () => void;
@@ -0,0 +1,4 @@
1
+ // Пустая функция для значений по умолчанию. Наружу из пакета не экспортируется.
2
+ export const emptyFunction = () => {
3
+ // Намеренно пусто
4
+ };
package/features.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { TableColumnMeta } from './types';
2
+ /** Features required by the LT UI renderer. Pagination remains opt-in via manualPagination: false. */
3
+ export declare const defaultTableFeatures: {
4
+ columnFilteringFeature: import("@tanstack/table-core").TableFeature;
5
+ columnOrderingFeature: import("@tanstack/table-core").TableFeature;
6
+ columnPinningFeature: import("@tanstack/table-core").TableFeature;
7
+ columnResizingFeature: import("@tanstack/table-core").TableFeature;
8
+ columnSizingFeature: import("@tanstack/table-core").TableFeature;
9
+ columnVisibilityFeature: import("@tanstack/table-core").TableFeature;
10
+ globalFilteringFeature: import("@tanstack/table-core").TableFeature;
11
+ rowExpandingFeature: import("@tanstack/table-core").TableFeature;
12
+ rowPaginationFeature: import("@tanstack/table-core").TableFeature;
13
+ rowSelectionFeature: import("@tanstack/table-core").TableFeature;
14
+ rowSortingFeature: import("@tanstack/table-core").TableFeature;
15
+ filteredRowModel: (table: import("@tanstack/table-core").Table<any, any>) => () => import("@tanstack/table-core").RowModel<any, any>;
16
+ sortedRowModel: (table: import("@tanstack/table-core").Table<any, any>) => () => import("@tanstack/table-core").RowModel<any, any>;
17
+ expandedRowModel: (table: import("@tanstack/table-core").Table<any, any>) => () => import("@tanstack/table-core").RowModel<any, any>;
18
+ paginatedRowModel: (table: import("@tanstack/table-core").Table<any, any>) => () => import("@tanstack/table-core").RowModel<any, any>;
19
+ filterFns: {
20
+ includesString: import("@tanstack/table-core").CreatedFilterFn<any, any>;
21
+ includesStringSensitive: import("@tanstack/table-core").CreatedFilterFn<any, any>;
22
+ equalsString: import("@tanstack/table-core").CreatedFilterFn<any, any>;
23
+ arrIncludes: import("@tanstack/table-core").CreatedFilterFn<any, any>;
24
+ equals: import("@tanstack/table-core").CreatedFilterFn<any, any>;
25
+ weakEquals: import("@tanstack/table-core").CreatedFilterFn<any, any>;
26
+ inNumberRange: import("@tanstack/table-core").CreatedFilterFn<any, any>;
27
+ };
28
+ sortFns: {
29
+ alphanumeric: import("@tanstack/table-core").CreatedSortFn<any, any>;
30
+ alphanumericCaseSensitive: import("@tanstack/table-core").CreatedSortFn<any, any>;
31
+ basic: import("@tanstack/table-core").CreatedSortFn<any, any>;
32
+ datetime: import("@tanstack/table-core").CreatedSortFn<any, any>;
33
+ text: import("@tanstack/table-core").CreatedSortFn<any, any>;
34
+ textCaseSensitive: import("@tanstack/table-core").CreatedSortFn<any, any>;
35
+ };
36
+ columnMeta: TableColumnMeta;
37
+ };
38
+ export type LtTableFeatures = typeof defaultTableFeatures;
package/features.js ADDED
@@ -0,0 +1,37 @@
1
+ import { columnFilteringFeature, columnOrderingFeature, columnPinningFeature, columnResizingFeature, columnSizingFeature, columnVisibilityFeature, globalFilteringFeature, rowExpandingFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, tableFeatures, metaHelper, createFilteredRowModel, createSortedRowModel, createExpandedRowModel, createPaginatedRowModel, filterFn_includesString, filterFn_includesStringSensitive, filterFn_equalsString, filterFn_arrIncludes, filterFn_equals, filterFn_weakEquals, filterFn_inNumberRange, sortFn_alphanumeric, sortFn_alphanumericCaseSensitive, sortFn_basic, sortFn_datetime, sortFn_text, sortFn_textCaseSensitive, } from '@tanstack/react-table';
2
+ /** Features required by the LT UI renderer. Pagination remains opt-in via manualPagination: false. */
3
+ export const defaultTableFeatures = tableFeatures({
4
+ columnFilteringFeature,
5
+ columnOrderingFeature,
6
+ columnPinningFeature,
7
+ columnResizingFeature,
8
+ columnSizingFeature,
9
+ columnVisibilityFeature,
10
+ globalFilteringFeature,
11
+ rowExpandingFeature,
12
+ rowPaginationFeature,
13
+ rowSelectionFeature,
14
+ rowSortingFeature,
15
+ filteredRowModel: createFilteredRowModel(),
16
+ sortedRowModel: createSortedRowModel(),
17
+ expandedRowModel: createExpandedRowModel(),
18
+ paginatedRowModel: createPaginatedRowModel(),
19
+ filterFns: {
20
+ includesString: filterFn_includesString,
21
+ includesStringSensitive: filterFn_includesStringSensitive,
22
+ equalsString: filterFn_equalsString,
23
+ arrIncludes: filterFn_arrIncludes,
24
+ equals: filterFn_equals,
25
+ weakEquals: filterFn_weakEquals,
26
+ inNumberRange: filterFn_inNumberRange,
27
+ },
28
+ sortFns: {
29
+ alphanumeric: sortFn_alphanumeric,
30
+ alphanumericCaseSensitive: sortFn_alphanumericCaseSensitive,
31
+ basic: sortFn_basic,
32
+ datetime: sortFn_datetime,
33
+ text: sortFn_text,
34
+ textCaseSensitive: sortFn_textCaseSensitive,
35
+ },
36
+ columnMeta: metaHelper(),
37
+ });
@@ -0,0 +1,29 @@
1
+ import React from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import type { Column, RowData } from './tanstack';
4
+ /** Фильтр в ячейке шапки: текстовое поле или список значений. Значение — `columnFilters` TanStack Table */
5
+ export type TableColumnFilter = {
6
+ type?: 'text';
7
+ placeholder?: string;
8
+ debounce?: number;
9
+ } | {
10
+ type: 'select';
11
+ options: {
12
+ value: string;
13
+ label: string;
14
+ }[];
15
+ placeholder?: string;
16
+ };
17
+ type Props<T extends RowData> = {
18
+ column: Column<T, unknown>;
19
+ filter: TableColumnFilter;
20
+ /** Обычное содержимое шапки (заголовок, кнопка сортировки) */
21
+ children: ReactNode;
22
+ title: string;
23
+ };
24
+ /**
25
+ * Шапка колонки с фильтром: справа от заголовка кнопка-лупа, по нажатию заголовок заменяется полем ввода
26
+ * (или списком) прямо в ячейке. Пока фильтр задан, поле остаётся открытым, а лупа подсвечена.
27
+ */
28
+ export declare function HeaderFilter<T extends RowData>({ column, filter, children, title }: Readonly<Props<T>>): React.JSX.Element;
29
+ export {};
@@ -0,0 +1,54 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import React, { useEffect, useRef, useState } from 'react';
4
+ import clsx from 'clsx';
5
+ import { List, ListItem, Popover } from '@lt-ui/uikit';
6
+ import styles from './styles.module.css';
7
+ import { useLocale } from './locale';
8
+ const FilterIcon = () => (_jsxs("svg", { viewBox: "0 0 24 24", width: "16", height: "16", fill: "none", "aria-hidden": true, children: [_jsx("circle", { cx: "11", cy: "11", r: "6", stroke: "currentColor", strokeWidth: "1.75" }), _jsx("path", { d: "m15.5 15.5 4 4", stroke: "currentColor", strokeWidth: "1.75", strokeLinecap: "round" })] }));
9
+ const CloseIcon = () => (_jsx("svg", { viewBox: "0 0 24 24", width: "14", height: "14", fill: "none", "aria-hidden": true, children: _jsx("path", { d: "m6 6 12 12M18 6 6 18", stroke: "currentColor", strokeWidth: "1.75", strokeLinecap: "round" }) }));
10
+ /**
11
+ * Шапка колонки с фильтром: справа от заголовка кнопка-лупа, по нажатию заголовок заменяется полем ввода
12
+ * (или списком) прямо в ячейке. Пока фильтр задан, поле остаётся открытым, а лупа подсвечена.
13
+ */
14
+ export function HeaderFilter({ column, filter, children, title }) {
15
+ var _a, _b, _c;
16
+ const { t } = useLocale();
17
+ const current = column.getFilterValue();
18
+ const [open, setOpen] = useState(current != null && current !== '');
19
+ const [text, setText] = useState(typeof current === 'string' ? current : '');
20
+ const [menu, setMenu] = useState(false);
21
+ const input = useRef(null);
22
+ const delay = filter.type === 'select' ? 0 : ((_a = filter.debounce) !== null && _a !== void 0 ? _a : 300);
23
+ // Внешний сброс фильтра (например, «Сбросить всё») закрывает поле
24
+ useEffect(() => {
25
+ if (current == null || current === '')
26
+ setText('');
27
+ }, [current]);
28
+ useEffect(() => {
29
+ if (filter.type === 'select')
30
+ return undefined;
31
+ if ((text || undefined) === (current || undefined))
32
+ return undefined;
33
+ const timer = setTimeout(() => column.setFilterValue(text || undefined), delay);
34
+ return () => clearTimeout(timer);
35
+ // `current` и `column` стабильны для нашей цели: пауза перезапускается только при вводе
36
+ // eslint-disable-next-line react-hooks/exhaustive-deps
37
+ }, [text]);
38
+ useEffect(() => {
39
+ var _a;
40
+ if (open)
41
+ (_a = input.current) === null || _a === void 0 ? void 0 : _a.focus();
42
+ }, [open]);
43
+ const active = current != null && current !== '';
44
+ const close = () => {
45
+ setText('');
46
+ column.setFilterValue(undefined);
47
+ setOpen(false);
48
+ };
49
+ const selected = filter.type === 'select' ? filter.options.find(option => option.value === current) : undefined;
50
+ return (_jsxs("span", { className: clsx(styles.headFilter, open && styles.headFilterOpen), "data-active": active || undefined, children: [_jsx("span", { className: styles.headFilterTitle, children: children }), open && filter.type !== 'select' && (_jsx("input", { ref: input, type: "text", className: styles.headFilterInput, "aria-label": t('table.filter', { title }), placeholder: (_b = filter.placeholder) !== null && _b !== void 0 ? _b : title, value: text, onChange: event => setText(event.target.value), onKeyDown: event => event.key === 'Escape' && close(), onBlur: () => !text && !active && setOpen(false) })), open && filter.type === 'select' && (_jsx(Popover, { open: menu, onOpenChange: setMenu, placement: "bottom-start", arrow: false, offset: 4, anchor: _jsx("button", { type: "button", className: styles.headFilterSelect, "aria-label": t('table.filter', { title }), "aria-haspopup": "listbox", "aria-expanded": menu, children: selected ? (selected.label) : (_jsx("span", { className: styles.headFilterPlaceholder, children: (_c = filter.placeholder) !== null && _c !== void 0 ? _c : title })) }), children: _jsx(List, { size: "m", selectionMode: "single", "aria-label": title, value: typeof current === 'string' ? current : null, onUpdate: value => {
51
+ column.setFilterValue(typeof value === 'string' ? value : undefined);
52
+ setMenu(false);
53
+ }, children: filter.options.map(option => (_jsx(ListItem, { value: option.value, text: option.label }, option.value))) }) })), _jsx("button", { type: "button", className: styles.headFilterButton, "aria-label": open ? t('table.resetFilter') : t('table.filter', { title }), onClick: open ? close : () => setOpen(true), children: open ? _jsx(CloseIcon, {}) : _jsx(FilterIcon, {}) })] }));
54
+ }
package/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import './types';
2
+ export { Table } from './table';
3
+ export { useTable, tableDefaultColumn } from './use-table';
4
+ export { selectionColumn, expandColumn, SELECTION_COLUMN_ID, EXPAND_COLUMN_ID } from './columns';
5
+ export { TablePagination } from './table-pagination';
6
+ export { toggleRowSelection } from './selection';
7
+ export { TableColumnSettings, useTableColumnSettings } from './column-settings';
8
+ export { ColumnSettingsIcon } from './corner-settings';
9
+ export * from './cells';
10
+ export type { UseTableOptions } from './use-table';
11
+ export type { TablePaginationProps } from './table-pagination';
12
+ export type { TableColumnSettingsProps, TableColumnSettingsValue } from './column-settings';
13
+ export type { TableProps, TableVariant, TableSize, TableAlign } from './types';
14
+ export { TableSearch } from './table-search';
15
+ export { TableToolbar } from './table-toolbar';
16
+ export type { TableColumnFilter } from './header-filter';
17
+ export type { TableSearchProps } from './table-search';
18
+ export type { TableToolbarProps } from './table-toolbar';
19
+ export { defaultTableFeatures } from './features';
20
+ export type { LtTableFeatures } from './features';
21
+ export type { TableColumnMeta } from './types';
22
+ export type { ColumnDef, RowData, RowSelectionState, SortingState, PaginationState, ColumnFiltersState, Table as TableInstance, Column as TableColumn, Row as TableRowInstance, } from './tanstack';
package/index.js ADDED
@@ -0,0 +1,12 @@
1
+ import './types';
2
+ export { Table } from './table';
3
+ export { useTable, tableDefaultColumn } from './use-table';
4
+ export { selectionColumn, expandColumn, SELECTION_COLUMN_ID, EXPAND_COLUMN_ID } from './columns';
5
+ export { TablePagination } from './table-pagination';
6
+ export { toggleRowSelection } from './selection';
7
+ export { TableColumnSettings, useTableColumnSettings } from './column-settings';
8
+ export { ColumnSettingsIcon } from './corner-settings';
9
+ export * from './cells';
10
+ export { TableSearch } from './table-search';
11
+ export { TableToolbar } from './table-toolbar';
12
+ export { defaultTableFeatures } from './features';
package/layout.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { CSSProperties } from 'react';
2
+ import type { Column, RowData } from './tanstack';
3
+ /** Ширина, заданная колонке явно. У TanStack по умолчанию 150px: `useTable` сбрасывает её, колонка тогда по содержимому */
4
+ export declare function cellStyle<T extends RowData>(column: Column<T, unknown>): CSSProperties;
5
+ export declare function cellClass<T extends RowData>(column: Column<T, unknown>, part?: 'header' | 'cell'): string;
package/layout.js ADDED
@@ -0,0 +1,27 @@
1
+ import clsx from 'clsx';
2
+ import styles from './styles.module.css';
3
+ const maxWidth = (pinned, size, maxSize) => {
4
+ if (pinned)
5
+ return `${size}px`;
6
+ return maxSize && maxSize < 100000 ? `${maxSize}px` : undefined;
7
+ };
8
+ /** Ширина, заданная колонке явно. У TanStack по умолчанию 150px: `useTable` сбрасывает её, колонка тогда по содержимому */
9
+ export function cellStyle(column) {
10
+ const size = column.getSize();
11
+ const { minSize, maxSize } = column.columnDef;
12
+ const pinned = column.getIsPinned();
13
+ return {
14
+ width: size > 0 ? `${size}px` : undefined,
15
+ minWidth: minSize && minSize > 0 ? `${minSize}px` : (size && `${size}px`) || undefined,
16
+ // Закреплённая колонка не шире своего `size`: от него считается отступ следующих закреплённых колонок
17
+ maxWidth: maxWidth(pinned, size, maxSize),
18
+ ...(pinned === 'start' && { insetInlineStart: `${column.getStart('start')}px` }),
19
+ ...(pinned === 'end' && { insetInlineEnd: `${column.getAfter('end')}px` }),
20
+ };
21
+ }
22
+ export function cellClass(column, part) {
23
+ var _a;
24
+ const meta = column.columnDef.meta;
25
+ const pinned = column.getIsPinned();
26
+ return clsx(styles[`align-${(_a = meta === null || meta === void 0 ? void 0 : meta.align) !== null && _a !== void 0 ? _a : 'start'}`], (meta === null || meta === void 0 ? void 0 : meta.ellipsis) && styles.ellipsis, pinned && styles.sticky, pinned === 'end' && styles.stickyEnd, part === 'cell' && (meta === null || meta === void 0 ? void 0 : meta.strong) && styles.strong, meta === null || meta === void 0 ? void 0 : meta.className, part === 'header' && (meta === null || meta === void 0 ? void 0 : meta.headerClassName), part === 'cell' && (meta === null || meta === void 0 ? void 0 : meta.cellClassName));
27
+ }
@@ -0,0 +1,3 @@
1
+ export { useLocale } from './use-locale';
2
+ export { en as enTableMessages, ru as ruTableMessages } from './messages';
3
+ export type { TableMessages } from './messages';
@@ -0,0 +1,2 @@
1
+ export { useLocale } from './use-locale';
2
+ export { en as enTableMessages, ru as ruTableMessages } from './messages';
@@ -0,0 +1,40 @@
1
+ /** Строки `@lt-ui/table`: подписи для скринридера, кнопки и пустое состояние. Переопределяются через `messages` провайдера */
2
+ export interface TableMessages {
3
+ table: {
4
+ empty: string;
5
+ selectAll: string;
6
+ selectRow: string;
7
+ expandRow: string;
8
+ collapseRow: string;
9
+ filter: string;
10
+ resetFilter: string;
11
+ search: {
12
+ placeholder: string;
13
+ label: string;
14
+ };
15
+ toolbar: string;
16
+ columns: {
17
+ label: string;
18
+ move: string;
19
+ show: string;
20
+ reset: string;
21
+ };
22
+ cell: {
23
+ copy: string;
24
+ copied: string;
25
+ actions: string;
26
+ remove: string;
27
+ download: string;
28
+ select: string;
29
+ expand: string;
30
+ collapse: string;
31
+ };
32
+ fileSize: {
33
+ b: string;
34
+ kb: string;
35
+ mb: string;
36
+ };
37
+ };
38
+ }
39
+ export declare const ru: TableMessages;
40
+ export declare const en: TableMessages;
@@ -0,0 +1,60 @@
1
+ export const ru = {
2
+ table: {
3
+ empty: 'Нет данных',
4
+ selectAll: 'Выбрать все',
5
+ selectRow: 'Выбрать строку',
6
+ expandRow: 'Раскрыть строку',
7
+ collapseRow: 'Свернуть строку',
8
+ filter: 'Фильтр: {title}',
9
+ resetFilter: 'Сбросить фильтр',
10
+ search: { placeholder: 'Поиск', label: 'Поиск по таблице' },
11
+ toolbar: 'Инструменты таблицы',
12
+ columns: {
13
+ label: 'Столбцы',
14
+ move: 'Переместить «{title}»',
15
+ show: 'Показать «{title}»',
16
+ reset: 'Сбросить',
17
+ },
18
+ cell: {
19
+ copy: 'Скопировать',
20
+ copied: 'Скопировано',
21
+ actions: 'Действия',
22
+ remove: 'Удалить',
23
+ download: 'Скачать',
24
+ select: 'Выберите',
25
+ expand: 'Раскрыть',
26
+ collapse: 'Свернуть',
27
+ },
28
+ fileSize: { b: 'Б', kb: 'КБ', mb: 'МБ' },
29
+ },
30
+ };
31
+ export const en = {
32
+ table: {
33
+ empty: 'No data',
34
+ selectAll: 'Select all',
35
+ selectRow: 'Select row',
36
+ expandRow: 'Expand row',
37
+ collapseRow: 'Collapse row',
38
+ filter: 'Filter: {title}',
39
+ resetFilter: 'Reset filter',
40
+ search: { placeholder: 'Search', label: 'Search the table' },
41
+ toolbar: 'Table tools',
42
+ columns: {
43
+ label: 'Columns',
44
+ move: 'Move “{title}”',
45
+ show: 'Show “{title}”',
46
+ reset: 'Reset',
47
+ },
48
+ cell: {
49
+ copy: 'Copy',
50
+ copied: 'Copied',
51
+ actions: 'Actions',
52
+ remove: 'Remove',
53
+ download: 'Download',
54
+ select: 'Select',
55
+ expand: 'Expand',
56
+ collapse: 'Collapse',
57
+ },
58
+ fileSize: { b: 'B', kb: 'KB', mb: 'MB' },
59
+ },
60
+ };
@@ -0,0 +1,9 @@
1
+ import type { TableMessages } from './messages';
2
+ /**
3
+ * Язык и переводчик строк таблицы: язык берётся у ближайшего `ThemeProvider` или `LocaleProvider`
4
+ * из `@lt-ui/uikit`, строки переопределяются в `messages` под ключом `table`.
5
+ */
6
+ export declare const useLocale: () => {
7
+ locale: import("@lt-ui/i18n").Locale;
8
+ t: import("@lt-ui/i18n").Translate<TableMessages>;
9
+ };
@@ -0,0 +1,7 @@
1
+ import { createUseLocale } from '@lt-ui/i18n';
2
+ import { en, ru } from './messages';
3
+ /**
4
+ * Язык и переводчик строк таблицы: язык берётся у ближайшего `ThemeProvider` или `LocaleProvider`
5
+ * из `@lt-ui/uikit`, строки переопределяются в `messages` под ключом `table`.
6
+ */
7
+ export const useLocale = createUseLocale({ en, ru });
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@lt-ui/table",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "LT UI",
5
+ "license": "MIT",
6
+ "engines": {
7
+ "node": ">=20.19.0"
8
+ },
9
+ "peerDependencies": {
10
+ "@lt-ui/uikit": "0.0.1",
11
+ "@tanstack/react-table": "^9.3.1",
12
+ "react": "^18.0.0 || ^19.0.0"
13
+ },
14
+ "dependencies": {
15
+ "@lt-ui/i18n": "0.0.1",
16
+ "clsx": "^2.1.1"
17
+ },
18
+ "main": "./cjs/index.js",
19
+ "module": "./index.js",
20
+ "types": "./index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./index.d.ts",
24
+ "import": "./index.js",
25
+ "require": "./cjs/index.js"
26
+ }
27
+ },
28
+ "sideEffects": [
29
+ "*.css"
30
+ ],
31
+ "private": false,
32
+ "publishConfig": {
33
+ "access": "public"
34
+ }
35
+ }
@@ -0,0 +1,7 @@
1
+ import React from 'react';
2
+ /**
3
+ * Граница строки с операцией: тонкая дорожка по периметру и яркий отрезок, который бежит по ней с постоянной скоростью.
4
+ * Размер берётся у строки (`ResizeObserver`), поэтому анимация подстраивается под любую ширину и высоту таблицы:
5
+ * длина отрезка и время оборота считаются от периметра, а не от угла, как у вращающегося градиента.
6
+ */
7
+ export declare function RowLoadingBorder(): React.JSX.Element;
@@ -0,0 +1,40 @@
1
+ 'use client';
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import React, { useLayoutEffect, useRef, useState } from 'react';
4
+ import styles from './styles.module.css';
5
+ const RADIUS = 8;
6
+ /** Скорость бегущего отрезка по границе, px/с: одинаковая у узкой и широкой строки */
7
+ const SPEED = 1100;
8
+ /**
9
+ * Граница строки с операцией: тонкая дорожка по периметру и яркий отрезок, который бежит по ней с постоянной скоростью.
10
+ * Размер берётся у строки (`ResizeObserver`), поэтому анимация подстраивается под любую ширину и высоту таблицы:
11
+ * длина отрезка и время оборота считаются от периметра, а не от угла, как у вращающегося градиента.
12
+ */
13
+ export function RowLoadingBorder() {
14
+ const root = useRef(null);
15
+ const [size, setSize] = useState({ width: 0, height: 0 });
16
+ useLayoutEffect(() => {
17
+ var _a;
18
+ const row = (_a = root.current) === null || _a === void 0 ? void 0 : _a.closest('tr');
19
+ if (!row)
20
+ return undefined;
21
+ const measure = () => setSize({ width: row.clientWidth, height: row.clientHeight });
22
+ measure();
23
+ if (typeof ResizeObserver === 'undefined')
24
+ return undefined;
25
+ const observer = new ResizeObserver(measure);
26
+ observer.observe(row);
27
+ return () => observer.disconnect();
28
+ }, []);
29
+ const { width, height } = size;
30
+ const w = Math.max(width - 2, 0);
31
+ const h = Math.max(height - 2, 0);
32
+ const r = Math.min(RADIUS, w / 2, h / 2);
33
+ // Периметр скруглённого прямоугольника
34
+ const perimeter = 2 * (w + h) - (8 - 2 * Math.PI) * r;
35
+ const head = Math.min(Math.max(perimeter * 0.22, 80), 260);
36
+ return (_jsx("svg", { ref: root, className: styles.loadingBorder, width: width, height: height, viewBox: `0 0 ${width} ${height}`, "aria-hidden": true, children: width > 0 && (_jsxs(_Fragment, { children: [_jsx("rect", { className: styles.loadingTrack, x: 1, y: 1, width: w, height: h, rx: r }), _jsx("rect", { className: styles.loadingRun, x: 1, y: 1, width: w, height: h, rx: r, strokeDasharray: `${head} ${Math.max(perimeter - head, 0)}`, style: {
37
+ '--table-row-perimeter': `${perimeter}px`,
38
+ animationDuration: `${Math.max(perimeter / SPEED, 0.8)}s`,
39
+ } })] })) }));
40
+ }
package/selection.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { Row, RowData, Table } from './tanstack';
2
+ /**
3
+ * Переключает выбор строки; с `shiftKey` выбирает (или снимает) весь диапазон между прошлой и этой строкой,
4
+ * как в файловых менеджерах и таблицах Gravity. Недоступные для выбора строки пропускаются.
5
+ */
6
+ export declare function toggleRowSelection<T extends RowData>(table: Table<T>, row: Row<T>, event?: {
7
+ shiftKey?: boolean;
8
+ }): void;
package/selection.js ADDED
@@ -0,0 +1,31 @@
1
+ /** Строка, от которой считается диапазон при выборе с Shift: для каждой таблицы своя */
2
+ const anchors = new WeakMap();
3
+ /**
4
+ * Переключает выбор строки; с `shiftKey` выбирает (или снимает) весь диапазон между прошлой и этой строкой,
5
+ * как в файловых менеджерах и таблицах Gravity. Недоступные для выбора строки пропускаются.
6
+ */
7
+ export function toggleRowSelection(table, row, event) {
8
+ const checked = !row.getIsSelected();
9
+ const anchor = anchors.get(table);
10
+ const rows = table.getRowModel().rows;
11
+ const from = anchor === undefined ? -1 : rows.findIndex(item => item.id === anchor);
12
+ const to = rows.findIndex(item => item.id === row.id);
13
+ anchors.set(table, row.id);
14
+ if (!(event === null || event === void 0 ? void 0 : event.shiftKey) || from < 0 || to < 0) {
15
+ row.toggleSelected(checked);
16
+ return;
17
+ }
18
+ const [start, end] = from < to ? [from, to] : [to, from];
19
+ table.setRowSelection(old => {
20
+ const next = { ...old };
21
+ rows.slice(start, end + 1).forEach(item => {
22
+ if (!item.getCanSelect())
23
+ return;
24
+ if (checked)
25
+ next[item.id] = true;
26
+ else
27
+ delete next[item.id];
28
+ });
29
+ return next;
30
+ });
31
+ }
package/sort-icon.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+ type Direction = false | 'asc' | 'desc';
3
+ /** Две стрелки: активная — тёмная, вторая — приглушена */
4
+ export declare const SortIcon: ({ direction }: {
5
+ direction: Direction;
6
+ }) => React.JSX.Element;
7
+ export declare const ChevronIcon: () => React.JSX.Element;
8
+ export {};