@eifi1/ui-kit 0.34.0 → 0.35.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.
- package/README.md +82 -38
- package/dist/billing/billing-banner.d.ts +5 -2
- package/dist/billing/billing-banner.js.map +1 -1
- package/dist/billing/plan-limit-notice.d.ts +5 -2
- package/dist/billing/plan-limit-notice.js.map +1 -1
- package/dist/chart.js.map +1 -1
- package/dist/components/amount-input.d.ts +0 -3
- package/dist/components/amount-input.js +2 -2
- package/dist/components/amount-input.js.map +1 -1
- package/dist/components/calculator.d.ts +1 -4
- package/dist/components/calculator.js +1 -3
- package/dist/components/calculator.js.map +1 -1
- package/dist/components/chart-zoom.d.ts +0 -37
- package/dist/components/chart-zoom.js +1 -28
- package/dist/components/chart-zoom.js.map +1 -1
- package/dist/components/chip-input.d.ts +0 -4
- package/dist/components/chip-input.js +1 -5
- package/dist/components/chip-input.js.map +1 -1
- package/dist/components/combobox.d.ts +1 -1
- package/dist/components/combobox.js.map +1 -1
- package/dist/components/copy-button.d.ts +5 -1
- package/dist/components/copy-button.js.map +1 -1
- package/dist/components/currency-option-list.d.ts +3 -8
- package/dist/components/currency-option-list.js +1 -29
- package/dist/components/currency-option-list.js.map +1 -1
- package/dist/components/danger-confirm.d.ts +3 -3
- package/dist/components/danger-confirm.js.map +1 -1
- package/dist/components/data-table-filter-popover.d.ts +1 -1
- package/dist/components/data-table-filter-popover.js +1 -1
- package/dist/components/data-table-filter-popover.js.map +1 -1
- package/dist/components/data-table-labels.d.ts +1 -42
- package/dist/components/data-table-labels.js +2 -31
- package/dist/components/data-table-labels.js.map +1 -1
- package/dist/components/data-table-shared.d.ts +17 -1
- package/dist/components/data-table-shared.js +22 -0
- package/dist/components/data-table-shared.js.map +1 -1
- package/dist/components/data-table.d.ts +12 -2
- package/dist/components/data-table.js +18 -14
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/dialog-frame.d.ts +3 -1
- package/dist/components/dialog-frame.js.map +1 -1
- package/dist/components/dropdown.d.ts +18 -15
- package/dist/components/dropdown.js +11 -3
- package/dist/components/dropdown.js.map +1 -1
- package/dist/components/entity-combobox.d.ts +1 -1
- package/dist/components/entity-combobox.js.map +1 -1
- package/dist/components/field-base.d.ts +0 -5
- package/dist/components/field-base.js +0 -5
- package/dist/components/field-base.js.map +1 -1
- package/dist/components/field-parts.d.ts +3 -11
- package/dist/components/field-parts.js +1 -9
- package/dist/components/field-parts.js.map +1 -1
- package/dist/components/field-strip.d.ts +8 -23
- package/dist/components/field-strip.js +24 -22
- package/dist/components/field-strip.js.map +1 -1
- package/dist/components/field-sync.d.ts +0 -4
- package/dist/components/field-sync.js +0 -4
- package/dist/components/field-sync.js.map +1 -1
- package/dist/components/field.d.ts +4 -4
- package/dist/components/field.js.map +1 -1
- package/dist/components/full-bleed-dialog.js +2 -2
- package/dist/components/full-bleed-dialog.js.map +1 -1
- package/dist/components/hover-menu.d.ts +6 -13
- package/dist/components/hover-menu.js +3 -3
- package/dist/components/hover-menu.js.map +1 -1
- package/dist/components/inline-entity-combobox.d.ts +1 -1
- package/dist/components/inline-entity-combobox.js.map +1 -1
- package/dist/components/modal.d.ts +9 -1
- package/dist/components/modal.js +7 -4
- package/dist/components/modal.js.map +1 -1
- package/dist/components/multi-select.d.ts +5 -16
- package/dist/components/multi-select.js +5 -10
- package/dist/components/multi-select.js.map +1 -1
- package/dist/components/number-input.d.ts +0 -3
- package/dist/components/number-input.js +2 -4
- package/dist/components/number-input.js.map +1 -1
- package/dist/components/popover.js +2 -2
- package/dist/components/popover.js.map +1 -1
- package/dist/components/series-chart.js.map +1 -1
- package/dist/components/server-wake.d.ts +0 -6
- package/dist/components/server-wake.js.map +1 -1
- package/dist/components/settings-fields.d.ts +4 -2
- package/dist/components/settings-fields.js.map +1 -1
- package/dist/components/stat-tile.d.ts +8 -2
- package/dist/components/stat-tile.js.map +1 -1
- package/dist/components/swipeable-row.d.ts +2 -17
- package/dist/components/swipeable-row.js +11 -16
- package/dist/components/swipeable-row.js.map +1 -1
- package/dist/components/tooltip.d.ts +9 -1
- package/dist/components/tooltip.js +20 -5
- package/dist/components/tooltip.js.map +1 -1
- package/dist/components/translation-review.d.ts +10 -2
- package/dist/components/translation-review.js +11 -3
- package/dist/components/translation-review.js.map +1 -1
- package/dist/components/use-table-state.d.ts +31 -3
- package/dist/components/use-table-state.js +53 -8
- package/dist/components/use-table-state.js.map +1 -1
- package/dist/components/user-avatar.d.ts +2 -2
- package/dist/components/user-avatar.js.map +1 -1
- package/dist/components/wizard-stepper.d.ts +1 -4
- package/dist/components/wizard-stepper.js +2 -3
- package/dist/components/wizard-stepper.js.map +1 -1
- package/dist/currencies.d.ts +23 -0
- package/dist/currencies.js +38 -0
- package/dist/currencies.js.map +1 -0
- package/dist/demo/demo-banner.d.ts +7 -2
- package/dist/demo/demo-banner.js.map +1 -1
- package/dist/eslint/index.d.ts +83 -0
- package/dist/eslint/index.js +69 -0
- package/dist/eslint/index.js.map +1 -0
- package/dist/eslint/role-utilities.d.ts +48 -0
- package/dist/eslint/role-utilities.generated.d.ts +2 -0
- package/dist/eslint/role-utilities.generated.js +143 -0
- package/dist/eslint/role-utilities.generated.js.map +1 -0
- package/dist/eslint/role-utilities.js +43 -0
- package/dist/eslint/role-utilities.js.map +1 -0
- package/dist/feedback/feedback-menu.d.ts +2 -2
- package/dist/feedback/feedback-menu.js.map +1 -1
- package/dist/feedback/feedback-thread.d.ts +3 -8
- package/dist/feedback/feedback-thread.js +0 -2
- package/dist/feedback/feedback-thread.js.map +1 -1
- package/dist/hooks/use-dismiss.d.ts +16 -3
- package/dist/hooks/use-dismiss.js +14 -2
- package/dist/hooks/use-dismiss.js.map +1 -1
- package/dist/i18n/kit-labels.d.ts +14 -4
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/i18n/locales/en.js +1 -1
- package/dist/i18n/locales/en.js.map +2 -2
- package/dist/i18n/locales/fr.js +3 -2
- package/dist/i18n/locales/fr.js.map +1 -1
- package/dist/i18n/locales/it.js +3 -2
- package/dist/i18n/locales/it.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/refs.d.ts +13 -0
- package/dist/lib/refs.js +15 -0
- package/dist/lib/refs.js.map +1 -0
- package/dist/rhf/fields.d.ts +10 -10
- package/dist/rhf/fields.js.map +1 -1
- package/dist/rhf/form-core.d.ts +5 -4
- package/dist/rhf/form-core.js.map +1 -1
- package/dist/rhf/form.d.ts +7 -36
- package/dist/rhf/form.js +1 -16
- package/dist/rhf/form.js.map +1 -1
- package/dist/rhf/line-items.d.ts +1 -1
- package/dist/rhf/line-items.js.map +1 -1
- package/dist/rhf/use-rhf-wizard-step.js.map +1 -1
- package/dist/rhf.js.map +1 -1
- package/dist/shell/option-switcher-menu.d.ts +5 -17
- package/dist/shell/option-switcher-menu.js +1 -3
- package/dist/shell/option-switcher-menu.js.map +1 -1
- package/dist/shell/role-switcher.d.ts +1 -4
- package/dist/shell/role-switcher.js +2 -3
- package/dist/shell/role-switcher.js.map +1 -1
- package/dist/shell/topbar-action-menu.d.ts +7 -19
- package/dist/shell/topbar-action-menu.js +1 -3
- package/dist/shell/topbar-action-menu.js.map +1 -1
- package/dist/shell/topbar-controls.d.ts +3 -12
- package/dist/shell/topbar-controls.js +6 -9
- package/dist/shell/topbar-controls.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/viewport.d.ts +25 -2
- package/dist/testing/viewport.js +61 -10
- package/dist/testing/viewport.js.map +1 -1
- package/dist/theme/palette-presets.d.ts +0 -7
- package/dist/theme/palette-presets.js +0 -279
- package/dist/theme/palette-presets.js.map +1 -1
- package/dist/wizard/types.d.ts +0 -5
- package/dist/wizard/types.js +1 -5
- package/dist/wizard/types.js.map +1 -1
- package/package.json +9 -1
- package/src/billing/billing-banner.tsx +5 -2
- package/src/billing/plan-limit-notice.tsx +5 -2
- package/src/chart.ts +5 -3
- package/src/components/amount-input.tsx +2 -6
- package/src/components/calculator.tsx +2 -7
- package/src/components/chart-zoom.tsx +4 -47
- package/src/components/chip-input.tsx +0 -7
- package/src/components/combobox.tsx +1 -1
- package/src/components/copy-button.tsx +5 -1
- package/src/components/currency-option-list.tsx +8 -42
- package/src/components/danger-confirm.tsx +3 -3
- package/src/components/data-table-filter-popover.tsx +2 -1
- package/src/components/data-table-labels.ts +2 -84
- package/src/components/data-table-shared.tsx +55 -2
- package/src/components/data-table.tsx +29 -17
- package/src/components/dialog-frame.tsx +3 -1
- package/src/components/dropdown.tsx +42 -18
- package/src/components/entity-combobox.tsx +1 -1
- package/src/components/field-base.tsx +0 -11
- package/src/components/field-parts.tsx +5 -19
- package/src/components/field-strip.tsx +9 -25
- package/src/components/field-sync.tsx +0 -7
- package/src/components/field.tsx +4 -4
- package/src/components/full-bleed-dialog.tsx +4 -3
- package/src/components/hover-menu.tsx +12 -16
- package/src/components/inline-entity-combobox.tsx +1 -1
- package/src/components/modal.tsx +20 -4
- package/src/components/multi-select.tsx +13 -30
- package/src/components/number-input.tsx +3 -8
- package/src/components/popover.tsx +5 -3
- package/src/components/series-chart.tsx +1 -1
- package/src/components/server-wake.tsx +0 -6
- package/src/components/settings-fields.tsx +4 -2
- package/src/components/stat-tile.tsx +8 -2
- package/src/components/swipeable-row.tsx +15 -37
- package/src/components/tooltip.tsx +37 -6
- package/src/components/translation-review.tsx +25 -7
- package/src/components/use-table-state.ts +91 -10
- package/src/components/user-avatar.tsx +2 -2
- package/src/components/wizard-stepper.tsx +2 -6
- package/src/currencies.ts +70 -0
- package/src/demo/demo-banner.tsx +7 -2
- package/src/eslint/index.ts +161 -0
- package/src/eslint/role-utilities.generated.ts +146 -0
- package/src/eslint/role-utilities.ts +99 -0
- package/src/feedback/feedback-menu.tsx +2 -2
- package/src/feedback/feedback-thread.tsx +3 -8
- package/src/hooks/use-dismiss.ts +39 -4
- package/src/i18n/kit-labels.tsx +15 -5
- package/src/i18n/locales/fr.ts +3 -2
- package/src/i18n/locales/it.ts +3 -2
- package/src/index.ts +3 -1
- package/src/lib/refs.ts +22 -0
- package/src/rhf/fields.tsx +10 -10
- package/src/rhf/form-core.tsx +5 -4
- package/src/rhf/form.tsx +7 -43
- package/src/rhf/line-items.tsx +1 -1
- package/src/rhf/use-rhf-wizard-step.ts +4 -4
- package/src/rhf.ts +3 -2
- package/src/shell/option-switcher-menu.tsx +5 -22
- package/src/shell/role-switcher.tsx +2 -6
- package/src/shell/topbar-action-menu.tsx +7 -24
- package/src/shell/topbar-controls.tsx +6 -18
- package/src/testing/index.ts +3 -1
- package/src/testing/viewport.ts +125 -19
- package/src/theme/palette-presets.ts +7 -293
- package/src/wizard/types.ts +0 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/use-table-state.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useLocation, useSearchParams } from \"react-router\";\nimport { readStored, writeStored } from \"../lib/safe-storage\";\nimport {\n decodeFilterValue,\n encodeFilterValue,\n isFilterActive,\n resolveFilter,\n} from \"./data-table-filters\";\nimport { decodeSorts, encodeSorts, normalizeSorts, type SortState } from \"./data-table-sort\";\nimport type { DataTableColumn, FilterState, ServerPagination } from \"./data-table\";\n\n// ---------- Persisted + URL-encoded view state ----------\n//\n// Moved here with `useTableState` when `DataTable` was split: these are what the hook\n// reads and writes, and nothing else in the table ever called them.\n\ninterface PersistedState {\n // Multi-sort array; blobs from before the upgrade hold a single {key, dir}\n // object (or null) — read back through normalizeSorts.\n sort: SortState[] | { key: string; dir: string } | null;\n filters: FilterState;\n pageSize: number | \"all\";\n widths?: Record<string, number>;\n hidden?: string[];\n}\n\nexport const DEFAULT_PERSIST_PREFIX = \"hbui-table:\";\n\nfunction loadPersisted(storageKey: string | undefined, prefix: string): Partial<PersistedState> {\n if (!storageKey) return {};\n const raw = readStored(prefix + storageKey);\n if (!raw) return {};\n try {\n const parsed = JSON.parse(raw) as Partial<PersistedState>;\n return parsed && typeof parsed === \"object\" ? parsed : {};\n } catch {\n return {}; // corrupt JSON — the storage access itself is guarded by readStored\n }\n}\n\n/** The blob that would be stored — also the value the effect below compares by, so\n * the comparison and the write can never disagree about what \"unchanged\" means. */\nfunction serializePersisted(state: PersistedState): string {\n return JSON.stringify(state);\n}\n\n// ---------- URL sync helpers ----------\n\nconst URL_FILTER_PREFIX = \"f.\";\nconst URL_SORT_KEY = \"sort\";\nconst URL_PAGE_KEY = \"p\";\nconst URL_PAGE_SIZE_KEY = \"ps\";\n/** The free-text search term — managed only by {@link useTableUrlState}, and only when\n * it is asked to (`search: true`); a plain `urlSync` table leaves a `q` alone. */\nconst URL_SEARCH_KEY = \"q\";\n\n/**\n * How a table is mirrored into the URL: `true`, or `{ prefix }` for a table that shares\n * its page with another URL-synced one. The prefix is put verbatim in front of EVERY key\n * the table writes and reads — `{ prefix: \"inv.\" }` gives `inv.f.<column>`, `inv.sort`,\n * `inv.p`, `inv.ps` (and `inv.q`) — so two tables on one page stop sharing a sort and a\n * page. Without one the keys are unprefixed, as they always were.\n */\nexport type TableUrlSync = boolean | { prefix?: string };\n\n/** The query keys of one table, with its prefix applied. */\ninterface UrlKeys {\n filter: string;\n sort: string;\n page: string;\n pageSize: string;\n search: string;\n}\n\nfunction urlKeys(prefix = \"\"): UrlKeys {\n return {\n filter: prefix + URL_FILTER_PREFIX,\n sort: prefix + URL_SORT_KEY,\n page: prefix + URL_PAGE_KEY,\n pageSize: prefix + URL_PAGE_SIZE_KEY,\n search: prefix + URL_SEARCH_KEY,\n };\n}\n\n/** `urlSync` split into \"is it on\" and \"under which prefix\". */\nfunction resolveTableUrlSync(urlSync: TableUrlSync | undefined): { enabled: boolean; prefix: string } {\n if (!urlSync) return { enabled: false, prefix: \"\" };\n return { enabled: true, prefix: urlSync === true ? \"\" : (urlSync.prefix ?? \"\") };\n}\n\n/** What {@link readTableUrlState} found in a query string. */\nexport interface TableUrlState {\n sorts?: SortState[];\n filters?: FilterState;\n /** `Infinity` for `ps=all`. */\n pageSize?: number;\n /** 0-based (the URL's `p` is 1-based). */\n page?: number;\n}\n\n/**\n * What a table's URL says, read out of a query string: the column filters (`f.<key>`),\n * the sort, the page size and the 0-based page. Absent keys are absent here too, so a\n * caller can tell \"not in the link\" from \"the default\". The same reader `urlSync` uses\n * on mount, exported for an owner that keeps the state itself — see\n * {@link useTableUrlState}.\n *\n * Pass the ROUTER's query string — the one `setSearchParams` writes — and the table's\n * `prefix` when it has one (see {@link TableUrlSync}).\n *\n * This read `window.location.search` until 0.7.0, which is the same string only under a\n * BrowserRouter. Under a HashRouter the router's query lives after the `#`\n * (`/#/tx?f.payee=Rewe`) and `window.location.search` is empty: a shared link opened\n * unfiltered, and the table's first write then replaced the link's filter with its own\n * empty state. Reading and writing through `useSearchParams` is one source for both\n * directions under every router, MemoryRouter included.\n */\nexport function readTableUrlState<T>(\n sp: URLSearchParams,\n columns: DataTableColumn<T>[],\n prefix?: string,\n): TableUrlState {\n const keys = urlKeys(prefix);\n const out: TableUrlState = {};\n\n const filters: FilterState = {};\n for (const col of columns) {\n const filter = resolveFilter(col);\n if (!filter) continue;\n const raw = sp.get(keys.filter + col.key);\n if (raw == null) continue;\n filters[col.key] = decodeFilterValue(filter, raw);\n }\n if (Object.keys(filters).length) out.filters = filters;\n\n const sortRaw = sp.get(keys.sort);\n if (sortRaw) {\n const decoded = decodeSorts(sortRaw, new Set(columns.map((c) => c.key)));\n if (decoded.length) out.sorts = decoded;\n }\n\n const psRaw = sp.get(keys.pageSize);\n if (psRaw === \"all\") out.pageSize = Infinity;\n else if (psRaw && Number(psRaw) > 0) out.pageSize = Number(psRaw);\n\n const pRaw = sp.get(keys.page);\n if (pRaw && Number(pRaw) >= 1) out.page = Number(pRaw) - 1;\n\n return out;\n}\n\n/**\n * The managed part of the query string, as a string, for comparing by VALUE.\n *\n * Everything the table puts in the address and nothing else, in a fixed order.\n * `columns` is walked for its keys only, which is why it can be left out of the\n * effect's dependencies without lying: a new column ARRAY carrying the same keys\n * produces the same signature, and a genuinely different set of filterable columns\n * produces a different one.\n */\nfunction urlSignature<T>(\n columns: DataTableColumn<T>[],\n sorts: SortState[],\n filters: FilterState,\n pageSize: number,\n page: number,\n defaultPageSize: number,\n keys: UrlKeys,\n): string {\n const parts: string[] = [];\n for (const col of columns) {\n const state = filters[col.key];\n if (!state || !isFilterActive(state)) continue;\n const enc = encodeFilterValue(state);\n if (enc != null) parts.push(`${keys.filter}${col.key}=${enc}`);\n }\n parts.push(`${keys.sort}=${encodeSorts(sorts)}`);\n parts.push(\n `${keys.pageSize}=${\n pageSize === Infinity ? \"all\" : pageSize === defaultPageSize ? \"\" : String(pageSize)\n }`,\n );\n parts.push(`${keys.page}=${page > 0 ? String(page + 1) : \"\"}`);\n return parts.join(\"&\");\n}\n\nfunction writeUrlState<T>(\n setSearchParams: ReturnType<typeof useSearchParams>[1],\n columns: DataTableColumn<T>[],\n sorts: SortState[],\n filters: FilterState,\n pageSize: number,\n page: number,\n defaultPageSize: number,\n // `undefined`: the search term is not ours to manage, and a `q` is left as it is.\n search: string | undefined,\n // The current entry's route state, carried over the replace. A query rewrite is not\n // a navigation, and dropping the state would, for one, lose the mark a URL-bound\n // dialog's opener leaves there (see useDialogParam).\n state: unknown,\n keys: UrlKeys,\n): void {\n setSearchParams(\n (prev) => {\n const next = new URLSearchParams(prev);\n // clear managed keys\n for (const col of columns) next.delete(keys.filter + col.key);\n next.delete(keys.sort);\n next.delete(keys.page);\n next.delete(keys.pageSize);\n if (search !== undefined) {\n next.delete(keys.search);\n if (search.trim()) next.set(keys.search, search);\n }\n // write filters\n for (const col of columns) {\n const state = filters[col.key];\n if (!state || !isFilterActive(state)) continue;\n const enc = encodeFilterValue(state);\n if (enc != null) next.set(keys.filter + col.key, enc);\n }\n // write sort\n const sortEnc = encodeSorts(sorts);\n if (sortEnc) next.set(keys.sort, sortEnc);\n // write page size if non-default\n if (pageSize === Infinity) next.set(keys.pageSize, \"all\");\n else if (pageSize !== defaultPageSize) next.set(keys.pageSize, String(pageSize));\n // write page if not first\n if (page > 0) next.set(keys.page, String(page + 1));\n return next;\n },\n { replace: true, state },\n );\n}\n\n/**\n * Where a table's view lives: what it is sorted and filtered by, which page, how wide\n * the columns are and which are hidden — plus the two places that outlives a render.\n *\n * Lifted out of `DataTable`, which was 984 lines and twenty hooks in one function. This\n * is the part that is genuinely about STATE rather than about drawing, and the three\n * rules it encodes are easy to lose among the markup:\n *\n * * **The URL is read once, on mount.** A shared or deep link populates the initial view;\n * after that the state is local, or the browser's own history would fight the user's\n * next click.\n * * **Sorting and filtering are optionally CONTROLLED.** A server-driven table passes\n * state and a callback and owns them; everything else is self-owned. That is the\n * `sortsProp ?? internalSorts` pair, and it is why the setters are exposed separately.\n * * **Persistence writes on every change, the URL only when asked.** `storageKey` is the\n * per-table identity; `urlSync` is opt-in because only some tables want their view in\n * a shareable address.\n * * **A controlled filter or sort that changes sends the table back to page 1.** See\n * the note at the reset below.\n */\nexport function useTableState<T>({\n columns,\n storageKey,\n storageKeyPrefix,\n urlSync: urlSyncOption,\n defaultPageSize,\n sortsProp,\n filtersProp,\n}: {\n columns: DataTableColumn<T>[];\n storageKey?: string;\n storageKeyPrefix: string;\n urlSync?: TableUrlSync;\n defaultPageSize: number;\n sortsProp?: SortState[];\n filtersProp?: FilterState;\n}) {\n const { enabled: urlSync, prefix: urlPrefix } = resolveTableUrlSync(urlSyncOption);\n const keys = useMemo(() => urlKeys(urlPrefix), [urlPrefix]);\n // Called unconditionally (a Router is required either way — see src/data-table.ts),\n // and the SAME pair is used to read and to write; see `readTableUrlState`.\n const [searchParams, setSearchParams] = useSearchParams();\n const location = useLocation();\n // Read URL once on mount so URL-encoded views (e.g. shared links, deep links from\n // other pages) populate initial state. After mount, state is local.\n const [urlInitial] = useState<TableUrlState>(() =>\n urlSync ? readTableUrlState(searchParams, columns, urlPrefix) : {},\n );\n const initial = useMemo(\n () => loadPersisted(storageKey, storageKeyPrefix),\n [storageKey, storageKeyPrefix],\n );\n const [internalSorts, setInternalSorts] = useState<SortState[]>(() =>\n urlInitial.sorts !== undefined ? urlInitial.sorts : normalizeSorts(initial.sort),\n );\n const [internalFilters, setInternalFilters] = useState<FilterState>(\n () => urlInitial.filters ?? initial.filters ?? {},\n );\n // Controlled when the owner passes state + callback (server-driven tables);\n // self-owned otherwise.\n const sorts = sortsProp ?? internalSorts;\n const filters = filtersProp ?? internalFilters;\n const [page, setPage] = useState(() => urlInitial.page ?? 0);\n\n // ---- Controlled filters/sorts reset the page ----\n //\n // A self-owned table resets to page 1 in the filter handlers. A CONTROLLED one could\n // not: the handlers hand the change to the owner and return, and `page` lives here,\n // where the owner has no way to reach it — so narrowing a filter from outside (a\n // saved view, a chip dismissed above the table) left a client-side table on page 4\n // of what was now two pages, clamped to the last one instead of the first.\n //\n // So the table does it: whenever the controlled VALUE changes, back to the first\n // page. Compared by value, because a controlled prop is a fresh object on every\n // parent render. Adjusted during render rather than in an effect, so the stale page\n // is never painted and never written to the URL. Not on mount: a deep link's `p=3`\n // must survive the owner's first render. (In `serverPagination` mode this state is\n // unused — the owner's `page` is the page, and resetting it stays the owner's job.)\n const controlledSig =\n sortsProp !== undefined || filtersProp !== undefined\n ? JSON.stringify([sortsProp ?? null, filtersProp ?? null])\n : null;\n const [seenControlledSig, setSeenControlledSig] = useState(controlledSig);\n if (seenControlledSig !== controlledSig) {\n setSeenControlledSig(controlledSig);\n setPage(0);\n }\n const [pageSize, setPageSize] = useState<number>(() => {\n if (urlInitial.pageSize !== undefined) return urlInitial.pageSize;\n if (initial.pageSize === \"all\") return Infinity;\n if (typeof initial.pageSize === \"number\" && initial.pageSize > 0) return initial.pageSize;\n return defaultPageSize;\n });\n const [widths, setWidths] = useState<Record<string, number>>(() => initial.widths ?? {});\n const [hiddenCols, setHiddenCols] = useState<Set<string>>(() => new Set(initial.hidden ?? []));\n const [showSettings, setShowSettings] = useState(false);\n const headRefs = useMemo(() => new Map<string, HTMLTableCellElement>(), []);\n\n // ---- Writing out: both of these compare by VALUE ----\n //\n // A CONTROLLED table (`sorts`/`filters` props plus callbacks — every server-driven\n // one) receives a freshly-built object on every render of the page around it, and\n // `{}` is never `===` the `{}` before it. Keyed on identity, both effects below\n // therefore fired on every unrelated parent render: persistence wrote the same JSON\n // into `localStorage` each time — a synchronous main-thread write, on a page whose\n // other half may be a form being typed into — and the URL one handed react-router a\n // `replace` it answers with a render, which is the loop the audit records. A `ref`\n // holding what was last written is what makes \"changed\" mean changed.\n const lastPersisted = useRef<string | null>(null);\n const persisted = !storageKey\n ? \"\"\n : serializePersisted({\n sort: sorts,\n filters,\n pageSize: pageSize === Infinity ? \"all\" : pageSize,\n widths,\n hidden: Array.from(hiddenCols),\n });\n useEffect(() => {\n if (!storageKey) return;\n // The destination is part of the signature: two tables can hold identical state,\n // and a table that swaps `storageKey` has to write under the new one even though\n // nothing about the view changed.\n const target = storageKeyPrefix + storageKey;\n const sig = `${target}\\u0000${persisted}`;\n if (lastPersisted.current === sig) return;\n lastPersisted.current = sig;\n writeStored(target, persisted);\n }, [storageKey, storageKeyPrefix, persisted]);\n\n const lastUrl = useRef<string | null>(null);\n const urlSig = urlSync\n ? urlSignature(columns, sorts, filters, pageSize, page, defaultPageSize, keys)\n : \"\";\n useEffect(() => {\n if (!urlSync) return;\n if (lastUrl.current === urlSig) return;\n lastUrl.current = urlSig;\n // `columns` is deliberately not a dependency and does not need to be: the\n // signature above is computed from it, so a column set that would produce a\n // different address produces a different signature first.\n writeUrlState(setSearchParams, columns, sorts, filters, pageSize, page, defaultPageSize, undefined, location.state, keys);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [urlSync, urlSig]);\n\n return {\n sorts,\n filters,\n setInternalSorts,\n setInternalFilters,\n page,\n setPage,\n pageSize,\n setPageSize,\n widths,\n setWidths,\n hiddenCols,\n setHiddenCols,\n showSettings,\n setShowSettings,\n headRefs,\n };\n}\n\n// ---------- Owner-held table state, mirrored to the URL ----------\n\nexport interface UseTableUrlStateOptions<T> {\n /** The table's columns — read for their keys and filter types only. */\n columns: DataTableColumn<T>[];\n /** Default 25. A page size equal to it is left out of the URL. */\n defaultPageSize?: number;\n /** Mirror the state into the URL and seed it from there on mount. Default true.\n * `{ prefix }` puts a prefix in front of every key, for a page with two URL-synced\n * tables — see {@link TableUrlSync}. */\n urlSync?: TableUrlSync;\n /** Shorthand for `urlSync: { prefix }`; wins over a prefix given there. */\n urlPrefix?: string;\n /** Also hold a free-text search term, under `q`. Off by default, so a `q` that\n * belongs to someone else on the page is never touched. */\n search?: boolean;\n}\n\n/** The part of {@link DataTableProps} a server-driven table takes from its owner. */\nexport interface TableUrlStateProps {\n serverPagination: ServerPagination;\n filters: FilterState;\n onFiltersChange: (next: FilterState) => void;\n sorts: SortState[];\n onSortsChange: (next: SortState[]) => void;\n}\n\nexport interface UseTableUrlStateReturn {\n /** 0-based. */\n page: number;\n setPage: (page: number) => void;\n pageSize: number;\n /** Also back to the first page. */\n setPageSize: (pageSize: number) => void;\n filters: FilterState;\n /** Also back to the first page. */\n setFilters: (next: FilterState) => void;\n sorts: SortState[];\n /** Also back to the first page. */\n setSorts: (next: SortState[]) => void;\n /** The search term (`\"\"` unless `search: true`). */\n search: string;\n /** Also back to the first page. */\n setSearch: (next: string) => void;\n /**\n * Everything the table needs, to spread onto it:\n * `<DataTable {...table.tableProps(data?.total ?? 0, { isLoading })} rows={…} … />`.\n */\n tableProps: (total: number, options?: { isLoading?: boolean }) => TableUrlStateProps;\n}\n\ninterface OwnedState {\n sorts: SortState[];\n filters: FilterState;\n pageSize: number;\n page: number;\n search: string;\n}\n\n/**\n * The controlled state of a `serverPagination` table — filters, sorts, page, page size\n * and optionally a search term — kept by the OWNER and mirrored into the URL in the\n * table's own scheme (`f.<key>`, `sort`, `p`, `ps`, and `q`).\n *\n * A server-driven table owns none of this: the owner has to hold it to turn it into\n * the query that fetches `rows`, and until now it also had to restate the table's URL\n * codec to keep the view bookmarkable (kastlan's use-server-table.ts copied\n * `readUrlState` / `writeUrlState` to do it). Same rules as `urlSync`:\n *\n * * **The URL is read once, on mount** — a shared or deep link (see {@link filterHref})\n * seeds the view; after that the state is local and written out with `replace`.\n * * **Any change but the page itself goes back to page 1** — a narrower filter must not\n * leave the user on page 7 of 2.\n * * **Written by value**: an unchanged view writes nothing, however often the owner\n * renders.\n *\n * Mapping the state onto the backend's query parameters stays the owner's: that is the\n * part the kit cannot know.\n */\nexport function useTableUrlState<T>({\n columns,\n defaultPageSize = 25,\n urlSync: urlSyncOption = true,\n urlPrefix: urlPrefixOption,\n search: manageSearch = false,\n}: UseTableUrlStateOptions<T>): UseTableUrlStateReturn {\n const resolved = resolveTableUrlSync(urlSyncOption);\n const urlSync = resolved.enabled;\n const urlPrefix = urlPrefixOption ?? resolved.prefix;\n const keys = useMemo(() => urlKeys(urlPrefix), [urlPrefix]);\n const [searchParams, setSearchParams] = useSearchParams();\n const location = useLocation();\n const [state, setState] = useState<OwnedState>(() => {\n const url = urlSync ? readTableUrlState(searchParams, columns, urlPrefix) : {};\n return {\n sorts: url.sorts ?? [],\n filters: url.filters ?? {},\n pageSize: url.pageSize ?? defaultPageSize,\n page: url.page ?? 0,\n search: urlSync && manageSearch ? (searchParams.get(keys.search) ?? \"\") : \"\",\n };\n });\n\n const lastUrl = useRef<string | null>(null);\n const urlSig = urlSync\n ? urlSignature(columns, state.sorts, state.filters, state.pageSize, state.page, defaultPageSize, keys) +\n (manageSearch ? `&${keys.search}=${state.search.trim() ? state.search : \"\"}` : \"\")\n : \"\";\n useEffect(() => {\n if (!urlSync) return;\n // First run included: a link that arrives with `p=1` or a default `ps` is\n // normalised to the table's own spelling, as `urlSync` does.\n if (lastUrl.current === urlSig) return;\n lastUrl.current = urlSig;\n writeUrlState(\n setSearchParams,\n columns,\n state.sorts,\n state.filters,\n state.pageSize,\n state.page,\n defaultPageSize,\n manageSearch ? state.search : undefined,\n location.state,\n keys,\n );\n // Keyed on the signature, which is computed from everything the write reads — see\n // the same effect in useTableState.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [urlSync, urlSig]);\n\n const setPage = (page: number) => setState((s) => ({ ...s, page }));\n const setPageSize = (pageSize: number) => setState((s) => ({ ...s, pageSize, page: 0 }));\n const setFilters = (filters: FilterState) => setState((s) => ({ ...s, filters, page: 0 }));\n const setSorts = (sorts: SortState[]) => setState((s) => ({ ...s, sorts, page: 0 }));\n const setSearch = (search: string) => setState((s) => ({ ...s, search, page: 0 }));\n\n return {\n page: state.page,\n setPage,\n pageSize: state.pageSize,\n setPageSize,\n filters: state.filters,\n setFilters,\n sorts: state.sorts,\n setSorts,\n search: state.search,\n setSearch,\n tableProps: (total, options) => ({\n serverPagination: {\n page: state.page,\n pageSize: state.pageSize,\n total,\n onPageChange: setPage,\n onPageSizeChange: setPageSize,\n isLoading: options?.isLoading,\n },\n filters: state.filters,\n onFiltersChange: setFilters,\n sorts: state.sorts,\n onSortsChange: setSorts,\n }),\n };\n}\n"],"mappings":";AAAA,SAAS,WAAW,SAAS,QAAQ,gBAAgB;AACrD,SAAS,aAAa,uBAAuB;AAC7C,SAAS,YAAY,mBAAmB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,aAAa,sBAAsC;AAkBlE,MAAM,yBAAyB;AAEtC,SAAS,cAAc,YAAgC,QAAyC;AAC9F,MAAI,CAAC,WAAY,QAAO,CAAC;AACzB,QAAM,MAAM,WAAW,SAAS,UAAU;AAC1C,MAAI,CAAC,IAAK,QAAO,CAAC;AAClB,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,WAAO,UAAU,OAAO,WAAW,WAAW,SAAS,CAAC;AAAA,EAC1D,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAIA,SAAS,mBAAmB,OAA+B;AACzD,SAAO,KAAK,UAAU,KAAK;AAC7B;AAIA,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAA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;AAAA,MAC/B,kBAAkB;AAAA,QAChB,MAAM,MAAM;AAAA,QACZ,UAAU,MAAM;AAAA,QAChB;AAAA,QACA,cAAc;AAAA,QACd,kBAAkB;AAAA,QAClB,WAAW,SAAS;AAAA,MACtB;AAAA,MACA,SAAS,MAAM;AAAA,MACf,iBAAiB;AAAA,MACjB,OAAO,MAAM;AAAA,MACb,eAAe;AAAA,IACjB;AAAA,EACF;AACF;","names":["state"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/use-table-state.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useLocation, useSearchParams } from \"react-router\";\nimport { useKitTableStorageKeyPrefix } from \"../i18n/kit-labels\";\nimport { readStored, writeStored } from \"../lib/safe-storage\";\nimport {\n decodeFilterValue,\n encodeFilterValue,\n isFilterActive,\n resolveFilter,\n} from \"./data-table-filters\";\nimport { decodeSorts, encodeSorts, normalizeSorts, type SortState } from \"./data-table-sort\";\nimport type { DataTableColumn, FilterState, ServerPagination } from \"./data-table\";\n\n// ---------- Persisted + URL-encoded view state ----------\n//\n// Moved here with `useTableState` when `DataTable` was split: these are what the hook\n// reads and writes, and nothing else in the table ever called them.\n\ninterface PersistedState {\n // Multi-sort array; blobs from before the upgrade hold a single {key, dir}\n // object (or null) — read back through normalizeSorts.\n sort: SortState[] | { key: string; dir: string } | null;\n filters: FilterState;\n pageSize: number | \"all\";\n widths?: Record<string, number>;\n hidden?: string[];\n}\n\nexport const DEFAULT_PERSIST_PREFIX = \"hbui-table:\";\n\nfunction loadPersisted(storageKey: string | undefined, prefix: string): Partial<PersistedState> {\n if (!storageKey) return {};\n const raw = readStored(prefix + storageKey);\n if (!raw) return {};\n try {\n const parsed = JSON.parse(raw) as Partial<PersistedState>;\n return parsed && typeof parsed === \"object\" ? parsed : {};\n } catch {\n return {}; // corrupt JSON — the storage access itself is guarded by readStored\n }\n}\n\n/** The blob that would be stored — also the value the effect below compares by, so\n * the comparison and the write can never disagree about what \"unchanged\" means. */\nfunction serializePersisted(state: PersistedState): string {\n return JSON.stringify(state);\n}\n\n/** A stored page size as a table holds it — `\"all\"` is `Infinity` — or `fallback`. */\nfunction storedPageSize(stored: Partial<PersistedState>, fallback: number): number {\n if (stored.pageSize === \"all\") return Infinity;\n if (typeof stored.pageSize === \"number\" && stored.pageSize > 0) return stored.pageSize;\n return fallback;\n}\n\n// ---------- URL sync helpers ----------\n\nconst URL_FILTER_PREFIX = \"f.\";\nconst URL_SORT_KEY = \"sort\";\nconst URL_PAGE_KEY = \"p\";\nconst URL_PAGE_SIZE_KEY = \"ps\";\n/** The free-text search term — managed only by {@link useTableUrlState}, and only when\n * it is asked to (`search: true`); a plain `urlSync` table leaves a `q` alone. */\nconst URL_SEARCH_KEY = \"q\";\n\n/**\n * How a table is mirrored into the URL: `true`, or `{ prefix }` for a table that shares\n * its page with another URL-synced one. The prefix is put verbatim in front of EVERY key\n * the table writes and reads — `{ prefix: \"inv.\" }` gives `inv.f.<column>`, `inv.sort`,\n * `inv.p`, `inv.ps` (and `inv.q`) — so two tables on one page stop sharing a sort and a\n * page. Without one the keys are unprefixed, as they always were.\n */\nexport type TableUrlSync = boolean | { prefix?: string };\n\n/** The query keys of one table, with its prefix applied. */\ninterface UrlKeys {\n filter: string;\n sort: string;\n page: string;\n pageSize: string;\n search: string;\n}\n\nfunction urlKeys(prefix = \"\"): UrlKeys {\n return {\n filter: prefix + URL_FILTER_PREFIX,\n sort: prefix + URL_SORT_KEY,\n page: prefix + URL_PAGE_KEY,\n pageSize: prefix + URL_PAGE_SIZE_KEY,\n search: prefix + URL_SEARCH_KEY,\n };\n}\n\n/** `urlSync` split into \"is it on\" and \"under which prefix\". */\nfunction resolveTableUrlSync(urlSync: TableUrlSync | undefined): { enabled: boolean; prefix: string } {\n if (!urlSync) return { enabled: false, prefix: \"\" };\n return { enabled: true, prefix: urlSync === true ? \"\" : (urlSync.prefix ?? \"\") };\n}\n\n/** What {@link readTableUrlState} found in a query string. */\nexport interface TableUrlState {\n sorts?: SortState[];\n filters?: FilterState;\n /** `Infinity` for `ps=all`. */\n pageSize?: number;\n /** 0-based (the URL's `p` is 1-based). */\n page?: number;\n}\n\n/**\n * What a table's URL says, read out of a query string: the column filters (`f.<key>`),\n * the sort, the page size and the 0-based page. Absent keys are absent here too, so a\n * caller can tell \"not in the link\" from \"the default\". The same reader `urlSync` uses\n * on mount, exported for an owner that keeps the state itself — see\n * {@link useTableUrlState}.\n *\n * Pass the ROUTER's query string — the one `setSearchParams` writes — and the table's\n * `prefix` when it has one (see {@link TableUrlSync}).\n *\n * This read `window.location.search` until 0.7.0, which is the same string only under a\n * BrowserRouter. Under a HashRouter the router's query lives after the `#`\n * (`/#/tx?f.payee=Rewe`) and `window.location.search` is empty: a shared link opened\n * unfiltered, and the table's first write then replaced the link's filter with its own\n * empty state. Reading and writing through `useSearchParams` is one source for both\n * directions under every router, MemoryRouter included.\n */\nexport function readTableUrlState<T>(\n sp: URLSearchParams,\n columns: DataTableColumn<T>[],\n prefix?: string,\n): TableUrlState {\n const keys = urlKeys(prefix);\n const out: TableUrlState = {};\n\n const filters: FilterState = {};\n for (const col of columns) {\n const filter = resolveFilter(col);\n if (!filter) continue;\n const raw = sp.get(keys.filter + col.key);\n if (raw == null) continue;\n filters[col.key] = decodeFilterValue(filter, raw);\n }\n if (Object.keys(filters).length) out.filters = filters;\n\n const sortRaw = sp.get(keys.sort);\n if (sortRaw) {\n const decoded = decodeSorts(sortRaw, new Set(columns.map((c) => c.key)));\n if (decoded.length) out.sorts = decoded;\n }\n\n const psRaw = sp.get(keys.pageSize);\n if (psRaw === \"all\") out.pageSize = Infinity;\n else if (psRaw && Number(psRaw) > 0) out.pageSize = Number(psRaw);\n\n const pRaw = sp.get(keys.page);\n if (pRaw && Number(pRaw) >= 1) out.page = Number(pRaw) - 1;\n\n return out;\n}\n\n/**\n * The managed part of the query string, as a string, for comparing by VALUE.\n *\n * Everything the table puts in the address and nothing else, in a fixed order.\n * `columns` is walked for its keys only, which is why it can be left out of the\n * effect's dependencies without lying: a new column ARRAY carrying the same keys\n * produces the same signature, and a genuinely different set of filterable columns\n * produces a different one.\n */\nfunction urlSignature<T>(\n columns: DataTableColumn<T>[],\n sorts: SortState[],\n filters: FilterState,\n pageSize: number,\n page: number,\n defaultPageSize: number,\n keys: UrlKeys,\n): string {\n const parts: string[] = [];\n for (const col of columns) {\n const state = filters[col.key];\n if (!state || !isFilterActive(state)) continue;\n const enc = encodeFilterValue(state);\n if (enc != null) parts.push(`${keys.filter}${col.key}=${enc}`);\n }\n parts.push(`${keys.sort}=${encodeSorts(sorts)}`);\n parts.push(\n `${keys.pageSize}=${\n pageSize === Infinity ? \"all\" : pageSize === defaultPageSize ? \"\" : String(pageSize)\n }`,\n );\n parts.push(`${keys.page}=${page > 0 ? String(page + 1) : \"\"}`);\n return parts.join(\"&\");\n}\n\nfunction writeUrlState<T>(\n setSearchParams: ReturnType<typeof useSearchParams>[1],\n columns: DataTableColumn<T>[],\n sorts: SortState[],\n filters: FilterState,\n pageSize: number,\n page: number,\n defaultPageSize: number,\n // `undefined`: the search term is not ours to manage, and a `q` is left as it is.\n search: string | undefined,\n // The current entry's route state, carried over the replace. A query rewrite is not\n // a navigation, and dropping the state would, for one, lose the mark a URL-bound\n // dialog's opener leaves there (see useDialogParam).\n state: unknown,\n keys: UrlKeys,\n): void {\n setSearchParams(\n (prev) => {\n const next = new URLSearchParams(prev);\n // clear managed keys\n for (const col of columns) next.delete(keys.filter + col.key);\n next.delete(keys.sort);\n next.delete(keys.page);\n next.delete(keys.pageSize);\n if (search !== undefined) {\n next.delete(keys.search);\n if (search.trim()) next.set(keys.search, search);\n }\n // write filters\n for (const col of columns) {\n const state = filters[col.key];\n if (!state || !isFilterActive(state)) continue;\n const enc = encodeFilterValue(state);\n if (enc != null) next.set(keys.filter + col.key, enc);\n }\n // write sort\n const sortEnc = encodeSorts(sorts);\n if (sortEnc) next.set(keys.sort, sortEnc);\n // write page size if non-default\n if (pageSize === Infinity) next.set(keys.pageSize, \"all\");\n else if (pageSize !== defaultPageSize) next.set(keys.pageSize, String(pageSize));\n // write page if not first\n if (page > 0) next.set(keys.page, String(page + 1));\n return next;\n },\n { replace: true, state },\n );\n}\n\n/**\n * Where a table's view lives: what it is sorted and filtered by, which page, how wide\n * the columns are and which are hidden — plus the two places that outlives a render.\n *\n * Lifted out of `DataTable`, which was 984 lines and twenty hooks in one function. This\n * is the part that is genuinely about STATE rather than about drawing, and the three\n * rules it encodes are easy to lose among the markup:\n *\n * * **The URL is read once, on mount.** A shared or deep link populates the initial view;\n * after that the state is local, or the browser's own history would fight the user's\n * next click.\n * * **Sorting and filtering are optionally CONTROLLED.** A server-driven table passes\n * state and a callback and owns them; everything else is self-owned. That is the\n * `sortsProp ?? internalSorts` pair, and it is why the setters are exposed separately.\n * * **Persistence writes on every change, the URL only when asked.** `storageKey` is the\n * per-table identity; `urlSync` is opt-in because only some tables want their view in\n * a shareable address.\n * * **A controlled filter, sort or page size that changes sends the table back to page\n * 1.** See the note at the reset below.\n */\nexport function useTableState<T>({\n columns,\n storageKey,\n storageKeyPrefix,\n urlSync: urlSyncOption,\n defaultPageSize,\n sortsProp,\n filtersProp,\n pageSizeProp,\n}: {\n columns: DataTableColumn<T>[];\n storageKey?: string;\n storageKeyPrefix: string;\n urlSync?: TableUrlSync;\n defaultPageSize: number;\n sortsProp?: SortState[];\n filtersProp?: FilterState;\n pageSizeProp?: number;\n}) {\n const { enabled: urlSync, prefix: urlPrefix } = resolveTableUrlSync(urlSyncOption);\n const keys = useMemo(() => urlKeys(urlPrefix), [urlPrefix]);\n // Called unconditionally (a Router is required either way — see src/data-table.ts),\n // and the SAME pair is used to read and to write; see `readTableUrlState`.\n const [searchParams, setSearchParams] = useSearchParams();\n const location = useLocation();\n // Read URL once on mount so URL-encoded views (e.g. shared links, deep links from\n // other pages) populate initial state. After mount, state is local.\n const [urlInitial] = useState<TableUrlState>(() =>\n urlSync ? readTableUrlState(searchParams, columns, urlPrefix) : {},\n );\n const initial = useMemo(\n () => loadPersisted(storageKey, storageKeyPrefix),\n [storageKey, storageKeyPrefix],\n );\n const [internalSorts, setInternalSorts] = useState<SortState[]>(() =>\n urlInitial.sorts !== undefined ? urlInitial.sorts : normalizeSorts(initial.sort),\n );\n const [internalFilters, setInternalFilters] = useState<FilterState>(\n () => urlInitial.filters ?? initial.filters ?? {},\n );\n // Controlled when the owner passes state + callback (server-driven tables);\n // self-owned otherwise.\n const sorts = sortsProp ?? internalSorts;\n const filters = filtersProp ?? internalFilters;\n const [page, setPage] = useState(() => urlInitial.page ?? 0);\n\n // ---- Controlled filters/sorts reset the page ----\n //\n // A self-owned table resets to page 1 in the filter handlers. A CONTROLLED one could\n // not: the handlers hand the change to the owner and return, and `page` lives here,\n // where the owner has no way to reach it — so narrowing a filter from outside (a\n // saved view, a chip dismissed above the table) left a client-side table on page 4\n // of what was now two pages, clamped to the last one instead of the first.\n //\n // So the table does it: whenever the controlled VALUE changes, back to the first\n // page. Compared by value, because a controlled prop is a fresh object on every\n // parent render. Adjusted during render rather than in an effect, so the stale page\n // is never painted and never written to the URL. Not on mount: a deep link's `p=3`\n // must survive the owner's first render. (In `serverPagination` mode this state is\n // unused — the owner's `page` is the page, and resetting it stays the owner's job.)\n // A controlled page size counts too: the groups of `TranslationReviewPanel` share one,\n // and a group paged deep into its rows starts over when another group's pager changes it.\n const controlledSig =\n sortsProp !== undefined || filtersProp !== undefined || pageSizeProp !== undefined\n ? JSON.stringify([sortsProp ?? null, filtersProp ?? null, String(pageSizeProp)])\n : null;\n const [seenControlledSig, setSeenControlledSig] = useState(controlledSig);\n if (seenControlledSig !== controlledSig) {\n setSeenControlledSig(controlledSig);\n setPage(0);\n }\n const [internalPageSize, setPageSize] = useState<number>(() =>\n urlInitial.pageSize !== undefined ? urlInitial.pageSize : storedPageSize(initial, defaultPageSize),\n );\n const pageSize = pageSizeProp ?? internalPageSize;\n const [widths, setWidths] = useState<Record<string, number>>(() => initial.widths ?? {});\n const [hiddenCols, setHiddenCols] = useState<Set<string>>(() => new Set(initial.hidden ?? []));\n const [showSettings, setShowSettings] = useState(false);\n const headRefs = useMemo(() => new Map<string, HTMLTableCellElement>(), []);\n\n // ---- Writing out: both of these compare by VALUE ----\n //\n // A CONTROLLED table (`sorts`/`filters` props plus callbacks — every server-driven\n // one) receives a freshly-built object on every render of the page around it, and\n // `{}` is never `===` the `{}` before it. Keyed on identity, both effects below\n // therefore fired on every unrelated parent render: persistence wrote the same JSON\n // into `localStorage` each time — a synchronous main-thread write, on a page whose\n // other half may be a form being typed into — and the URL one handed react-router a\n // `replace` it answers with a render, which is the loop the audit records. A `ref`\n // holding what was last written is what makes \"changed\" mean changed.\n const lastPersisted = useRef<string | null>(null);\n const persisted = !storageKey\n ? \"\"\n : serializePersisted({\n sort: sorts,\n filters,\n pageSize: pageSize === Infinity ? \"all\" : pageSize,\n widths,\n hidden: Array.from(hiddenCols),\n });\n useEffect(() => {\n if (!storageKey) return;\n // The destination is part of the signature: two tables can hold identical state,\n // and a table that swaps `storageKey` has to write under the new one even though\n // nothing about the view changed.\n const target = storageKeyPrefix + storageKey;\n const sig = `${target}\\u0000${persisted}`;\n if (lastPersisted.current === sig) return;\n lastPersisted.current = sig;\n writeStored(target, persisted);\n }, [storageKey, storageKeyPrefix, persisted]);\n\n const lastUrl = useRef<string | null>(null);\n const urlSig = urlSync\n ? urlSignature(columns, sorts, filters, pageSize, page, defaultPageSize, keys)\n : \"\";\n useEffect(() => {\n if (!urlSync) return;\n if (lastUrl.current === urlSig) return;\n lastUrl.current = urlSig;\n // `columns` is deliberately not a dependency and does not need to be: the\n // signature above is computed from it, so a column set that would produce a\n // different address produces a different signature first.\n writeUrlState(setSearchParams, columns, sorts, filters, pageSize, page, defaultPageSize, undefined, location.state, keys);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [urlSync, urlSig]);\n\n return {\n sorts,\n filters,\n setInternalSorts,\n setInternalFilters,\n page,\n setPage,\n pageSize,\n setPageSize,\n widths,\n setWidths,\n hiddenCols,\n setHiddenCols,\n showSettings,\n setShowSettings,\n headRefs,\n };\n}\n\n// ---------- One view over several tables ----------\n\n/** What {@link useSharedTableView} keeps. */\nexport interface SharedTableView {\n sorts: SortState[];\n setSorts: (next: SortState[]) => void;\n /** `Infinity` for \"all\", as a table holds it. */\n pageSize: number;\n setPageSize: (next: number) => void;\n}\n\n/**\n * One table view — the sort and the page size — for an owner that draws it as SEVERAL\n * tables over one `storageKey`: `TranslationReviewPanel`'s groups, which sort and page\n * alike (0.35, Kurvenschmiede: its grouped review stored no view at all). Pass them to\n * each table as `sorts`/`onSortsChange` and `pageSize`/`onPageSizeChange`.\n *\n * Kept in the very blob a `DataTable` with that `storageKey` keeps, not in a format of\n * its own, so the single table and the groups read each other's view. What the blob\n * holds besides (filters, column widths, hidden columns) is carried over as stored, for\n * the single table to find as it left it. Read when `active` turns on — on mount, or\n * when the owner switches to this view — and written on a change, never on a read. The\n * prefix resolves as DataTable's does: prop > provider > the kit's.\n */\nexport function useSharedTableView({\n active,\n storageKey,\n storageKeyPrefix,\n defaultPageSize,\n}: {\n active: boolean;\n storageKey?: string;\n storageKeyPrefix?: string;\n defaultPageSize: number;\n}): SharedTableView {\n const providerPrefix = useKitTableStorageKeyPrefix();\n const prefix = storageKeyPrefix ?? providerPrefix ?? DEFAULT_PERSIST_PREFIX;\n const read = () => {\n const stored = active ? loadPersisted(storageKey, prefix) : {};\n return { sorts: normalizeSorts(stored.sort), pageSize: storedPageSize(stored, defaultPageSize) };\n };\n const [view, setView] = useState(read);\n // Adjusted during render when `active` turns on, so the first render of the groups\n // already has the view the single table left, not a frame of the default.\n const [wasActive, setWasActive] = useState(active);\n if (active !== wasActive) {\n setWasActive(active);\n if (active) setView(read());\n }\n const change = (patch: Partial<typeof view>) => {\n const next = { ...view, ...patch };\n setView(next);\n if (!active || !storageKey) return;\n const stored = loadPersisted(storageKey, prefix);\n const blob: PersistedState = {\n sort: next.sorts,\n filters: stored.filters ?? {},\n pageSize: next.pageSize === Infinity ? \"all\" : next.pageSize,\n widths: stored.widths,\n hidden: stored.hidden,\n };\n writeStored(prefix + storageKey, serializePersisted(blob));\n };\n return {\n sorts: view.sorts,\n setSorts: (sorts) => change({ sorts }),\n pageSize: view.pageSize,\n setPageSize: (pageSize) => change({ pageSize }),\n };\n}\n\n// ---------- Owner-held table state, mirrored to the URL ----------\n\nexport interface UseTableUrlStateOptions<T> {\n /** The table's columns — read for their keys and filter types only. */\n columns: DataTableColumn<T>[];\n /** Default 25. A page size equal to it is left out of the URL. */\n defaultPageSize?: number;\n /** Mirror the state into the URL and seed it from there on mount. Default true.\n * `{ prefix }` puts a prefix in front of every key, for a page with two URL-synced\n * tables — see {@link TableUrlSync}. */\n urlSync?: TableUrlSync;\n /** Shorthand for `urlSync: { prefix }`; wins over a prefix given there. */\n urlPrefix?: string;\n /** Also hold a free-text search term, under `q`. Off by default, so a `q` that\n * belongs to someone else on the page is never touched. */\n search?: boolean;\n}\n\n/** The part of {@link DataTableProps} a server-driven table takes from its owner. */\nexport interface TableUrlStateProps {\n serverPagination: ServerPagination;\n filters: FilterState;\n onFiltersChange: (next: FilterState) => void;\n sorts: SortState[];\n onSortsChange: (next: SortState[]) => void;\n}\n\nexport interface UseTableUrlStateReturn {\n /** 0-based. */\n page: number;\n setPage: (page: number) => void;\n pageSize: number;\n /** Also back to the first page. */\n setPageSize: (pageSize: number) => void;\n filters: FilterState;\n /** Also back to the first page. */\n setFilters: (next: FilterState) => void;\n sorts: SortState[];\n /** Also back to the first page. */\n setSorts: (next: SortState[]) => void;\n /** The search term (`\"\"` unless `search: true`). */\n search: string;\n /** Also back to the first page. */\n setSearch: (next: string) => void;\n /**\n * Everything the table needs, to spread onto it:\n * `<DataTable {...table.tableProps(data?.total ?? 0, { isLoading })} rows={…} … />`.\n */\n tableProps: (total: number, options?: { isLoading?: boolean }) => TableUrlStateProps;\n}\n\ninterface OwnedState {\n sorts: SortState[];\n filters: FilterState;\n pageSize: number;\n page: number;\n search: string;\n}\n\n/**\n * The controlled state of a `serverPagination` table — filters, sorts, page, page size\n * and optionally a search term — kept by the OWNER and mirrored into the URL in the\n * table's own scheme (`f.<key>`, `sort`, `p`, `ps`, and `q`).\n *\n * A server-driven table owns none of this: the owner has to hold it to turn it into\n * the query that fetches `rows`, and until now it also had to restate the table's URL\n * codec to keep the view bookmarkable (kastlan's use-server-table.ts copied\n * `readUrlState` / `writeUrlState` to do it). Same rules as `urlSync`:\n *\n * * **The URL is read once, on mount** — a shared or deep link (see {@link filterHref})\n * seeds the view; after that the state is local and written out with `replace`.\n * * **Any change but the page itself goes back to page 1** — a narrower filter must not\n * leave the user on page 7 of 2.\n * * **Written by value**: an unchanged view writes nothing, however often the owner\n * renders.\n *\n * Mapping the state onto the backend's query parameters stays the owner's: that is the\n * part the kit cannot know.\n */\nexport function useTableUrlState<T>({\n columns,\n defaultPageSize = 25,\n urlSync: urlSyncOption = true,\n urlPrefix: urlPrefixOption,\n search: manageSearch = false,\n}: UseTableUrlStateOptions<T>): UseTableUrlStateReturn {\n const resolved = resolveTableUrlSync(urlSyncOption);\n const urlSync = resolved.enabled;\n const urlPrefix = urlPrefixOption ?? resolved.prefix;\n const keys = useMemo(() => urlKeys(urlPrefix), [urlPrefix]);\n const [searchParams, setSearchParams] = useSearchParams();\n const location = useLocation();\n const [state, setState] = useState<OwnedState>(() => {\n const url = urlSync ? readTableUrlState(searchParams, columns, urlPrefix) : {};\n return {\n sorts: url.sorts ?? [],\n filters: url.filters ?? {},\n pageSize: url.pageSize ?? defaultPageSize,\n page: url.page ?? 0,\n search: urlSync && manageSearch ? (searchParams.get(keys.search) ?? \"\") : \"\",\n };\n });\n\n const lastUrl = useRef<string | null>(null);\n const urlSig = urlSync\n ? urlSignature(columns, state.sorts, state.filters, state.pageSize, state.page, defaultPageSize, keys) +\n (manageSearch ? `&${keys.search}=${state.search.trim() ? state.search : \"\"}` : \"\")\n : \"\";\n useEffect(() => {\n if (!urlSync) return;\n // First run included: a link that arrives with `p=1` or a default `ps` is\n // normalised to the table's own spelling, as `urlSync` does.\n if (lastUrl.current === urlSig) return;\n lastUrl.current = urlSig;\n writeUrlState(\n setSearchParams,\n columns,\n state.sorts,\n state.filters,\n state.pageSize,\n state.page,\n defaultPageSize,\n manageSearch ? state.search : undefined,\n location.state,\n keys,\n );\n // Keyed on the signature, which is computed from everything the write reads — see\n // the same effect in useTableState.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [urlSync, urlSig]);\n\n const setPage = (page: number) => setState((s) => ({ ...s, page }));\n const setPageSize = (pageSize: number) => setState((s) => ({ ...s, pageSize, page: 0 }));\n const setFilters = (filters: FilterState) => setState((s) => ({ ...s, filters, page: 0 }));\n const setSorts = (sorts: SortState[]) => setState((s) => ({ ...s, sorts, page: 0 }));\n const setSearch = (search: string) => setState((s) => ({ ...s, search, page: 0 }));\n\n return {\n page: state.page,\n setPage,\n pageSize: state.pageSize,\n setPageSize,\n filters: state.filters,\n setFilters,\n sorts: state.sorts,\n setSorts,\n search: state.search,\n setSearch,\n tableProps: (total, options) => ({\n serverPagination: {\n page: state.page,\n pageSize: state.pageSize,\n total,\n onPageChange: setPage,\n onPageSizeChange: setPageSize,\n isLoading: options?.isLoading,\n },\n filters: state.filters,\n onFiltersChange: setFilters,\n sorts: state.sorts,\n onSortsChange: setSorts,\n }),\n };\n}\n"],"mappings":";AAAA,SAAS,WAAW,SAAS,QAAQ,gBAAgB;AACrD,SAAS,aAAa,uBAAuB;AAC7C,SAAS,mCAAmC;AAC5C,SAAS,YAAY,mBAAmB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,aAAa,sBAAsC;AAkBlE,MAAM,yBAAyB;AAEtC,SAAS,cAAc,YAAgC,QAAyC;AAC9F,MAAI,CAAC,WAAY,QAAO,CAAC;AACzB,QAAM,MAAM,WAAW,SAAS,UAAU;AAC1C,MAAI,CAAC,IAAK,QAAO,CAAC;AAClB,MAAI;AACF,UAAM,SAAS,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AQ,MAAM,EAAE,EAAE;AAEjF,SAAO;AAAA,IACL,MAAM,MAAM;AAAA,IACZ;AAAA,IACA,UAAU,MAAM;AAAA,IAChB;AAAA,IACA,SAAS,MAAM;AAAA,IACf;AAAA,IACA,OAAO,MAAM;AAAA,IACb;AAAA,IACA,QAAQ,MAAM;AAAA,IACd;AAAA,IACA,YAAY,CAAC,OAAO,aAAa;AAAA,MAC/B,kBAAkB;AAAA,QAChB,MAAM,MAAM;AAAA,QACZ,UAAU,MAAM;AAAA,QAChB;AAAA,QACA,cAAc;AAAA,QACd,kBAAkB;AAAA,QAClB,WAAW,SAAS;AAAA,MACtB;AAAA,MACA,SAAS,MAAM;AAAA,MACf,iBAAiB;AAAA,MACjB,OAAO,MAAM;AAAA,MACb,eAAe;AAAA,IACjB;AAAA,EACF;AACF;","names":["state"]}
|
|
@@ -50,9 +50,9 @@ export interface UserAvatarProps extends Omit<ComponentPropsWithRef<"span">, "ch
|
|
|
50
50
|
* in the surface colour so it reads as its own mark (keksdose account-menu ~385,
|
|
51
51
|
* top-bar :152). Its `label` is read as text where the dot sits — inside a button
|
|
52
52
|
* named by its content it joins that name. In `TopBarActionMenu`'s `trigger` the
|
|
53
|
-
* button is named by the menu's `
|
|
53
|
+
* button is named by the menu's `aria-label` followed by this label: "Account menu
|
|
54
54
|
* 3 unread". The initials stay hidden either way, so the person's name is NOT part
|
|
55
|
-
* of it — put it in `
|
|
55
|
+
* of it — put it in `aria-label` ("Marcel Eifert, account menu") if it should be.
|
|
56
56
|
*/
|
|
57
57
|
badge?: UserAvatarBadge | null;
|
|
58
58
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/user-avatar.tsx"],"sourcesContent":["import type { ComponentPropsWithRef, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { personInitials } from \"../lib/person-name\";\nimport type { PersonName } from \"../lib/person-name\";\nimport { useKitLocale } from \"../i18n/kit-labels\";\nimport { StatusDot } from \"./status-dot\";\nimport type { StatusDotSize, StatusDotTone } from \"./status-dot\";\n\n/** Initials from a display name (first + last) or, failing that, an email —\n * e.g. \"Marcel Eifert\" → \"ME\", \"marcel@x.com\" → \"MA\". App-agnostic.\n *\n * \"Failing that\" means BLANK, not merely absent. This was `name ?? email ?? \"?\"`,\n * and `??` falls through on null/undefined alone — so an empty or whitespace-only\n * display name short-circuited the email it had in hand and landed on the guard\n * below, returning \"?\" for a user whose address says \"MA\" perfectly well. Keksdose\n * cannot reach it (its `display_name` has `min_length=1`), but this is exported as\n * app-agnostic, and any consumer whose profile name is optional free text got a wall\n * of \"?\" chips. The guard is what shows the empty case was foreseen; it just\n * answered it at the wrong end. */\nexport function avatarInitials(name?: string | null, email?: string | null): string {\n const source = [name, email].map((s) => s?.trim()).find(Boolean) ?? \"?\";\n const parts = source.split(/\\s+/).filter(Boolean);\n if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();\n return source.slice(0, 2).toUpperCase();\n}\n\nconst AVATAR_SIZES = {\n sm: \"size-7 text-caption\",\n md: \"size-8 text-xs\",\n lg: \"size-12 text-base\",\n} as const;\n\nconst CHIP =\n \"inline-flex shrink-0 items-center justify-center rounded-full bg-inverse font-semibold text-inverse\";\n\n/** The dot grows with the avatar: 8px on `sm`, 10px on `md` (keksdose's), 12px on `lg`. */\nconst BADGE_SIZES: Record<keyof typeof AVATAR_SIZES, StatusDotSize> = { sm: \"sm\", md: \"md\", lg: \"lg\" };\n\n/** A status dot in the avatar's top corner — an unread count, presence. */\nexport interface UserAvatarBadge {\n /** What the dot MEANS, for a screen reader (\"3 unread\"). Required: a coloured circle\n * says nothing to someone who cannot see it. */\n label: ReactNode;\n /** Default `danger`, the unread dot both apps draw by hand. */\n tone?: StatusDotTone;\n}\n\n/** A `<span>`'s props, minus `children`: the content is the initials this computes\n * from `person`/`name`/`email`, so there is nothing for a caller to put inside. */\nexport interface UserAvatarProps extends Omit<ComponentPropsWithRef<\"span\">, \"children\"> {\n name?: string | null;\n email?: string | null;\n /**\n * The person's first and last name (0.29.0, docs/auth-harmonization.md §3.2) —\n * preferred over `name` whenever either part is filled in. The initials follow the\n * READER's language, the provider's `locale`: \"AE\" for Ada Example, \"EA\" in Hungarian\n * (family name first), the family name's first character alone in Chinese. See\n * {@link personInitials}.\n *\n * `name` stays the fallback for an API that still sends only `display_name`, and\n * `email` after it: a person whose two parts are both blank falls through to them.\n * A migrated user (the whole old display name in `first`, no `last`, §3.3) keeps the\n * initials they had.\n */\n person?: PersonName | null;\n size?: keyof typeof AVATAR_SIZES;\n /**\n * A status dot in the top-end corner (the top-right in LTR, top-left in RTL), ringed\n * in the surface colour so it reads as its own mark (keksdose account-menu ~385,\n * top-bar :152). Its `label` is read as text where the dot sits — inside a button\n * named by its content it joins that name. In `TopBarActionMenu`'s `trigger` the\n * button is named by the menu's `
|
|
1
|
+
{"version":3,"sources":["../../src/components/user-avatar.tsx"],"sourcesContent":["import type { ComponentPropsWithRef, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { personInitials } from \"../lib/person-name\";\nimport type { PersonName } from \"../lib/person-name\";\nimport { useKitLocale } from \"../i18n/kit-labels\";\nimport { StatusDot } from \"./status-dot\";\nimport type { StatusDotSize, StatusDotTone } from \"./status-dot\";\n\n/** Initials from a display name (first + last) or, failing that, an email —\n * e.g. \"Marcel Eifert\" → \"ME\", \"marcel@x.com\" → \"MA\". App-agnostic.\n *\n * \"Failing that\" means BLANK, not merely absent. This was `name ?? email ?? \"?\"`,\n * and `??` falls through on null/undefined alone — so an empty or whitespace-only\n * display name short-circuited the email it had in hand and landed on the guard\n * below, returning \"?\" for a user whose address says \"MA\" perfectly well. Keksdose\n * cannot reach it (its `display_name` has `min_length=1`), but this is exported as\n * app-agnostic, and any consumer whose profile name is optional free text got a wall\n * of \"?\" chips. The guard is what shows the empty case was foreseen; it just\n * answered it at the wrong end. */\nexport function avatarInitials(name?: string | null, email?: string | null): string {\n const source = [name, email].map((s) => s?.trim()).find(Boolean) ?? \"?\";\n const parts = source.split(/\\s+/).filter(Boolean);\n if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();\n return source.slice(0, 2).toUpperCase();\n}\n\nconst AVATAR_SIZES = {\n sm: \"size-7 text-caption\",\n md: \"size-8 text-xs\",\n lg: \"size-12 text-base\",\n} as const;\n\nconst CHIP =\n \"inline-flex shrink-0 items-center justify-center rounded-full bg-inverse font-semibold text-inverse\";\n\n/** The dot grows with the avatar: 8px on `sm`, 10px on `md` (keksdose's), 12px on `lg`. */\nconst BADGE_SIZES: Record<keyof typeof AVATAR_SIZES, StatusDotSize> = { sm: \"sm\", md: \"md\", lg: \"lg\" };\n\n/** A status dot in the avatar's top corner — an unread count, presence. */\nexport interface UserAvatarBadge {\n /** What the dot MEANS, for a screen reader (\"3 unread\"). Required: a coloured circle\n * says nothing to someone who cannot see it. */\n label: ReactNode;\n /** Default `danger`, the unread dot both apps draw by hand. */\n tone?: StatusDotTone;\n}\n\n/** A `<span>`'s props, minus `children`: the content is the initials this computes\n * from `person`/`name`/`email`, so there is nothing for a caller to put inside. */\nexport interface UserAvatarProps extends Omit<ComponentPropsWithRef<\"span\">, \"children\"> {\n name?: string | null;\n email?: string | null;\n /**\n * The person's first and last name (0.29.0, docs/auth-harmonization.md §3.2) —\n * preferred over `name` whenever either part is filled in. The initials follow the\n * READER's language, the provider's `locale`: \"AE\" for Ada Example, \"EA\" in Hungarian\n * (family name first), the family name's first character alone in Chinese. See\n * {@link personInitials}.\n *\n * `name` stays the fallback for an API that still sends only `display_name`, and\n * `email` after it: a person whose two parts are both blank falls through to them.\n * A migrated user (the whole old display name in `first`, no `last`, §3.3) keeps the\n * initials they had.\n */\n person?: PersonName | null;\n size?: keyof typeof AVATAR_SIZES;\n /**\n * A status dot in the top-end corner (the top-right in LTR, top-left in RTL), ringed\n * in the surface colour so it reads as its own mark (keksdose account-menu ~385,\n * top-bar :152). Its `label` is read as text where the dot sits — inside a button\n * named by its content it joins that name. In `TopBarActionMenu`'s `trigger` the\n * button is named by the menu's `aria-label` followed by this label: \"Account menu\n * 3 unread\". The initials stay hidden either way, so the person's name is NOT part\n * of it — put it in `aria-label` (\"Marcel Eifert, account menu\") if it should be.\n */\n badge?: UserAvatarBadge | null;\n}\n\n/**\n * A round initials avatar — the common user chip shared across apps (feedback\n * #333). Purely presentational; wrap it in a button for the account menu trigger.\n */\nexport function UserAvatar({ name, email, person, size = \"md\", badge, className, ...rest }: UserAvatarProps) {\n const locale = useKitLocale();\n const initials = (person ? personInitials(person, locale) : \"\") || avatarInitials(name, email);\n if (badge) {\n // A wrapper, because the chip itself is `aria-hidden` and the badge label must not\n // be. `className` stays on the chip (a size override still sizes the circle); the\n // other attributes go on the wrapper, which is what a caller addresses. `relative`\n // also contains the sr-only text.\n return (\n <span {...rest} className=\"relative inline-flex shrink-0\">\n <span\n aria-hidden\n className={cn(\n CHIP,\n AVATAR_SIZES[size],\n className,\n )}\n >\n {initials}\n </span>\n <StatusDot\n ring\n tone={badge.tone ?? \"danger\"}\n size={BADGE_SIZES[size]}\n className=\"absolute -end-0.5 -top-0.5\"\n />\n <span className=\"sr-only\">{badge.label}</span>\n </span>\n );\n }\n return (\n <span\n // `aria-hidden` sits BEFORE the spread, unlike the structural attributes on the\n // other components here, because it is a DEFAULT rather than an invariant. The\n // avatar is decorative next to the name it belongs to — which is where all three\n // apps render it — so hiding it stops a screen reader saying \"ME\" after the word\n // \"Marcel Eifert\". A caller who renders one ALONE (an assignee column, a\n // presence dot) needs the opposite, and now has it: `aria-hidden={false}` plus an\n // `aria-label` arrives through `...rest` and wins.\n aria-hidden\n {...rest}\n className={cn(\n CHIP,\n AVATAR_SIZES[size],\n className,\n )}\n >\n {initials}\n </span>\n );\n}\n"],"mappings":";AA2FM,SACE,KADF;AA1FN,SAAS,UAAU;AACnB,SAAS,sBAAsB;AAE/B,SAAS,oBAAoB;AAC7B,SAAS,iBAAiB;AAcnB,SAAS,eAAe,MAAsB,OAA+B;AAClF,QAAM,SAAS,CA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ACH;AAEJ;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Compact step indicator for the import wizards. Past steps are plain, the
|
|
2
2
|
* current one is highlighted, future ones muted. */
|
|
3
|
-
export declare function WizardStepper({ steps, current, "aria-label":
|
|
3
|
+
export declare function WizardStepper({ steps, current, "aria-label": ariaLabel, }: {
|
|
4
4
|
steps: {
|
|
5
5
|
key: string;
|
|
6
6
|
label: string;
|
|
@@ -8,7 +8,4 @@ export declare function WizardStepper({ steps, current, "aria-label": ariaLabelA
|
|
|
8
8
|
current: string;
|
|
9
9
|
/** Names the list of steps ("Import steps"). */
|
|
10
10
|
"aria-label"?: string;
|
|
11
|
-
/** @deprecated 0.34 — use `aria-label`; removed in 0.35 (refactor audit 2026-10, API-1).
|
|
12
|
-
* Names the steps only when `aria-label` is absent. */
|
|
13
|
-
ariaLabel?: string;
|
|
14
11
|
}): import("react").JSX.Element;
|
|
@@ -4,8 +4,7 @@ import { cn } from "../lib/cn.js";
|
|
|
4
4
|
function WizardStepper({
|
|
5
5
|
steps,
|
|
6
6
|
current,
|
|
7
|
-
"aria-label":
|
|
8
|
-
ariaLabel
|
|
7
|
+
"aria-label": ariaLabel
|
|
9
8
|
}) {
|
|
10
9
|
const currentIndex = steps.findIndex((s) => s.key === current);
|
|
11
10
|
return (
|
|
@@ -13,7 +12,7 @@ function WizardStepper({
|
|
|
13
12
|
// (0.32.1, the 360 px Extra-large sweep; docs/text-size-harmonization.md §4).
|
|
14
13
|
// "Upload — Map columns — Confirm" ran 22 px past a 360 px phone at Extra large.
|
|
15
14
|
// Where the steps fit, they stay one row.
|
|
16
|
-
/* @__PURE__ */ jsx("ol", { className: "flex flex-wrap items-center gap-1 text-xs", "aria-label":
|
|
15
|
+
/* @__PURE__ */ jsx("ol", { className: "flex flex-wrap items-center gap-1 text-xs", "aria-label": ariaLabel, children: steps.map((step, i) => /* @__PURE__ */ jsxs("li", { className: "flex items-center gap-1", children: [
|
|
17
16
|
i > 0 && /* @__PURE__ */ jsx("span", { className: "w-4 border-t border-subtle" }),
|
|
18
17
|
/* @__PURE__ */ jsx(
|
|
19
18
|
"span",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/wizard-stepper.tsx"],"sourcesContent":["import { cn } from \"../lib/cn\";\n\n/** Compact step indicator for the import wizards. Past steps are plain, the\n * current one is highlighted, future ones muted. */\nexport function WizardStepper({\n steps,\n current,\n \"aria-label\":
|
|
1
|
+
{"version":3,"sources":["../../src/components/wizard-stepper.tsx"],"sourcesContent":["import { cn } from \"../lib/cn\";\n\n/** Compact step indicator for the import wizards. Past steps are plain, the\n * current one is highlighted, future ones muted. */\nexport function WizardStepper({\n steps,\n current,\n \"aria-label\": ariaLabel,\n}: {\n steps: { key: string; label: string }[];\n current: string;\n /** Names the list of steps (\"Import steps\"). */\n \"aria-label\"?: string;\n}) {\n const currentIndex = steps.findIndex((s) => s.key === current);\n return (\n // `flex-wrap`: the steps flow onto a second line rather than past the screen\n // (0.32.1, the 360 px Extra-large sweep; docs/text-size-harmonization.md §4).\n // \"Upload — Map columns — Confirm\" ran 22 px past a 360 px phone at Extra large.\n // Where the steps fit, they stay one row.\n <ol className=\"flex flex-wrap items-center gap-1 text-xs\" aria-label={ariaLabel}>\n {steps.map((step, i) => (\n <li key={step.key} className=\"flex items-center gap-1\">\n {i > 0 && <span className=\"w-4 border-t border-subtle\" />}\n <span\n aria-current={step.key === current ? \"step\" : undefined}\n className={cn(\n \"rounded-full px-2 py-0.5\",\n i === currentIndex\n ? \"bg-inverse text-inverse font-medium\"\n : i < currentIndex\n ? \"text-secondary\"\n : \"text-placeholder\",\n )}\n >\n {step.label}\n </span>\n </li>\n ))}\n </ol>\n );\n}\n"],"mappings":";AAsBQ,SACY,KADZ;AAtBR,SAAS,UAAU;AAIZ,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA,cAAc;AAChB,GAKG;AACD,QAAM,eAAe,MAAM,UAAU,CAAC,MAAM,EAAE,QAAQ,OAAO;AAC7D;AAAA;AAAA;AAAA;AAAA;AAAA,IAKE,oBAAC,QAAG,WAAU,6CAA4C,cAAY,WACnE,gBAAM,IAAI,CAAC,MAAM,MAChB,qBAAC,QAAkB,WAAU,2BAC1B;AAAA,UAAI,KAAK,oBAAC,UAAK,WAAU,8BAA6B;AAAA,MACvD;AAAA,QAAC;AAAA;AAAA,UACC,gBAAc,KAAK,QAAQ,UAAU,SAAS;AAAA,UAC9C,WAAW;AAAA,YACT;AAAA,YACA,MAAM,eACF,wCACA,IAAI,eACF,mBACA;AAAA,UACR;AAAA,UAEC,eAAK;AAAA;AAAA,MACR;AAAA,SAdO,KAAK,GAed,CACD,GACH;AAAA;AAEJ;","names":[]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export interface CurrencyOption {
|
|
2
|
+
code: string;
|
|
3
|
+
name: string;
|
|
4
|
+
symbol: string;
|
|
5
|
+
/** ISO 3166-1 alpha-2 country code (lowercase) used by flag-icons. */
|
|
6
|
+
country: string;
|
|
7
|
+
}
|
|
8
|
+
export declare const CURRENCIES: CurrencyOption[];
|
|
9
|
+
/**
|
|
10
|
+
* Each currency code → the flag the kit paints for it: the lowercase ISO 3166-1 alpha-2
|
|
11
|
+
* code flag-icons names it by (`fi-ch`, `flags/4x3/ch.svg`). `CHF` → `"ch"`, `EUR` →
|
|
12
|
+
* `"eu"` (flag-icons has the EU's flag under that code).
|
|
13
|
+
*
|
|
14
|
+
* Derived from {@link CURRENCIES}, so a currency the pickers gain is a flag here too. An
|
|
15
|
+
* app that ships only the flags it renders builds its subset from these values:
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* // vite.config.ts — plain Node, no DOM
|
|
19
|
+
* import { CURRENCY_COUNTRIES } from "@eifi1/ui-kit/currencies";
|
|
20
|
+
* const flags = new Set(Object.values(CURRENCY_COUNTRIES));
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export declare const CURRENCY_COUNTRIES: Record<string, string>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
const CURRENCIES = [
|
|
3
|
+
{ code: "EUR", name: "Euro", symbol: "\u20AC", country: "eu" },
|
|
4
|
+
{ code: "USD", name: "US Dollar", symbol: "$", country: "us" },
|
|
5
|
+
{ code: "GBP", name: "British Pound", symbol: "\xA3", country: "gb" },
|
|
6
|
+
{ code: "CHF", name: "Swiss Franc", symbol: "CHF", country: "ch" },
|
|
7
|
+
{ code: "JPY", name: "Japanese Yen", symbol: "\xA5", country: "jp" },
|
|
8
|
+
{ code: "CAD", name: "Canadian Dollar", symbol: "CA$", country: "ca" },
|
|
9
|
+
{ code: "AUD", name: "Australian Dollar", symbol: "A$", country: "au" },
|
|
10
|
+
{ code: "NZD", name: "New Zealand Dollar", symbol: "NZ$", country: "nz" },
|
|
11
|
+
{ code: "SEK", name: "Swedish Krona", symbol: "kr", country: "se" },
|
|
12
|
+
{ code: "NOK", name: "Norwegian Krone", symbol: "kr", country: "no" },
|
|
13
|
+
{ code: "DKK", name: "Danish Krone", symbol: "kr", country: "dk" },
|
|
14
|
+
{ code: "PLN", name: "Polish Zloty", symbol: "z\u0142", country: "pl" },
|
|
15
|
+
{ code: "CZK", name: "Czech Koruna", symbol: "K\u010D", country: "cz" },
|
|
16
|
+
{ code: "HUF", name: "Hungarian Forint", symbol: "Ft", country: "hu" },
|
|
17
|
+
{ code: "RON", name: "Romanian Leu", symbol: "lei", country: "ro" },
|
|
18
|
+
{ code: "BGN", name: "Bulgarian Lev", symbol: "\u043B\u0432", country: "bg" },
|
|
19
|
+
{ code: "TRY", name: "Turkish Lira", symbol: "\u20BA", country: "tr" },
|
|
20
|
+
{ code: "RUB", name: "Russian Ruble", symbol: "\u20BD", country: "ru" },
|
|
21
|
+
{ code: "CNY", name: "Chinese Yuan", symbol: "\xA5", country: "cn" },
|
|
22
|
+
{ code: "HKD", name: "Hong Kong Dollar", symbol: "HK$", country: "hk" },
|
|
23
|
+
{ code: "SGD", name: "Singapore Dollar", symbol: "S$", country: "sg" },
|
|
24
|
+
{ code: "INR", name: "Indian Rupee", symbol: "\u20B9", country: "in" },
|
|
25
|
+
{ code: "BRL", name: "Brazilian Real", symbol: "R$", country: "br" },
|
|
26
|
+
{ code: "MXN", name: "Mexican Peso", symbol: "MX$", country: "mx" },
|
|
27
|
+
{ code: "ZAR", name: "South African Rand", symbol: "R", country: "za" },
|
|
28
|
+
{ code: "ILS", name: "Israeli Shekel", symbol: "\u20AA", country: "il" },
|
|
29
|
+
{ code: "AED", name: "UAE Dirham", symbol: "\u062F.\u0625", country: "ae" }
|
|
30
|
+
];
|
|
31
|
+
const CURRENCY_COUNTRIES = Object.fromEntries(
|
|
32
|
+
CURRENCIES.map((c) => [c.code, c.country])
|
|
33
|
+
);
|
|
34
|
+
export {
|
|
35
|
+
CURRENCIES,
|
|
36
|
+
CURRENCY_COUNTRIES
|
|
37
|
+
};
|
|
38
|
+
//# sourceMappingURL=currencies.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/currencies.ts"],"sourcesContent":["// `@eifi1/ui-kit/currencies` — the currencies the kit's pickers offer, as plain data\n// (0.35, keksdose's 0.34 report).\n//\n// This module imports NOTHING: no React, no stylesheet, no other kit module. That is the\n// entry's whole promise, because an app's BUILD reads it in Node — keksdose's Vite plugin\n// builds its flag-icons subset from these country codes while Vite loads its config. Until\n// 0.35 that plugin parsed the `country` literals out of dist/components/currency-select.js;\n// 0.34 moved the list into the picker's option list and 91 of its test files failed at\n// load. A file inside dist/ is not something the kit promises; an entry is.\n// packaging-contract.test.ts pins the purity, scripts/verify-package.mjs the load in Node.\n//\n// CurrencySelect, AmountInput's currency chip and NumberInput's code detection read this\n// same array (components/currency-option-list re-exports it, and currency-select as it\n// always has), so the list the pickers show and the flags an app ships cannot drift.\n\nexport interface CurrencyOption {\n code: string;\n name: string;\n symbol: string;\n /** ISO 3166-1 alpha-2 country code (lowercase) used by flag-icons. */\n country: string;\n}\n\nexport const CURRENCIES: CurrencyOption[] = [\n { code: \"EUR\", name: \"Euro\", symbol: \"€\", country: \"eu\" },\n { code: \"USD\", name: \"US Dollar\", symbol: \"$\", country: \"us\" },\n { code: \"GBP\", name: \"British Pound\", symbol: \"£\", country: \"gb\" },\n { code: \"CHF\", name: \"Swiss Franc\", symbol: \"CHF\", country: \"ch\" },\n { code: \"JPY\", name: \"Japanese Yen\", symbol: \"¥\", country: \"jp\" },\n { code: \"CAD\", name: \"Canadian Dollar\", symbol: \"CA$\", country: \"ca\" },\n { code: \"AUD\", name: \"Australian Dollar\", symbol: \"A$\", country: \"au\" },\n { code: \"NZD\", name: \"New Zealand Dollar\", symbol: \"NZ$\", country: \"nz\" },\n { code: \"SEK\", name: \"Swedish Krona\", symbol: \"kr\", country: \"se\" },\n { code: \"NOK\", name: \"Norwegian Krone\", symbol: \"kr\", country: \"no\" },\n { code: \"DKK\", name: \"Danish Krone\", symbol: \"kr\", country: \"dk\" },\n { code: \"PLN\", name: \"Polish Zloty\", symbol: \"zł\", country: \"pl\" },\n { code: \"CZK\", name: \"Czech Koruna\", symbol: \"Kč\", country: \"cz\" },\n { code: \"HUF\", name: \"Hungarian Forint\", symbol: \"Ft\", country: \"hu\" },\n { code: \"RON\", name: \"Romanian Leu\", symbol: \"lei\", country: \"ro\" },\n { code: \"BGN\", name: \"Bulgarian Lev\", symbol: \"лв\", country: \"bg\" },\n { code: \"TRY\", name: \"Turkish Lira\", symbol: \"₺\", country: \"tr\" },\n { code: \"RUB\", name: \"Russian Ruble\", symbol: \"₽\", country: \"ru\" },\n { code: \"CNY\", name: \"Chinese Yuan\", symbol: \"¥\", country: \"cn\" },\n { code: \"HKD\", name: \"Hong Kong Dollar\", symbol: \"HK$\", country: \"hk\" },\n { code: \"SGD\", name: \"Singapore Dollar\", symbol: \"S$\", country: \"sg\" },\n { code: \"INR\", name: \"Indian Rupee\", symbol: \"₹\", country: \"in\" },\n { code: \"BRL\", name: \"Brazilian Real\", symbol: \"R$\", country: \"br\" },\n { code: \"MXN\", name: \"Mexican Peso\", symbol: \"MX$\", country: \"mx\" },\n { code: \"ZAR\", name: \"South African Rand\", symbol: \"R\", country: \"za\" },\n { code: \"ILS\", name: \"Israeli Shekel\", symbol: \"₪\", country: \"il\" },\n { code: \"AED\", name: \"UAE Dirham\", symbol: \"د.إ\", country: \"ae\" },\n];\n\n/**\n * Each currency code → the flag the kit paints for it: the lowercase ISO 3166-1 alpha-2\n * code flag-icons names it by (`fi-ch`, `flags/4x3/ch.svg`). `CHF` → `\"ch\"`, `EUR` →\n * `\"eu\"` (flag-icons has the EU's flag under that code).\n *\n * Derived from {@link CURRENCIES}, so a currency the pickers gain is a flag here too. An\n * app that ships only the flags it renders builds its subset from these values:\n *\n * ```ts\n * // vite.config.ts — plain Node, no DOM\n * import { CURRENCY_COUNTRIES } from \"@eifi1/ui-kit/currencies\";\n * const flags = new Set(Object.values(CURRENCY_COUNTRIES));\n * ```\n */\nexport const CURRENCY_COUNTRIES: Record<string, string> = Object.fromEntries(\n CURRENCIES.map((c) => [c.code, c.country]),\n);\n"],"mappings":";AAuBO,MAAM,aAA+B;AAAA,EAC1C,EAAE,MAAM,OAAO,MAAM,QAAQ,QAAQ,UAAK,SAAS,KAAK;AAAA,EACxD,EAAE,MAAM,OAAO,MAAM,aAAa,QAAQ,KAAK,SAAS,KAAK;AAAA,EAC7D,EAAE,MAAM,OAAO,MAAM,iBAAiB,QAAQ,QAAK,SAAS,KAAK;AAAA,EACjE,EAAE,MAAM,OAAO,MAAM,eAAe,QAAQ,OAAO,SAAS,KAAK;AAAA,EACjE,EAAE,MAAM,OAAO,MAAM,gBAAgB,QAAQ,QAAK,SAAS,KAAK;AAAA,EAChE,EAAE,MAAM,OAAO,MAAM,mBAAmB,QAAQ,OAAO,SAAS,KAAK;AAAA,EACrE,EAAE,MAAM,OAAO,MAAM,qBAAqB,QAAQ,MAAM,SAAS,KAAK;AAAA,EACtE,EAAE,MAAM,OAAO,MAAM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E,EAAE,MAAM,OAAO,MAAM,kBAAkB,QAAQ,UAAK,SAAS,KAAK;AAAA,EAClE,EAAE,MAAM,OAAO,MAAM,cAAc,QAAQ,iBAAO,SAAS,KAAK;AAClE;AAgBO,MAAM,qBAA6C,OAAO;AAAA,EAC/D,WAAW,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC;AAC3C;","names":[]}
|
|
@@ -1,11 +1,16 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ComponentPropsWithRef } from "react";
|
|
2
2
|
import type { AccessChoice } from "../landing/access.js";
|
|
3
3
|
import type { LandingLabels } from "../landing/landing-labels.js";
|
|
4
4
|
import type { DemoExpiry } from "./demo-countdown.js";
|
|
5
5
|
import type { DemoLabels } from "./demo-labels.js";
|
|
6
6
|
import type { DemoModel } from "./demo-session.js";
|
|
7
7
|
import type { LabelOverride } from "../i18n/kit-labels.js";
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* A `div`'s props, `ref` included since 0.35 (round 0.35 R4, the follow-up to API-2). They
|
|
10
|
+
* go on to the {@link AlertBanner} strip, so the ref is the strip's own `<div>` — never a
|
|
11
|
+
* link or a button: the banner takes no `href` or `onClick` of its own.
|
|
12
|
+
*/
|
|
13
|
+
export interface DemoBannerProps extends Omit<ComponentPropsWithRef<"div">, "children" | "onClick"> {
|
|
9
14
|
/** The demo's end: `expires_at` from the `TokenResponse`, or `demo_expires_at` from
|
|
10
15
|
* `/auth/me` (§5.3). */
|
|
11
16
|
expiresAt: DemoExpiry | null | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/demo/demo-banner.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../src/demo/demo-banner.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport type { ComponentPropsWithRef } from \"react\";\nimport { ChevronDown, ChevronUp, Timer } from \"lucide-react\";\n\nimport { cn } from \"../lib/cn\";\nimport { readSessionStored, writeSessionStored } from \"../lib/safe-storage\";\nimport { AlertBanner } from \"../components/alert-banner\";\nimport { Button } from \"../components/button\";\nimport { IconButton } from \"../components/icon-button\";\nimport { useAccessAction } from \"../landing/access\";\nimport type { AccessChoice } from \"../landing/access\";\nimport { useLandingLabels } from \"../landing/landing-labels\";\nimport type { LandingLabels } from \"../landing/landing-labels\";\nimport { useDemoCountdown } from \"./demo-countdown\";\nimport type { DemoCountdown, DemoExpiry } from \"./demo-countdown\";\nimport { useDemoLabels } from \"./demo-labels\";\nimport type { DemoLabels } from \"./demo-labels\";\nimport type { DemoModel } from \"./demo-session\";\nimport type { LabelOverride } from \"../i18n/kit-labels\";\n\n/** The default `sessionStorage` key of the collapsed state. */\nconst COLLAPSE_KEY = \"kit.demoBanner.collapsed\";\n\n/** \"Demo · 23 h 12 min left\", \"Demo · 50 min left\", the end, or plain \"Demo\". */\nfunction timeText(countdown: DemoCountdown, labels: DemoLabels): string {\n if (countdown.minutesLeft === null) return labels.badge;\n if (countdown.ended) return labels.endedTitle;\n return countdown.lastHour\n ? labels.minutesLeft(countdown.minutes)\n : labels.hoursLeft(countdown.hours, countdown.minutes);\n}\n\n/**\n * A `div`'s props, `ref` included since 0.35 (round 0.35 R4, the follow-up to API-2). They\n * go on to the {@link AlertBanner} strip, so the ref is the strip's own `<div>` — never a\n * link or a button: the banner takes no `href` or `onClick` of its own.\n */\nexport interface DemoBannerProps extends Omit<ComponentPropsWithRef<\"div\">, \"children\" | \"onClick\"> {\n /** The demo's end: `expires_at` from the `TokenResponse`, or `demo_expires_at` from\n * `/auth/me` (§5.3). */\n expiresAt: DemoExpiry | null | undefined;\n /** Which line the banner says about the data (§2.3). */\n model: DemoModel;\n /** \"Request access\". */\n access: AccessChoice;\n /** \"Sign in\" — let through for a demo session by `RedirectIfAuthed allowDemo`. Default\n * `/login`. */\n signInHref?: string;\n /** The countdown reached zero: clear the session and replace to `/demo/ended` (§5.5). */\n onEnded?: () => void;\n /** Where the collapsed state is kept for the tab's session. Default\n * `kit.demoBanner.collapsed`. */\n collapseKey?: string;\n /** The clock, for tests and previews. Default `Date.now`. Keep it stable. */\n now?: () => number;\n labels?: LabelOverride<DemoLabels>;\n /** The access words (`landing` namespace) for this instance. */\n landingLabels?: Partial<LandingLabels>;\n}\n\n/**\n * The demo's strip under the top bar, on every page of a demo session\n * (docs/landing-demo-harmonization.md §5.4) — a kit `AlertBanner` strip:\n *\n * - the time left, \"Demo · 23 h 12 min left\" — minutes only in the last hour, and the\n * warning tone in the last ten minutes (`useDemoCountdown`);\n * - one line on the model: R \"You're looking at sample data. Changes aren't possible.\",\n * S \"Your own work is deleted when the demo ends.\";\n * - \"Request access\" (the mail) and \"Sign in\".\n *\n * It collapses to the countdown alone, for the tab's session (`sessionStorage`) — never\n * hidden for good: it is a live state, like keksdose's preview banner, which a demo user\n * gets instead of. At zero it calls `onEnded`.\n *\n * The countdown is no live region: a sentence read out every minute would drown the\n * page. A screen-reader user meets it at the top of the page, and the end page says\n * the rest.\n */\nexport function DemoBanner({\n expiresAt,\n model,\n access,\n signInHref = \"/login\",\n onEnded,\n collapseKey = COLLAPSE_KEY,\n now,\n labels: labelsProp,\n landingLabels,\n className,\n ...rest\n}: DemoBannerProps) {\n const labels = useDemoLabels(labelsProp);\n const landing = useLandingLabels(landingLabels);\n const accessLink = useAccessAction(access, landingLabels);\n const countdown = useDemoCountdown(expiresAt, { now, onEnded });\n // `sessionStorage`, guarded (lib/safe-storage): blocked storage reads as \"not set\",\n // and the banner just opens again next time.\n const [collapsed, setCollapsed] = useState(() => readSessionStored(collapseKey) === \"1\");\n\n const toggle = () => {\n const next = !collapsed;\n setCollapsed(next);\n writeSessionStored(collapseKey, next ? \"1\" : null);\n };\n\n return (\n <AlertBanner\n {...rest}\n variant=\"strip\"\n size=\"sm\"\n tone={countdown.warning || countdown.ended ? \"warning\" : \"info\"}\n icon={<Timer />}\n data-demo-model={model}\n className={cn(\"sm:text-sm\", className)}\n action={\n <>\n {!collapsed && (\n <>\n <Button href={accessLink.href} variant=\"brand\" size=\"sm\">\n {accessLink.label}\n </Button>\n <Button href={signInHref} variant=\"secondary\" size=\"sm\">\n {landing.signIn}\n </Button>\n </>\n )}\n <IconButton\n size=\"2xs\"\n variant=\"ghost\"\n label={labels.details}\n // The icon alone at every text size (docs/text-size-harmonization.md §10.8):\n // a strip's one disclosure chevron beside its two links, whose state the\n // chevron and `aria-expanded` say; \"Details\" as text at Large would push the\n // links onto another line of a strip that is meant to stay one.\n labelVisible={false}\n aria-expanded={!collapsed}\n onClick={toggle}\n >\n {collapsed ? <ChevronDown /> : <ChevronUp />}\n </IconButton>\n </>\n }\n >\n <span className=\"font-semibold\">{timeText(countdown, labels)}</span>\n {!collapsed && (\n <>\n {\" \"}\n <span>{model === \"read-only\" ? labels.readOnly : labels.sandbox}</span>\n </>\n )}\n </AlertBanner>\n );\n}\n"],"mappings":";AA+GY,SAMA,UANA,KAMA,YANA;AA/GZ,SAAS,gBAAgB;AAEzB,SAAS,aAAa,WAAW,aAAa;AAE9C,SAAS,UAAU;AACnB,SAAS,mBAAmB,0BAA0B;AACtD,SAAS,mBAAmB;AAC5B,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;AAEhC,SAAS,wBAAwB;AAEjC,SAAS,wBAAwB;AAEjC,SAAS,qBAAqB;AAM9B,MAAM,eAAe;AAGrB,SAAS,SAAS,WAA0B,QAA4B;AACtE,MAAI,UAAU,gBAAgB,KAAM,QAAO,OAAO;AAClD,MAAI,UAAU,MAAO,QAAO,OAAO;AACnC,SAAO,UAAU,WACb,OAAO,YAAY,UAAU,OAAO,IACpC,OAAO,UAAU,UAAU,OAAO,UAAU,OAAO;AACzD;AAgDO,SAAS,WAAW;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA,GAAG;AACL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":[]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
interface Position {
|
|
2
|
+
line: number;
|
|
3
|
+
column: number;
|
|
4
|
+
}
|
|
5
|
+
/** The part of an ESTree string node the rule reads. */
|
|
6
|
+
interface StringNode {
|
|
7
|
+
type: string;
|
|
8
|
+
value?: unknown;
|
|
9
|
+
range?: [number, number];
|
|
10
|
+
loc?: {
|
|
11
|
+
start: Position;
|
|
12
|
+
end: Position;
|
|
13
|
+
} | null;
|
|
14
|
+
}
|
|
15
|
+
interface Fix {
|
|
16
|
+
range: [number, number];
|
|
17
|
+
text: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The part of ESLint's rule context the rule uses — `sourceCode.text` and `report`, which
|
|
21
|
+
* every ESLint since flat config has — so that ESLint's own RuleContext, and @eslint/core's
|
|
22
|
+
* that `defineConfig` checks a plugin against, are assignable to it. The source is only an
|
|
23
|
+
* `object` here because a language's source may be binary, with no `text` at all.
|
|
24
|
+
*/
|
|
25
|
+
interface RoleUtilitiesContext {
|
|
26
|
+
sourceCode: object;
|
|
27
|
+
report(descriptor: {
|
|
28
|
+
loc: {
|
|
29
|
+
start: Position;
|
|
30
|
+
end: Position;
|
|
31
|
+
};
|
|
32
|
+
messageId: string;
|
|
33
|
+
data: Record<string, string>;
|
|
34
|
+
fix: ((fixer: {
|
|
35
|
+
replaceTextRange(range: [number, number], text: string): Fix;
|
|
36
|
+
}) => Fix) | null;
|
|
37
|
+
}): void;
|
|
38
|
+
}
|
|
39
|
+
interface RoleUtilitiesRule {
|
|
40
|
+
meta: {
|
|
41
|
+
type: "suggestion";
|
|
42
|
+
docs: {
|
|
43
|
+
description: string;
|
|
44
|
+
url: string;
|
|
45
|
+
};
|
|
46
|
+
fixable: "code";
|
|
47
|
+
schema: [];
|
|
48
|
+
messages: {
|
|
49
|
+
useRoleUtility: string;
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
create(context: RoleUtilitiesContext): {
|
|
53
|
+
Literal(node: StringNode): void;
|
|
54
|
+
TemplateElement(node: StringNode): void;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Spelled out, self-reference included, so a typed config (`defineConfig`, `tseslint.config`) takes it. */
|
|
58
|
+
interface UiKitEslintPlugin {
|
|
59
|
+
meta: {
|
|
60
|
+
name: string;
|
|
61
|
+
version: string;
|
|
62
|
+
namespace: string;
|
|
63
|
+
};
|
|
64
|
+
rules: {
|
|
65
|
+
"role-utilities": RoleUtilitiesRule;
|
|
66
|
+
};
|
|
67
|
+
configs: {
|
|
68
|
+
/** The rule as an error, on every file the app's other config objects lint but its tests. */
|
|
69
|
+
recommended: {
|
|
70
|
+
name: string;
|
|
71
|
+
ignores: string[];
|
|
72
|
+
plugins: {
|
|
73
|
+
"@eifi1/ui-kit": UiKitEslintPlugin;
|
|
74
|
+
};
|
|
75
|
+
rules: {
|
|
76
|
+
"@eifi1/ui-kit/role-utilities": "error";
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** The flat-config plugin: add `configs.recommended`, or register it under `@eifi1/ui-kit`. */
|
|
82
|
+
declare const plugin: UiKitEslintPlugin;
|
|
83
|
+
export default plugin;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { findRoleClasses } from "./role-utilities.js";
|
|
3
|
+
import { ROLE_UTILITIES } from "./role-utilities.generated.js";
|
|
4
|
+
const roleUtilities = {
|
|
5
|
+
meta: {
|
|
6
|
+
type: "suggestion",
|
|
7
|
+
docs: {
|
|
8
|
+
description: "Write a colour role's utility (text-muted) rather than its [var(--\u2026)] class",
|
|
9
|
+
url: "https://github.com/Eifi1/ui-kit#lint-the-role-utilities-in-an-app"
|
|
10
|
+
},
|
|
11
|
+
fixable: "code",
|
|
12
|
+
schema: [],
|
|
13
|
+
messages: {
|
|
14
|
+
useRoleUtility: "Write the role utility `{{utilities}}`, not `{{found}}`: variants and an opacity work on it the same (tokens.css, @theme inline)."
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
create(context) {
|
|
18
|
+
const source = context.sourceCode;
|
|
19
|
+
const text = typeof source.text === "string" ? source.text : "";
|
|
20
|
+
const check = (node) => {
|
|
21
|
+
if (!node.range || !node.loc) return;
|
|
22
|
+
const [start] = node.range;
|
|
23
|
+
const { line, column } = node.loc.start;
|
|
24
|
+
const at = (offset) => {
|
|
25
|
+
const lines = text.slice(start, start + offset).split("\n");
|
|
26
|
+
const last = lines.length - 1;
|
|
27
|
+
return { line: line + last, column: last ? lines[last].length : column + offset };
|
|
28
|
+
};
|
|
29
|
+
for (const hit of findRoleClasses(text.slice(start, node.range[1]), ROLE_UTILITIES)) {
|
|
30
|
+
const end = hit.index + hit.found.length;
|
|
31
|
+
const range = [start + hit.index, start + end];
|
|
32
|
+
const [only] = hit.utilities;
|
|
33
|
+
context.report({
|
|
34
|
+
loc: { start: at(hit.index), end: at(end) },
|
|
35
|
+
messageId: "useRoleUtility",
|
|
36
|
+
data: { found: hit.found, utilities: hit.utilities.join("` or `") },
|
|
37
|
+
// Several names for one token are a choice, not a fix.
|
|
38
|
+
fix: hit.utilities.length === 1 ? (fixer) => fixer.replaceTextRange(range, only) : null
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
Literal(node) {
|
|
44
|
+
if (typeof node.value === "string") check(node);
|
|
45
|
+
},
|
|
46
|
+
TemplateElement: check
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const VERSION = true ? "0.35.0" : "0.0.0-source";
|
|
51
|
+
const recommended = {
|
|
52
|
+
name: "@eifi1/ui-kit/recommended",
|
|
53
|
+
// Not the tests, as check:tokens skips the kit's: a test names the old class to assert it
|
|
54
|
+
// is gone (keksdose's cleared-status-toggle.test.tsx does, three times).
|
|
55
|
+
ignores: ["**/__tests__/**", "**/*.test.*", "**/*.spec.*"],
|
|
56
|
+
plugins: {},
|
|
57
|
+
rules: { "@eifi1/ui-kit/role-utilities": "error" }
|
|
58
|
+
};
|
|
59
|
+
const plugin = {
|
|
60
|
+
meta: { name: "@eifi1/ui-kit", version: VERSION, namespace: "@eifi1/ui-kit" },
|
|
61
|
+
rules: { "role-utilities": roleUtilities },
|
|
62
|
+
configs: { recommended }
|
|
63
|
+
};
|
|
64
|
+
recommended.plugins["@eifi1/ui-kit"] = plugin;
|
|
65
|
+
var eslint_default = plugin;
|
|
66
|
+
export {
|
|
67
|
+
eslint_default as default
|
|
68
|
+
};
|
|
69
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/eslint/index.ts"],"sourcesContent":["// `@eifi1/ui-kit/eslint` — the kit's role-utility rule for an app's own markup (round 0.35\n// R5, Kurvenschmiede's Q6).\n//\n// The kit holds its markup to \"write `text-muted`, not `text-[var(--text-muted)]`\" with\n// `npm run check:tokens`, at zero since 0.34. The apps are asked to follow the same rule\n// (README \"How to write a colour\"), but nothing in their builds objected when a\n// `[var(--role)]` class came back. This is that check as an ESLint plugin, so an app's\n// `eslint.config.js` turns it on with one line:\n//\n// import uiKit from \"@eifi1/ui-kit/eslint\";\n// export default [..., uiKit.configs.recommended];\n//\n// It reads every string literal and template-literal quasi — a JSX `className`, a `cn()` or\n// `clsx()` argument, a class constant — and reports a `[var(--x)]` class where the property\n// has a role utility for that token, naming it. One utility is an autofix that keeps the\n// variants and the opacity: `hover:text-[var(--text-muted)]/70` → `hover:text-muted/70`.\n//\n// Plain Node, like the rest of an ESLint config: no React, no stylesheet, and no import of\n// `eslint` itself, which is the app's (packaging-contract.test.ts refuses an undeclared\n// package in src/), so the few types it needs are written out below.\nimport { findRoleClasses } from \"./role-utilities\";\nimport { ROLE_UTILITIES } from \"./role-utilities.generated\";\n\ninterface Position {\n line: number;\n column: number;\n}\n\n/** The part of an ESTree string node the rule reads. */\ninterface StringNode {\n type: string;\n value?: unknown;\n range?: [number, number];\n loc?: { start: Position; end: Position } | null;\n}\n\ninterface Fix {\n range: [number, number];\n text: string;\n}\n\n/**\n * The part of ESLint's rule context the rule uses — `sourceCode.text` and `report`, which\n * every ESLint since flat config has — so that ESLint's own RuleContext, and @eslint/core's\n * that `defineConfig` checks a plugin against, are assignable to it. The source is only an\n * `object` here because a language's source may be binary, with no `text` at all.\n */\ninterface RoleUtilitiesContext {\n sourceCode: object;\n report(descriptor: {\n loc: { start: Position; end: Position };\n messageId: string;\n data: Record<string, string>;\n fix: ((fixer: { replaceTextRange(range: [number, number], text: string): Fix }) => Fix) | null;\n }): void;\n}\n\ninterface RoleUtilitiesRule {\n meta: {\n type: \"suggestion\";\n docs: { description: string; url: string };\n fixable: \"code\";\n schema: [];\n messages: { useRoleUtility: string };\n };\n create(context: RoleUtilitiesContext): {\n Literal(node: StringNode): void;\n TemplateElement(node: StringNode): void;\n };\n}\n\nconst roleUtilities: RoleUtilitiesRule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Write a colour role's utility (text-muted) rather than its [var(--…)] class\",\n url: \"https://github.com/Eifi1/ui-kit#lint-the-role-utilities-in-an-app\",\n },\n fixable: \"code\",\n schema: [],\n messages: {\n useRoleUtility:\n \"Write the role utility `{{utilities}}`, not `{{found}}`: variants and an opacity work on it the same (tokens.css, @theme inline).\",\n },\n },\n create(context) {\n const source = context.sourceCode as { text?: unknown };\n const text = typeof source.text === \"string\" ? source.text : \"\";\n const check = (node: StringNode) => {\n if (!node.range || !node.loc) return;\n const [start] = node.range;\n const { line, column } = node.loc.start;\n // An offset in the node's source text — quotes included, so it is an offset in the\n // file — as a position. A template literal may span lines.\n const at = (offset: number): Position => {\n const lines = text.slice(start, start + offset).split(\"\\n\");\n const last = lines.length - 1;\n return { line: line + last, column: last ? lines[last].length : column + offset };\n };\n for (const hit of findRoleClasses(text.slice(start, node.range[1]), ROLE_UTILITIES)) {\n const end = hit.index + hit.found.length;\n const range: [number, number] = [start + hit.index, start + end];\n const [only] = hit.utilities;\n context.report({\n loc: { start: at(hit.index), end: at(end) },\n messageId: \"useRoleUtility\",\n data: { found: hit.found, utilities: hit.utilities.join(\"` or `\") },\n // Several names for one token are a choice, not a fix.\n fix: hit.utilities.length === 1 ? (fixer) => fixer.replaceTextRange(range, only) : null,\n });\n }\n };\n return {\n Literal(node) {\n if (typeof node.value === \"string\") check(node);\n },\n TemplateElement: check,\n };\n },\n};\n\n// The kit's version, baked in by tsup's `define` (tsup.config.ts). ESLint's cache keys a\n// file's result on each plugin's name@version, so without it an app's `eslint --cache`\n// would keep a file's old verdict after a kit release that gave a role a utility. Unset\n// when the source runs (the tests), where nothing is cached.\ndeclare const __UI_KIT_VERSION__: string | undefined;\nconst VERSION = typeof __UI_KIT_VERSION__ === \"string\" ? __UI_KIT_VERSION__ : \"0.0.0-source\";\n\n/** Spelled out, self-reference included, so a typed config (`defineConfig`, `tseslint.config`) takes it. */\ninterface UiKitEslintPlugin {\n meta: { name: string; version: string; namespace: string };\n rules: { \"role-utilities\": RoleUtilitiesRule };\n configs: {\n /** The rule as an error, on every file the app's other config objects lint but its tests. */\n recommended: {\n name: string;\n ignores: string[];\n plugins: { \"@eifi1/ui-kit\": UiKitEslintPlugin };\n rules: { \"@eifi1/ui-kit/role-utilities\": \"error\" };\n };\n };\n}\n\nconst recommended: UiKitEslintPlugin[\"configs\"][\"recommended\"] = {\n name: \"@eifi1/ui-kit/recommended\",\n // Not the tests, as check:tokens skips the kit's: a test names the old class to assert it\n // is gone (keksdose's cleared-status-toggle.test.tsx does, three times).\n ignores: [\"**/__tests__/**\", \"**/*.test.*\", \"**/*.spec.*\"],\n plugins: {} as UiKitEslintPlugin[\"configs\"][\"recommended\"][\"plugins\"],\n rules: { \"@eifi1/ui-kit/role-utilities\": \"error\" },\n};\n\n/** The flat-config plugin: add `configs.recommended`, or register it under `@eifi1/ui-kit`. */\nconst plugin: UiKitEslintPlugin = {\n meta: { name: \"@eifi1/ui-kit\", version: VERSION, namespace: \"@eifi1/ui-kit\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