mirror of
https://github.com/navikt/aksel.git
synced 2026-11-24 21:54:05 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
010a2028f8 | ||
|
|
4700da665c | ||
|
|
0de6bc83bc | ||
|
|
8c73a23939 | ||
|
|
6d608cda93 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@navikt/ds-react": patch
|
||||
---
|
||||
|
||||
Popover and other floating components: Dismiss when focus leaves the overlay and its trigger, including inside web components.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@navikt/ds-react": patch
|
||||
---
|
||||
|
||||
Switch: `<Switch />` elements inside a `<Fieldset />` with `readOnly` now share a single padlock in the group legend instead of displaying one per switch. Each switch retains screen-reader text indicating its read-only state, and standalone switches keep their individual padlocks.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@navikt/ds-react": patch
|
||||
---
|
||||
|
||||
Button: Preserve keyboard modifiers during native Space activation.
|
||||
@@ -48,8 +48,8 @@
|
||||
- `corepack yarn tsc --noEmit --incremental false --project <tsconfig>` - targeted type-check
|
||||
- `corepack yarn workspace <name> <script>` - e.g. `@navikt/ds-react test` (Vitest + tsc), `website test`
|
||||
- `corepack yarn lint` / `corepack yarn test` / `corepack yarn boot` - root suites (slow; cross-workspace changes only)
|
||||
- `corepack yarn storybook` (:6006) / `corepack yarn storybook:aksel` (website examples, :6007, no secrets) / `corepack yarn storybook:test` (play tests in Playwright Chromium, Firefox and WebKit; only Chromium when `COPILOT_CLI` is set; filter with `--browser.name=<browser>`) / `corepack yarn dev` (website, :3000, needs Sanity token)
|
||||
- Targeted play tests: `corepack yarn storybook:test <path/to/X.tests.stories.tsx>` (repo root). Run after changing play tests. Under Copilot CLI this runs only Chromium (Firefox/WebKit can't launch in the cplt sandbox; CI covers them); if the browser can't launch, report tests as not run with the exact command.
|
||||
- `corepack yarn storybook` (:6006) / `corepack yarn storybook:aksel` (website examples, :6007, no secrets) / `corepack yarn storybook:test` (play tests, Playwright Firefox; Chromium when `COPILOT_CLI` is set) / `corepack yarn dev` (website, :3000, needs Sanity token)
|
||||
- Targeted play tests: `corepack yarn storybook:test <path/to/X.tests.stories.tsx>` (repo root). Run after changing play tests. Under Copilot CLI this runs Chromium; if the browser can't launch, report tests as not run with the exact command.
|
||||
|
||||
## Where to edit
|
||||
|
||||
|
||||
@@ -17,4 +17,4 @@ applyTo: "**/*.test.ts,**/*.test.tsx,**/*.stories.tsx"
|
||||
- Before removing or consolidating tests, map each meaningful old scenario/assertion to its replacement story or test. Keep coverage that still represents a supported behavior; explain when a scenario is intentionally obsolete.
|
||||
- For state, accessibility, keyboard or focus behavior, use the [component-contract skill](../skills/component-contract/SKILL.md) to identify the contract and evidence to preserve.
|
||||
- ds-react unit tests run with `TZ=UTC`. Date logic must not depend on the local timezone.
|
||||
- Browser tests run in Playwright Chromium, Firefox and WebKit (one CI job each). Under Copilot CLI only Chromium runs, since Firefox/WebKit can't launch in the cplt sandbox (see `vitest.config.mts`). Run one browser with `--browser.name=<browser>`. Yarn has `enableScripts: false`, so if the browser is missing, report it instead of installing globally.
|
||||
- Browser tests need Playwright Firefox (Chromium under Copilot CLI, see `vitest.config.mts`). Yarn has `enableScripts: false`, so if the browser is missing, report it instead of installing globally.
|
||||
@@ -71,15 +71,11 @@ jobs:
|
||||
run: yarn test
|
||||
|
||||
ui:
|
||||
name: UI tests (Storybook, ${{ matrix.browser }})
|
||||
name: UI tests (Storybook)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.61.1-noble
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
browser: [chromium, firefox, webkit]
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v7
|
||||
@@ -93,6 +89,6 @@ jobs:
|
||||
npm_auth_token: ${{ secrets.READER_TOKEN }}
|
||||
|
||||
- name: Test UI
|
||||
run: yarn storybook:test --max-workers=2 --browser.name=${{ matrix.browser }}
|
||||
run: yarn storybook:test --max-workers=2
|
||||
env:
|
||||
HOME: /root
|
||||
Vendored
+3
-10
@@ -2,17 +2,10 @@
|
||||
"cssVariables.lookupFiles": ["@navikt/core/tokens/dist/tokens.css"],
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"files.watcherExclude": {
|
||||
"**/.git/objects/**": true,
|
||||
"**/.git/subtree-cache/**": true,
|
||||
"**/node_modules/**": true,
|
||||
"**/.yarn/**": true,
|
||||
"**/dist/**": true,
|
||||
"**/esm/**": true,
|
||||
"**/cjs/**": true,
|
||||
"**/lib/**": true,
|
||||
"**/@navikt/aksel-icons/src/**": true,
|
||||
"**/.next/**": true,
|
||||
"**/storybook-static/**": true
|
||||
"**/dist": true,
|
||||
"**/esm": true,
|
||||
"**/cjs": true
|
||||
},
|
||||
"playwright.reuseBrowser": true,
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib",
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# @navikt/aksel-icons
|
||||
|
||||
## 8.23.1
|
||||
|
||||
## 8.23.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@navikt/aksel-icons",
|
||||
"version": "8.23.1",
|
||||
"version": "8.23.0",
|
||||
"author": "Aksel | Nav",
|
||||
"homepage": "https://aksel.nav.no/ikoner",
|
||||
"repository": {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# @navikt/aksel-stylelint
|
||||
|
||||
## 8.23.1
|
||||
|
||||
## 8.23.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@navikt/aksel-stylelint",
|
||||
"version": "8.23.1",
|
||||
"version": "8.23.0",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=18.12.0"
|
||||
@@ -43,8 +43,8 @@
|
||||
"dev": "yarn watch:lint"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@navikt/ds-css": "^8.23.1",
|
||||
"@navikt/ds-tokens": "^8.23.1",
|
||||
"@navikt/ds-css": "^8.23.0",
|
||||
"@navikt/ds-tokens": "^8.23.0",
|
||||
"concurrently": "10.0.6",
|
||||
"postcss-selector-parser": "^7.1.7",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# @navikt/aksel
|
||||
|
||||
## 8.23.1
|
||||
|
||||
## 8.23.0
|
||||
|
||||
## 8.22.1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@navikt/aksel",
|
||||
"version": "8.23.1",
|
||||
"version": "8.23.0",
|
||||
"description": "Aksel command line interface. Codemods and other utilities for Aksel users.",
|
||||
"author": "Aksel | Nav designsystem team",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
# @navikt/ds-css
|
||||
|
||||
## 8.23.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- DataGrid: Change `overflow:hidden` to `min-height:0` and `min-width:0` on root ([#5568](https://github.com/navikt/aksel/pull/5568))
|
||||
|
||||
## 8.23.0
|
||||
|
||||
## 8.22.1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@navikt/ds-css",
|
||||
"version": "8.23.1",
|
||||
"version": "8.23.0",
|
||||
"description": "CSS for Nav Designsystem",
|
||||
"author": "Aksel | Nav designsystem team",
|
||||
"keywords": [
|
||||
@@ -32,7 +32,7 @@
|
||||
"css:get-version": "node config/get-version.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@navikt/ds-tokens": "^8.23.1",
|
||||
"@navikt/ds-tokens": "^8.23.0",
|
||||
"browserslist": "^4.28.7",
|
||||
"esbuild": "^0.28.2",
|
||||
"fast-glob": "3.3.3",
|
||||
|
||||
@@ -6,10 +6,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
|
||||
/* Makes DataGridRoot shrink inside a height-limited flex container */
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.aksel-data-table__frame {
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
# @navikt/ds-react
|
||||
|
||||
## 8.23.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- DataGrid: Keyboard navigation in table no longer prevents shift+tabbing away from the table ([`7dbf1d5`](https://github.com/navikt/aksel/commit/7dbf1d5382367837b1f43fc76ca57d986218b64d))
|
||||
|
||||
- Button: Preserve keyboard modifiers during native Space activation. ([#5564](https://github.com/navikt/aksel/pull/5564))
|
||||
|
||||
- DataGrid.Table: Temporarily removed `topContent` and `bottomContent` props. ([#5579](https://github.com/navikt/aksel/pull/5579))
|
||||
|
||||
- Updated dependencies []:
|
||||
- @navikt/ds-tokens@8.23.1
|
||||
- @navikt/aksel-icons@8.23.1
|
||||
|
||||
## 8.23.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@navikt/ds-react",
|
||||
"version": "8.23.1",
|
||||
"version": "8.23.0",
|
||||
"description": "React components from the Norwegian Labour and Welfare Administration.",
|
||||
"author": "Aksel, a team part of the Norwegian Labour and Welfare Administration.",
|
||||
"license": "MIT",
|
||||
@@ -788,8 +788,8 @@
|
||||
"dependencies": {
|
||||
"@floating-ui/react": "0.27.20",
|
||||
"@floating-ui/react-dom": "^2.1.9",
|
||||
"@navikt/aksel-icons": "^8.23.1",
|
||||
"@navikt/ds-tokens": "^8.23.1",
|
||||
"@navikt/aksel-icons": "^8.23.0",
|
||||
"@navikt/ds-tokens": "^8.23.0",
|
||||
"date-fns": "^4.0.0",
|
||||
"react-day-picker": "10.0.2"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { DataGrid } from "..";
|
||||
import { Pagination } from "../../pagination";
|
||||
import { HStack, VStack } from "../../primitives/stack";
|
||||
import { Detail } from "../../typography";
|
||||
import {
|
||||
type DataGridPlugin,
|
||||
type DataGridPlugins,
|
||||
applyTableContext,
|
||||
resolveDataGridPlugins,
|
||||
} from "./dataGridPlugins";
|
||||
|
||||
type InvoiceRow = {
|
||||
id: string;
|
||||
invoiceNumber: string;
|
||||
category: string;
|
||||
status: string;
|
||||
amount: string;
|
||||
};
|
||||
|
||||
const DEMO_ROWS: InvoiceRow[] = [
|
||||
{
|
||||
id: "1",
|
||||
invoiceNumber: "INV-2026-001",
|
||||
category: "Cloud Hosting",
|
||||
status: "Paid",
|
||||
amount: "12 400 kr",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
invoiceNumber: "INV-2026-002",
|
||||
category: "Software License",
|
||||
status: "Pending",
|
||||
amount: "4 850 kr",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
invoiceNumber: "INV-2026-003",
|
||||
category: "Office Supplies",
|
||||
status: "Paid",
|
||||
amount: "1 290 kr",
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
invoiceNumber: "INV-2026-004",
|
||||
category: "Security Audit",
|
||||
status: "Overdue",
|
||||
amount: "28 000 kr",
|
||||
},
|
||||
{
|
||||
id: "5",
|
||||
invoiceNumber: "INV-2026-005",
|
||||
category: "Hardware",
|
||||
status: "Paid",
|
||||
amount: "19 990 kr",
|
||||
},
|
||||
{
|
||||
id: "6",
|
||||
invoiceNumber: "INV-2026-006",
|
||||
category: "Training",
|
||||
status: "Pending",
|
||||
amount: "7 500 kr",
|
||||
},
|
||||
{
|
||||
id: "7",
|
||||
invoiceNumber: "INV-2026-007",
|
||||
category: "Domain Renewal",
|
||||
status: "Paid",
|
||||
amount: "640 kr",
|
||||
},
|
||||
{
|
||||
id: "8",
|
||||
invoiceNumber: "INV-2026-008",
|
||||
category: "Monitoring",
|
||||
status: "Pending",
|
||||
amount: "3 200 kr",
|
||||
},
|
||||
];
|
||||
|
||||
const DEMO_COLUMNS: DataGrid.Columns<InvoiceRow> = [
|
||||
{
|
||||
id: "invoiceNumber",
|
||||
header: "Invoice",
|
||||
isRowHeader: true,
|
||||
bodyCell: (row) => row.invoiceNumber,
|
||||
},
|
||||
{ id: "category", header: "Category", bodyCell: (row) => row.category },
|
||||
{ id: "status", header: "Status", bodyCell: (row) => row.status },
|
||||
{ id: "amount", header: "Amount", bodyCell: (row) => row.amount },
|
||||
];
|
||||
|
||||
/**
|
||||
* Preview of how `DataGrid` will integrate the plugin API.
|
||||
* Only two lines are added around `DataGrid`'s children:
|
||||
* 1. `resolveDataGridPlugins(userPlugins)` to order and stabilize plugins
|
||||
* 2. `applyTableContext(plugins, children)` to wrap the grid output
|
||||
*/
|
||||
function PluginAwareDataGrid<RowT>({
|
||||
plugins: userPlugins,
|
||||
children,
|
||||
...dataGridProps
|
||||
}: DataGrid.Props<RowT> & { plugins?: DataGridPlugins }) {
|
||||
const plugins = resolveDataGridPlugins(userPlugins);
|
||||
|
||||
return (
|
||||
<DataGrid {...dataGridProps}>
|
||||
{applyTableContext(plugins, children)}
|
||||
</DataGrid>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Example first-party plugin hook.
|
||||
* The consumer owns pagination state; the hook returns a memoized `DataGridPlugin`
|
||||
* that wraps the table with Aksel's `<Pagination />`.
|
||||
*/
|
||||
function useDummyPaginationPlugin({
|
||||
page,
|
||||
pageSize,
|
||||
totalItems,
|
||||
onPageChange,
|
||||
}: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalItems: number;
|
||||
onPageChange: (nextPage: number) => void;
|
||||
}): DataGridPlugin {
|
||||
return useMemo(() => {
|
||||
const pageCount = Math.max(1, Math.ceil(totalItems / pageSize));
|
||||
const start = (page - 1) * pageSize + 1;
|
||||
const end = Math.min(page * pageSize, totalItems);
|
||||
|
||||
return {
|
||||
transformTableContext: (children) => (
|
||||
<VStack gap="space-12" data-plugin="pagination">
|
||||
{children}
|
||||
<HStack align="center" justify="space-between" gap="space-16" wrap>
|
||||
<Detail>
|
||||
Showing {start}–{end} of {totalItems}
|
||||
</Detail>
|
||||
<Pagination
|
||||
page={page}
|
||||
count={pageCount}
|
||||
onPageChange={onPageChange}
|
||||
size="small"
|
||||
/>
|
||||
</HStack>
|
||||
</VStack>
|
||||
),
|
||||
};
|
||||
}, [page, pageSize, totalItems, onPageChange]);
|
||||
}
|
||||
|
||||
const meta: Meta = {
|
||||
title: "ds-react/DataGrid/Plugins",
|
||||
parameters: {
|
||||
chromatic: { disable: true },
|
||||
layout: "padded",
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj;
|
||||
|
||||
/**
|
||||
* Shows the intended consumer API for a first-party plugin hook:
|
||||
* state stays in consumer code, the hook returns a memoized `DataGridPlugin`,
|
||||
* and `DataGrid` renders it through `plugins={{ pagination }}`.
|
||||
*/
|
||||
export const PaginationPlugin: Story = {
|
||||
render: function PaginationPluginDemo() {
|
||||
const [page, setPage] = useState(1);
|
||||
const pageSize = 3;
|
||||
|
||||
const paginationPlugin = useDummyPaginationPlugin({
|
||||
page,
|
||||
pageSize,
|
||||
totalItems: DEMO_ROWS.length,
|
||||
onPageChange: setPage,
|
||||
});
|
||||
|
||||
const pageRows = useMemo(
|
||||
() => DEMO_ROWS.slice((page - 1) * pageSize, page * pageSize),
|
||||
[page],
|
||||
);
|
||||
|
||||
return (
|
||||
<PluginAwareDataGrid
|
||||
columns={DEMO_COLUMNS}
|
||||
data={pageRows}
|
||||
getRowId={(row) => row.id}
|
||||
plugins={{ pagination: paginationPlugin }}
|
||||
>
|
||||
<DataGrid.Table />
|
||||
</PluginAwareDataGrid>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import * as consoleWarningModule from "../../utils/helpers/consoleWarning";
|
||||
import {
|
||||
type DataGridPlugin,
|
||||
type DataGridPlugins,
|
||||
applyTableContext,
|
||||
resolveDataGridPlugins,
|
||||
} from "./dataGridPlugins";
|
||||
|
||||
const createContextPlugin = (label: string): DataGridPlugin => ({
|
||||
transformTableContext: (children) => `${label}(${children})`,
|
||||
});
|
||||
|
||||
describe("resolveDataGridPlugins", () => {
|
||||
test("returns a stable empty array when plugins are undefined or empty", () => {
|
||||
const initialResult = resolveDataGridPlugins(undefined);
|
||||
expect(initialResult).toEqual([]);
|
||||
expect(resolveDataGridPlugins({})).toBe(initialResult);
|
||||
});
|
||||
|
||||
test("orders known plugins before unknown plugins, ignores prototype keys, and skips non-object entries", () => {
|
||||
const customFirst = createContextPlugin("first");
|
||||
const customSecond = createContextPlugin("second");
|
||||
const pagination = createContextPlugin("pagination");
|
||||
|
||||
expect(
|
||||
resolveDataGridPlugins({
|
||||
zCustom: customFirst,
|
||||
aCustom: customSecond,
|
||||
pagination,
|
||||
}),
|
||||
).toEqual([pagination, customFirst, customSecond]);
|
||||
|
||||
const inherited = Object.create({ pagination }) as DataGridPlugins;
|
||||
inherited.custom = customFirst;
|
||||
expect(resolveDataGridPlugins(inherited)).toEqual([customFirst]);
|
||||
|
||||
// Runtime guard: nullish or primitive entries on known or custom keys are skipped instead of crashing WeakMap
|
||||
expect(
|
||||
resolveDataGridPlugins({
|
||||
pagination: undefined,
|
||||
customUndefined: undefined,
|
||||
customNull: null,
|
||||
customPrimitive: "not-an-object",
|
||||
valid: customFirst,
|
||||
} as unknown as DataGridPlugins),
|
||||
).toEqual([customFirst]);
|
||||
});
|
||||
|
||||
test("interns array reference by plugin identity and order across inline objects", () => {
|
||||
const pagination = createContextPlugin("pagination");
|
||||
const customA = createContextPlugin("a");
|
||||
const customB = createContextPlugin("b");
|
||||
|
||||
const first = resolveDataGridPlugins({ customA, pagination });
|
||||
expect(Object.isFrozen(first)).toBe(true);
|
||||
|
||||
// New inline object with same plugin instances (even in different key order)
|
||||
expect(resolveDataGridPlugins({ pagination, customA })).toBe(first);
|
||||
|
||||
// Removing a plugin returns a new array; restoring it returns the interned array
|
||||
const paginationOnly = resolveDataGridPlugins({ pagination });
|
||||
expect(paginationOnly).not.toBe(first);
|
||||
expect(paginationOnly).toEqual([pagination]);
|
||||
|
||||
expect(resolveDataGridPlugins({ pagination, customA })).toBe(first);
|
||||
|
||||
// Changing plugin order or replacing an instance produces a new array
|
||||
const ab = resolveDataGridPlugins({ customA, customB });
|
||||
const ba = resolveDataGridPlugins({ customB, customA });
|
||||
expect(ba).not.toBe(ab);
|
||||
expect(ba).toEqual([customB, customA]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyTableContext", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test("wraps children in reverse plugin order and skips plugins without a valid transform", () => {
|
||||
const pagination = createContextPlugin("pagination");
|
||||
const custom = createContextPlugin("custom");
|
||||
const noopPlugin = {} as DataGridPlugin;
|
||||
const invalidPlugin = {
|
||||
transformTableContext: "not-a-function",
|
||||
} as unknown as DataGridPlugin;
|
||||
|
||||
expect(applyTableContext([], "table")).toBe("table");
|
||||
expect(
|
||||
applyTableContext(
|
||||
[pagination, noopPlugin, invalidPlugin, custom],
|
||||
"table",
|
||||
),
|
||||
).toBe("pagination(custom(table))");
|
||||
});
|
||||
|
||||
test("preserves previous content and warns when transformTableContext returns undefined", () => {
|
||||
const warnSpy = vi
|
||||
.spyOn(consoleWarningModule, "consoleWarning")
|
||||
.mockImplementation(() => {});
|
||||
const outer = createContextPlugin("outer");
|
||||
const returnsUndefined: DataGridPlugin = {
|
||||
transformTableContext: () => undefined,
|
||||
};
|
||||
const inner = createContextPlugin("inner");
|
||||
|
||||
expect(applyTableContext([outer, returnsUndefined, inner], "table")).toBe(
|
||||
"outer(inner(table))",
|
||||
);
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("transformTableContext returned undefined"),
|
||||
);
|
||||
});
|
||||
|
||||
test("catches plugin errors, logs them, and continues applying remaining plugins", () => {
|
||||
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const boom = new Error("plugin failure");
|
||||
const outer = createContextPlugin("outer");
|
||||
const broken: DataGridPlugin = {
|
||||
transformTableContext: () => {
|
||||
throw boom;
|
||||
},
|
||||
};
|
||||
const inner = createContextPlugin("inner");
|
||||
|
||||
expect(applyTableContext([outer, broken, inner], "table")).toBe(
|
||||
"outer(inner(table))",
|
||||
);
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
"[Aksel] DataGrid: Plugin threw in transformTableContext:",
|
||||
boom,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { consoleWarning } from "../../utils/helpers/consoleWarning";
|
||||
|
||||
/**
|
||||
* Plugin that extends DataGrid rendering (e.g. wrapping the table in providers
|
||||
* or extra UI). Remember to memoize the plugin object (with `useMemo`) so
|
||||
* DataGrid can skip unnecessary re-renders.
|
||||
*/
|
||||
interface DataGridPlugin {
|
||||
/**
|
||||
* Wraps the table output in context providers or surrounding UI (e.g. pagination).
|
||||
* Runs as a plain function during render. Do not call React hooks directly
|
||||
* inside this function; render a component or provider that calls hooks instead.
|
||||
*/
|
||||
transformTableContext: (children: ReactNode) => ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixed order for built-in plugins so behavior doesn't depend on key order
|
||||
* in `plugins={{ ... }}`. Custom plugins are placed after these, in their
|
||||
* original order.
|
||||
*/
|
||||
const PLUGIN_ORDER = ["pagination"] as const;
|
||||
const KNOWN_PLUGINS = new Set<string>(PLUGIN_ORDER);
|
||||
|
||||
type BuiltInDataGridPluginKey = (typeof PLUGIN_ORDER)[number];
|
||||
|
||||
/**
|
||||
* Named plugins passed to DataGrid.
|
||||
*
|
||||
* Keep plugins always present rather than toggling entries conditionally:
|
||||
* adding or removing a plugin that wraps children changes React's tree depth and remounts the grid.
|
||||
* Control active/visible state inside the plugin instead.
|
||||
*/
|
||||
type DataGridPlugins = Partial<
|
||||
Record<BuiltInDataGridPluginKey, DataGridPlugin>
|
||||
> &
|
||||
Record<string, DataGridPlugin>;
|
||||
|
||||
/**
|
||||
* We freeze in dev-mode to enforce immutability of the empty plugin array.
|
||||
* Based on React best practices: https://react.dev/reference/react/createElement#caveats
|
||||
*/
|
||||
const EMPTY_PLUGINS: readonly never[] =
|
||||
process.env.NODE_ENV !== "production" ? Object.freeze([]) : [];
|
||||
|
||||
/**
|
||||
* Turns a `plugins={{ ... }}` object into an ordered, stable plugin array.
|
||||
*
|
||||
* - Orders built-in plugins consistently (`orderPlugins`).
|
||||
* - Keeps the same array reference even when the consumer passes an inline
|
||||
* `plugins={{ pagination }}` object on every render (`internByIdentity`).
|
||||
*/
|
||||
function resolveDataGridPlugins(
|
||||
userPlugins?: DataGridPlugins,
|
||||
): readonly DataGridPlugin[] {
|
||||
return internByIdentity(orderPlugins(userPlugins));
|
||||
}
|
||||
|
||||
// WeakMap keys must be objects; guard against nullish/primitive entries at runtime.
|
||||
function isPluginObject(value: unknown): value is DataGridPlugin {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Places known plugins first (in `PLUGIN_ORDER`), then unknown plugins in
|
||||
* insertion order.
|
||||
*/
|
||||
function orderPlugins(
|
||||
userPlugins?: DataGridPlugins,
|
||||
): readonly DataGridPlugin[] {
|
||||
if (!userPlugins) {
|
||||
return EMPTY_PLUGINS;
|
||||
}
|
||||
|
||||
const keys = Object.keys(userPlugins);
|
||||
if (keys.length === 0) {
|
||||
return EMPTY_PLUGINS;
|
||||
}
|
||||
|
||||
const ordered: DataGridPlugin[] = [];
|
||||
|
||||
for (const name of PLUGIN_ORDER) {
|
||||
/* TS target does not support Object.hasOwn */
|
||||
if (Object.prototype.hasOwnProperty.call(userPlugins, name)) {
|
||||
const plugin = userPlugins[name];
|
||||
if (isPluginObject(plugin)) {
|
||||
ordered.push(plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const name of keys) {
|
||||
if (!KNOWN_PLUGINS.has(name)) {
|
||||
const plugin = userPlugins[name];
|
||||
if (isPluginObject(plugin)) {
|
||||
ordered.push(plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ordered;
|
||||
}
|
||||
|
||||
interface InternNode {
|
||||
readonly next: WeakMap<object, InternNode>;
|
||||
array?: readonly object[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tree of WeakMaps where each path represents a sequence of plugin objects.
|
||||
* WeakMap lets unused paths be garbage-collected when plugins go away.
|
||||
*/
|
||||
const internRoot: InternNode = { next: new WeakMap() };
|
||||
|
||||
/**
|
||||
* Returns the same array instance whenever given the same objects in the same order
|
||||
* using a WeakMap trie (prefix tree keyed by object identity).
|
||||
*
|
||||
* Solves inline `plugins={{ pagination }}` props: `useMemo` on the outer object
|
||||
* would miss every render, and mutating a `useRef` during render is unsafe in
|
||||
* StrictMode / concurrent React.
|
||||
*
|
||||
* Each item walks one step down `internRoot`:
|
||||
* ```text
|
||||
* internRoot
|
||||
* └─ [pluginA] ──▶ nodeA (array: [pluginA])
|
||||
* └─ [pluginB] ──▶ nodeAB (array: [pluginA, pluginB])
|
||||
* └─ [pluginB] ──▶ nodeB
|
||||
* └─ [pluginA] ──▶ nodeBA (array: [pluginB, pluginA])
|
||||
* ```
|
||||
*
|
||||
* 1. Walk `internRoot` using each item as a `WeakMap` key, creating nodes as needed.
|
||||
* 2. Cache a copy at the terminal node so future calls with the same sequence return the exact same (`===`) array.
|
||||
* 3. Unused branches are garbage-collected automatically once any plugin object in the path is no longer referenced.
|
||||
*/
|
||||
function internByIdentity<T extends object>(items: readonly T[]): readonly T[] {
|
||||
if (items.length === 0) {
|
||||
return EMPTY_PLUGINS;
|
||||
}
|
||||
|
||||
let node = internRoot;
|
||||
for (const item of items) {
|
||||
let child = node.next.get(item);
|
||||
if (child === undefined) {
|
||||
child = { next: new WeakMap() };
|
||||
node.next.set(item, child);
|
||||
}
|
||||
node = child;
|
||||
}
|
||||
|
||||
if (node.array === undefined) {
|
||||
const copy = items.slice();
|
||||
/* Freeze in dev so accidental mutation fails fast instead of corrupting the shared cache. */
|
||||
node.array =
|
||||
process.env.NODE_ENV !== "production" ? Object.freeze(copy) : copy;
|
||||
}
|
||||
return node.array as readonly T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps `children` with each plugin's `transformTableContext`.
|
||||
* Runs in reverse so the first plugin wraps outermost.
|
||||
* Synchronous errors are caught and logged, and an `undefined` return preserves
|
||||
* the previous content so one broken plugin doesn't blank or crash the grid.
|
||||
*/
|
||||
function applyTableContext(
|
||||
plugins: readonly DataGridPlugin[],
|
||||
children: ReactNode,
|
||||
): ReactNode {
|
||||
let content = children;
|
||||
|
||||
for (let i = plugins.length - 1; i >= 0; i--) {
|
||||
const transform = plugins[i].transformTableContext;
|
||||
|
||||
if (typeof transform !== "function") {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const next = transform(content);
|
||||
if (next === undefined) {
|
||||
consoleWarning(
|
||||
"DataGrid: Plugin transformTableContext returned undefined. Preserving previous content.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
content = next;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[Aksel] DataGrid: Plugin threw in transformTableContext:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
export { applyTableContext, resolveDataGridPlugins };
|
||||
export type { DataGridPlugin, DataGridPlugins };
|
||||
@@ -59,7 +59,6 @@ export const Attachments: Story = {
|
||||
table content scrolls.
|
||||
</BodyShort>
|
||||
</VStack>
|
||||
<Content />
|
||||
<div
|
||||
style={{
|
||||
overflow: "hidden",
|
||||
@@ -70,8 +69,8 @@ export const Attachments: Story = {
|
||||
>
|
||||
<DataGrid columns={getColDefs(overflow)} data={getData(overflow)}>
|
||||
<DataGrid.Table
|
||||
// topContent={<Content />}
|
||||
// bottomContent={<Content />}
|
||||
topContent={<Content />}
|
||||
bottomContent={<Content />}
|
||||
stickyHeader
|
||||
/>
|
||||
</DataGrid>
|
||||
|
||||
@@ -22,7 +22,6 @@ type UseTableKeyboardNavOptions = {
|
||||
|
||||
function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
|
||||
const [tableRef, setTableRef] = useState<HTMLTableElement | null>(null);
|
||||
const [isFocusWithin, setIsFocusWithin] = useState(false);
|
||||
const { getTableGrid, activeCell, setActiveCell } = useGridCache(
|
||||
tableRef,
|
||||
enabled,
|
||||
@@ -123,7 +122,6 @@ function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
|
||||
* Make sure td/th elements have tabIndex={-1} so they can receive focus on click
|
||||
*/
|
||||
const handleTableFocusIn = useEventCallback((event: FocusEvent): void => {
|
||||
setIsFocusWithin(true);
|
||||
const target = event.target as Element | null;
|
||||
|
||||
if (tableRef && target === tableRef) {
|
||||
@@ -148,15 +146,6 @@ function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
|
||||
}
|
||||
});
|
||||
|
||||
const handleTableFocusOut = useEventCallback((event: FocusEvent): void => {
|
||||
if (
|
||||
!(event.relatedTarget instanceof Node) ||
|
||||
!tableRef?.contains(event.relatedTarget)
|
||||
) {
|
||||
setIsFocusWithin(false);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Attach event listeners for keyboard navigation and focus management.
|
||||
*/
|
||||
@@ -167,27 +156,16 @@ function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
|
||||
|
||||
tableRef.addEventListener("keydown", handleTableKeyDown);
|
||||
tableRef.addEventListener("focusin", handleTableFocusIn);
|
||||
tableRef.addEventListener("focusout", handleTableFocusOut);
|
||||
|
||||
return () => {
|
||||
tableRef.removeEventListener("keydown", handleTableKeyDown);
|
||||
tableRef.removeEventListener("focusin", handleTableFocusIn);
|
||||
tableRef.removeEventListener("focusout", handleTableFocusOut);
|
||||
};
|
||||
}, [
|
||||
tableRef,
|
||||
handleTableKeyDown,
|
||||
handleTableFocusIn,
|
||||
handleTableFocusOut,
|
||||
enabled,
|
||||
]);
|
||||
}, [tableRef, handleTableKeyDown, handleTableFocusIn, enabled]);
|
||||
|
||||
return {
|
||||
/*
|
||||
* Table should only have tabIndex until the focus is moved inside and is enabled
|
||||
* This allows focus to "escape" the table and move to other elements on the page.
|
||||
*/
|
||||
tabIndex: enabled ? (isFocusWithin ? -1 : 0) : undefined,
|
||||
/* Table should only have tabIndex until the focus is moved inside and is enabled */
|
||||
tabIndex: enabled ? 0 : undefined,
|
||||
setTableRef,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -138,16 +138,14 @@ interface DataGridTableProps<T> extends React.HTMLAttributes<HTMLTableElement> {
|
||||
* @default "row"
|
||||
*/
|
||||
selectionTrigger?: "row" | "control";
|
||||
|
||||
/* TODO: Temp removed to better integrate with plugins API */
|
||||
/**
|
||||
* Content to render above the table, outside its scrollable area.
|
||||
*/
|
||||
//topContent?: React.ReactNode;
|
||||
topContent?: React.ReactNode;
|
||||
/**
|
||||
* Content to render below the table, outside its scrollable area.
|
||||
*/
|
||||
//bottomContent?: React.ReactNode;
|
||||
bottomContent?: React.ReactNode;
|
||||
}
|
||||
|
||||
const DataGridTableInternal = forwardRef<
|
||||
@@ -171,6 +169,8 @@ const DataGridTableInternal = forwardRef<
|
||||
subRows,
|
||||
sorting,
|
||||
selectionTrigger = "row",
|
||||
topContent,
|
||||
bottomContent,
|
||||
...rest
|
||||
}: DataGridTableProps<unknown>,
|
||||
forwardedRef,
|
||||
@@ -211,31 +211,31 @@ const DataGridTableInternal = forwardRef<
|
||||
|
||||
const tableId = useId(id);
|
||||
|
||||
// const hasTopContent = topContent != null && topContent !== false;
|
||||
// const hasBottomContent = bottomContent != null && bottomContent !== false;
|
||||
// let attachmentPosition: "top" | "bottom" | "both" | undefined;
|
||||
const hasTopContent = topContent != null && topContent !== false;
|
||||
const hasBottomContent = bottomContent != null && bottomContent !== false;
|
||||
let attachmentPosition: "top" | "bottom" | "both" | undefined;
|
||||
|
||||
/* TODO: Need to figure out how to handle this since settings is provided from root, not table itself */
|
||||
const truncateContent = tableSettings?.truncateContent ?? layout !== "auto";
|
||||
|
||||
// if (hasTopContent && hasBottomContent) {
|
||||
// attachmentPosition = "both";
|
||||
// } else if (hasTopContent) {
|
||||
// attachmentPosition = "top";
|
||||
// } else if (hasBottomContent) {
|
||||
// attachmentPosition = "bottom";
|
||||
// }
|
||||
if (hasTopContent && hasBottomContent) {
|
||||
attachmentPosition = "both";
|
||||
} else if (hasTopContent) {
|
||||
attachmentPosition = "top";
|
||||
} else if (hasBottomContent) {
|
||||
attachmentPosition = "bottom";
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="aksel-data-table__frame"
|
||||
// data-attachments={attachmentPosition}
|
||||
data-attachments={attachmentPosition}
|
||||
>
|
||||
{/* {hasTopContent && (
|
||||
{hasTopContent && (
|
||||
<div className="aksel-data-table__attachment" data-attachment="top">
|
||||
{topContent}
|
||||
</div>
|
||||
)} */}
|
||||
)}
|
||||
|
||||
<DataTableContextProvider
|
||||
layout={layout}
|
||||
@@ -314,14 +314,14 @@ const DataGridTableInternal = forwardRef<
|
||||
</table>
|
||||
</TableElementWrapper>
|
||||
</DataTableContextProvider>
|
||||
{/* {hasBottomContent && (
|
||||
{hasBottomContent && (
|
||||
<div
|
||||
className="aksel-data-table__attachment"
|
||||
data-attachment="bottom"
|
||||
>
|
||||
{bottomContent}
|
||||
</div>
|
||||
)} */}
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
within,
|
||||
} from "storybook/test";
|
||||
import { Button } from "../button";
|
||||
import { Popover } from "../popover";
|
||||
import { Provider } from "../provider";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -702,7 +701,6 @@ export const TabToLinks: Story = {
|
||||
play: async ({ canvasElement, args }) => {
|
||||
const { canvas } = testUtils(canvasElement, args);
|
||||
|
||||
await waitFor(() => expect(canvas.getByTestId("popup")).toHaveFocus());
|
||||
await userEvent.tab();
|
||||
expect(canvas.getByPlaceholderText("test")).toHaveFocus();
|
||||
await userEvent.tab();
|
||||
@@ -714,78 +712,6 @@ export const TabToLinks: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
/* ----------------------- Nested dismissable layers ------------------------ */
|
||||
function PopoverInDialog() {
|
||||
const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(
|
||||
null,
|
||||
);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
ref={setAnchorEl}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
Popover trigger
|
||||
</button>
|
||||
<Popover open={open} anchorEl={anchorEl} onClose={() => setOpen(false)}>
|
||||
<Popover.Content>
|
||||
<button type="button">Inside popover</button>
|
||||
</Popover.Content>
|
||||
</Popover>
|
||||
<button type="button">Dialog button</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const PopoverInsideDialog: Story = {
|
||||
render: BaseDialogComponent,
|
||||
beforeEach: withoutAnimations,
|
||||
play: async ({ canvasElement, args }) => {
|
||||
const { canvas, expectPopupOpen, expectOpenChangeCalls } = testUtils(
|
||||
canvasElement,
|
||||
args,
|
||||
);
|
||||
await waitFor(() => expect(canvas.getByTestId("popup")).toHaveFocus());
|
||||
|
||||
const popoverTrigger = canvas.getByRole("button", {
|
||||
name: "Popover trigger",
|
||||
});
|
||||
const openPopover = async () => {
|
||||
popoverTrigger.focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
expect(popoverTrigger).toHaveAttribute("aria-expanded", "true");
|
||||
};
|
||||
|
||||
await openPopover();
|
||||
await userEvent.tab();
|
||||
expect(
|
||||
canvas.getByRole("button", { name: "Inside popover" }),
|
||||
).toHaveFocus();
|
||||
await userEvent.tab();
|
||||
expect(canvas.getByRole("button", { name: "Dialog button" })).toHaveFocus();
|
||||
await waitFor(() =>
|
||||
expect(popoverTrigger).toHaveAttribute("aria-expanded", "false"),
|
||||
);
|
||||
expectPopupOpen();
|
||||
|
||||
await openPopover();
|
||||
await userEvent.keyboard("{Escape}");
|
||||
await waitFor(() =>
|
||||
expect(popoverTrigger).toHaveAttribute("aria-expanded", "false"),
|
||||
);
|
||||
expectPopupOpen();
|
||||
expectOpenChangeCalls(0);
|
||||
},
|
||||
args: {
|
||||
rootProps: { defaultOpen: true, onOpenChange: fn() },
|
||||
popupProps: { children: <PopoverInDialog /> },
|
||||
},
|
||||
};
|
||||
|
||||
/* ------------------------------- Test setup ------------------------------- */
|
||||
type BaseDialogProps = {
|
||||
rootProps?: Omit<DialogProps, "children"> & { children?: React.ReactNode };
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import React from "react";
|
||||
import { renderStoriesForChromatic } from "../../utils/renderStoriesForChromatic";
|
||||
import { Fieldset } from "../fieldset";
|
||||
import Switch from "./Switch";
|
||||
|
||||
export default {
|
||||
@@ -126,15 +125,6 @@ export const Readonly: Story = {
|
||||
parameters: { controls: { disable: true } },
|
||||
};
|
||||
|
||||
export const ReadonlyGroup: Story = {
|
||||
render: () => (
|
||||
<Fieldset legend="Notifikasjoner" readOnly>
|
||||
<Switch defaultChecked>SMS</Switch>
|
||||
<Switch>E-post</Switch>
|
||||
</Fieldset>
|
||||
),
|
||||
};
|
||||
|
||||
export const ColorRole: Story = {
|
||||
render: () => (
|
||||
<div className="colgap" data-color="brand-magenta">
|
||||
@@ -168,7 +158,6 @@ export const Chromatic = renderStoriesForChromatic(
|
||||
Disabled,
|
||||
HideLabel,
|
||||
Readonly,
|
||||
ReadonlyGroup,
|
||||
ColorRole,
|
||||
},
|
||||
Switch,
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
import React, {
|
||||
type InputHTMLAttributes,
|
||||
forwardRef,
|
||||
useContext,
|
||||
useState,
|
||||
} from "react";
|
||||
import React, { type InputHTMLAttributes, forwardRef, useState } from "react";
|
||||
import { Loader } from "../../loader";
|
||||
import { BodyShort } from "../../typography";
|
||||
import { omit } from "../../utils-external";
|
||||
import { cl } from "../../utils/helpers";
|
||||
import { useI18n } from "../../utils/i18n/i18n.hooks";
|
||||
import { ReadOnlyIconWithTitle } from "../ReadOnlyIcon";
|
||||
import { FieldsetContext } from "../fieldset/context";
|
||||
import { type FormFieldProps, useFormField } from "../useFormField";
|
||||
|
||||
export interface SwitchProps
|
||||
@@ -129,7 +122,7 @@ export const Switch = forwardRef<HTMLInputElement, SwitchProps>(
|
||||
})}
|
||||
>
|
||||
<BodyShort as="span" size={size} className="aksel-switch__label">
|
||||
{readOnly && <ReadOnlyIcon />}
|
||||
{readOnly && <ReadOnlyIconWithTitle />}
|
||||
{children}
|
||||
</BodyShort>
|
||||
{description && (
|
||||
@@ -148,16 +141,6 @@ export const Switch = forwardRef<HTMLInputElement, SwitchProps>(
|
||||
},
|
||||
);
|
||||
|
||||
const ReadOnlyIcon = () => {
|
||||
const fieldset = useContext(FieldsetContext);
|
||||
const readOnlyText = useI18n("global")("readOnly");
|
||||
|
||||
if (fieldset?.readOnly) {
|
||||
return <span className="aksel-sr-only">{readOnlyText}</span>;
|
||||
}
|
||||
return <ReadOnlyIconWithTitle />;
|
||||
};
|
||||
|
||||
const SwitchIcon = ({
|
||||
size,
|
||||
checked,
|
||||
|
||||
@@ -48,7 +48,6 @@ export const Default = () => {
|
||||
|
||||
return (
|
||||
<div tabIndex={-1}>
|
||||
<Button>Before</Button>
|
||||
<Button ref={setAnchorEl} onClick={() => setOpen((x) => !x)}>
|
||||
Open
|
||||
</Button>
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { StoryObj } from "@storybook/react-vite";
|
||||
import React, { useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { expect, fn, userEvent, waitFor, within } from "storybook/test";
|
||||
import { Dialog, DialogPopup, DialogTitle, DialogTrigger } from "../dialog";
|
||||
import { expect, userEvent, waitFor, within } from "storybook/test";
|
||||
import { Popover } from "./root/PopoverRoot";
|
||||
|
||||
export default {
|
||||
@@ -103,283 +101,6 @@ export const KeepOpenOnPopoverClick: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
function tick() {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function ShadowFocusTestRender() {
|
||||
const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button type="button" ref={setAnchorEl} onClick={() => setOpen(true)}>
|
||||
Open popover
|
||||
</button>
|
||||
<Popover open={open} anchorEl={anchorEl} onClose={() => setOpen(false)}>
|
||||
<button type="button">Inside popover</button>
|
||||
{open &&
|
||||
anchorEl &&
|
||||
createPortal(
|
||||
<button type="button">Portaled popover content</button>,
|
||||
anchorEl.ownerDocument.body,
|
||||
)}
|
||||
</Popover>
|
||||
<button type="button">Another button</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const DismissOnFocusLeavingShadowPopover: Story = {
|
||||
globals: { webComponentWrapper: "open" },
|
||||
render: function NestedShadowPopover() {
|
||||
const [root, setRoot] = useState<ShadowRoot | null>(null);
|
||||
const attachRoot = React.useCallback((host: HTMLDivElement | null) => {
|
||||
if (host) {
|
||||
setRoot(host.shadowRoot ?? host.attachShadow({ mode: "open" }));
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div ref={attachRoot} data-testid="inner-host" />
|
||||
{root && createPortal(<ShadowFocusTestRender />, root)}
|
||||
<button type="button">Enclosing root button</button>
|
||||
</>
|
||||
);
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const outerRoot = canvasElement.firstElementChild?.shadowRoot;
|
||||
const outerMount = outerRoot?.querySelector("div");
|
||||
if (!outerRoot || !outerMount) {
|
||||
throw new Error("Expected the open shadow root Storybook decorator");
|
||||
}
|
||||
|
||||
const outerCanvas = within(outerMount);
|
||||
const innerRoot = outerCanvas.getByTestId("inner-host").shadowRoot;
|
||||
const innerMount = innerRoot?.querySelector("div");
|
||||
if (!innerRoot || !innerMount) {
|
||||
throw new Error("Expected a popover in the nested shadow root");
|
||||
}
|
||||
|
||||
const canvas = within(innerMount);
|
||||
const anchor = canvas.getByRole("button", { name: "Open popover" });
|
||||
const sibling = canvas.getByRole("button", { name: "Another button" });
|
||||
const enclosingButton = outerCanvas.getByRole("button", {
|
||||
name: "Enclosing root button",
|
||||
});
|
||||
|
||||
await userEvent.click(anchor);
|
||||
const inside = canvas.getByRole("button", { name: "Inside popover" });
|
||||
inside.focus();
|
||||
expect(innerRoot.activeElement).toBe(inside);
|
||||
|
||||
// Portaled content and anchor keep the popover open.
|
||||
const portaled = within(canvasElement.ownerDocument.body).getByRole(
|
||||
"button",
|
||||
{ name: "Portaled popover content" },
|
||||
);
|
||||
portaled.focus();
|
||||
await tick();
|
||||
expect(portaled).toHaveFocus();
|
||||
expect(inside).toBeVisible();
|
||||
|
||||
anchor.focus();
|
||||
await tick();
|
||||
expect(innerRoot.activeElement).toBe(anchor);
|
||||
expect(inside).toBeVisible();
|
||||
|
||||
// Moving focus to a sibling in the same shadow root closes the popover.
|
||||
sibling.focus();
|
||||
expect(innerRoot.activeElement).toBe(sibling);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
canvas.queryByRole("button", { name: "Inside popover" }),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
|
||||
// Moving focus to an enclosing shadow root closes the popover.
|
||||
await userEvent.click(anchor);
|
||||
canvas.getByRole("button", { name: "Inside popover" }).focus();
|
||||
await tick();
|
||||
enclosingButton.focus();
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
canvas.queryByRole("button", { name: "Inside popover" }),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(outerRoot.activeElement).toBe(enclosingButton);
|
||||
},
|
||||
};
|
||||
|
||||
function FocusScenarioRender({
|
||||
onClose,
|
||||
children,
|
||||
}: {
|
||||
onClose?: () => void;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button type="button">Before</button>
|
||||
<button
|
||||
type="button"
|
||||
ref={setAnchorEl}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
Trigger
|
||||
</button>
|
||||
<Popover
|
||||
open={open}
|
||||
anchorEl={anchorEl}
|
||||
onClose={() => {
|
||||
onClose?.();
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Popover.Content>
|
||||
<button type="button">Inside</button>
|
||||
{children}
|
||||
</Popover.Content>
|
||||
</Popover>
|
||||
<button type="button">After</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getFocusScenario(canvasElement: HTMLElement) {
|
||||
const canvas = within(canvasElement);
|
||||
const trigger = canvas.getByRole("button", { name: "Trigger" });
|
||||
return {
|
||||
canvas,
|
||||
before: canvas.getByRole("button", { name: "Before" }),
|
||||
trigger,
|
||||
after: canvas.getByRole("button", { name: "After" }),
|
||||
openWithKeyboard: async () => {
|
||||
trigger.focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
expect(trigger).toHaveAttribute("aria-expanded", "true");
|
||||
},
|
||||
expectClosed: () =>
|
||||
waitFor(() => expect(trigger).toHaveAttribute("aria-expanded", "false")),
|
||||
};
|
||||
}
|
||||
|
||||
function SelfRemovingButton() {
|
||||
const [visible, setVisible] = useState(true);
|
||||
return visible ? (
|
||||
<button type="button" onClick={() => setVisible(false)}>
|
||||
Remove me
|
||||
</button>
|
||||
) : null;
|
||||
}
|
||||
|
||||
export const FocusOutside: Story = {
|
||||
render: (args) => (
|
||||
<FocusScenarioRender onClose={args.onClose}>
|
||||
<SelfRemovingButton />
|
||||
<iframe title="Embedded" srcDoc="<button>Inside frame</button>" />
|
||||
{createPortal(<button type="button">Portaled</button>, document.body)}
|
||||
</FocusScenarioRender>
|
||||
),
|
||||
play: async ({ args, canvasElement }) => {
|
||||
const { canvas, before, trigger, after, openWithKeyboard, expectClosed } =
|
||||
getFocusScenario(canvasElement);
|
||||
|
||||
// Tabbing back to trigger keeps open; tabbing past it closes.
|
||||
await openWithKeyboard();
|
||||
await userEvent.tab();
|
||||
expect(canvas.getByRole("button", { name: "Inside" })).toHaveFocus();
|
||||
await userEvent.tab({ shift: true });
|
||||
expect(trigger).toHaveFocus();
|
||||
await tick();
|
||||
expect(args.onClose).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.tab({ shift: true });
|
||||
expect(before).toHaveFocus();
|
||||
await expectClosed();
|
||||
expect(args.onClose).toHaveBeenCalledOnce();
|
||||
|
||||
// Portal, iframe, and removed focused content keep open; outside focus closes.
|
||||
await openWithKeyboard();
|
||||
within(document.body).getByRole("button", { name: "Portaled" }).focus();
|
||||
await tick();
|
||||
canvas.getByTitle("Embedded").focus();
|
||||
await tick();
|
||||
canvas.getByRole("button", { name: "Remove me" }).focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
canvas.queryByRole("button", { name: "Remove me" }),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
await tick();
|
||||
expect(args.onClose).toHaveBeenCalledOnce();
|
||||
expect(trigger).toHaveAttribute("aria-expanded", "true");
|
||||
|
||||
after.focus();
|
||||
await expectClosed();
|
||||
expect(args.onClose).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
args: { onClose: fn() },
|
||||
};
|
||||
|
||||
export const KeepOpenWhileNestedDialogIsOpen: Story = {
|
||||
render: (args) => (
|
||||
<FocusScenarioRender onClose={args.onClose}>
|
||||
<Dialog>
|
||||
<DialogTrigger>
|
||||
<button type="button">Open dialog</button>
|
||||
</DialogTrigger>
|
||||
<DialogPopup aria-labelledby="nested-dialog-title">
|
||||
<DialogTitle id="nested-dialog-title">Nested dialog</DialogTitle>
|
||||
<button type="button">Dialog button</button>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</FocusScenarioRender>
|
||||
),
|
||||
beforeEach: () => {
|
||||
globalThis.AKSEL_NO_EXIT_ANIMATIONS = true;
|
||||
return () => {
|
||||
globalThis.AKSEL_NO_EXIT_ANIMATIONS = false;
|
||||
};
|
||||
},
|
||||
play: async ({ args, canvasElement }) => {
|
||||
const { canvas, trigger, openWithKeyboard, expectClosed } =
|
||||
getFocusScenario(canvasElement);
|
||||
const page = within(document.body);
|
||||
|
||||
await openWithKeyboard();
|
||||
const dialogTrigger = canvas.getByRole("button", { name: "Open dialog" });
|
||||
dialogTrigger.focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
|
||||
const dialog = await page.findByRole("dialog", { name: "Nested dialog" });
|
||||
await waitFor(() => expect(dialog).toHaveFocus());
|
||||
await userEvent.tab();
|
||||
expect(page.getByRole("button", { name: "Dialog button" })).toHaveFocus();
|
||||
await userEvent.tab();
|
||||
await userEvent.tab({ shift: true });
|
||||
await tick();
|
||||
expect(args.onClose).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.keyboard("{Escape}");
|
||||
await waitFor(() => expect(dialog).not.toBeInTheDocument());
|
||||
await waitFor(() => expect(dialogTrigger).toHaveFocus());
|
||||
await tick();
|
||||
expect(args.onClose).not.toHaveBeenCalled();
|
||||
expect(trigger).toHaveAttribute("aria-expanded", "true");
|
||||
|
||||
await userEvent.keyboard("{Escape}");
|
||||
await expectClosed();
|
||||
},
|
||||
args: { onClose: fn() },
|
||||
};
|
||||
|
||||
function PopoverPlacementTestRender({
|
||||
anchorTop,
|
||||
popoverHeight,
|
||||
|
||||
@@ -135,7 +135,7 @@ export const OpenDelay: Story = {
|
||||
{ timeout: 250 },
|
||||
);
|
||||
await waitFor(() => expect(canvas.getByRole("tooltip")).toBeVisible(), {
|
||||
timeout: 1000,
|
||||
timeout: 500,
|
||||
});
|
||||
},
|
||||
};
|
||||
+26
-46
@@ -47,36 +47,20 @@ export const FocusOutside: Story = {
|
||||
render: (props) => {
|
||||
return (
|
||||
<div>
|
||||
<button type="button">Before layer</button>
|
||||
<DismissableLayer asChild {...props}>
|
||||
<button type="button">Inside layer</button>
|
||||
<input type="text" />
|
||||
</DismissableLayer>
|
||||
<button type="button">After layer</button>
|
||||
<input type="text" data-testid="outside" />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
play: async ({ args, canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
const before = canvas.getByRole("button", { name: "Before layer" });
|
||||
const inside = canvas.getByRole("button", { name: "Inside layer" });
|
||||
const after = canvas.getByRole("button", { name: "After layer" });
|
||||
play: async ({ args }) => {
|
||||
const canvas = within(document.body);
|
||||
const outsideInput = canvas.getByTestId("outside");
|
||||
outsideInput.focus();
|
||||
|
||||
inside.focus();
|
||||
expect(inside).toHaveFocus();
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
expect(args.onFocusOutside).not.toHaveBeenCalled();
|
||||
|
||||
after.focus();
|
||||
expect(after).toHaveFocus();
|
||||
await waitFor(() => expect(args.onFocusOutside).toHaveBeenCalledOnce());
|
||||
expect(args.onFocusOutside).toHaveBeenCalledOnce();
|
||||
expect(args.onDismiss).toHaveBeenCalledOnce();
|
||||
|
||||
// Focus that never entered the layer (e.g. Safari leaving focus on body after click).
|
||||
after.blur();
|
||||
expect(document.body).toHaveFocus();
|
||||
before.focus();
|
||||
await waitFor(() => expect(args.onFocusOutside).toHaveBeenCalledTimes(2));
|
||||
expect(args.onDismiss).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
args: {
|
||||
onDismiss: fn(),
|
||||
@@ -174,9 +158,7 @@ export const InteractOutside: Story = {
|
||||
|
||||
outsideFocus.focus();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
|
||||
expect(args.onDismiss).toHaveBeenCalledTimes(2);
|
||||
|
||||
await userEvent.click(outsideElement);
|
||||
@@ -224,6 +206,8 @@ export const SafeZone: Story = {
|
||||
const [safeAnchor, setSafeAnchor] = React.useState<HTMLDivElement | null>(
|
||||
null,
|
||||
);
|
||||
const [safeContainer, setSafeContainer] =
|
||||
React.useState<HTMLDivElement | null>(null);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -239,42 +223,38 @@ export const SafeZone: Story = {
|
||||
{...props}
|
||||
safeZone={{
|
||||
anchor: safeAnchor,
|
||||
dismissable: safeContainer,
|
||||
}}
|
||||
>
|
||||
<button type="button">Inside layer</button>
|
||||
<div data-testid="safe-container" ref={setSafeContainer}>
|
||||
<button type="button">test</button>
|
||||
</div>
|
||||
</DismissableLayer>
|
||||
<button type="button">Outside layer</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
play: async ({ args }) => {
|
||||
const canvas = within(document.body);
|
||||
const outsideAnchor = canvas.getByTestId("safe-anchor");
|
||||
const inside = canvas.getByRole("button", { name: "Inside layer" });
|
||||
const outside = canvas.getByRole("button", { name: "Outside layer" });
|
||||
const outsideContainer = canvas.getByTestId("safe-container");
|
||||
|
||||
expect(args.onDismiss).not.toHaveBeenCalled();
|
||||
expect(args.onInteractOutside).not.toHaveBeenCalled();
|
||||
|
||||
outsideAnchor.focus();
|
||||
inside.focus();
|
||||
outsideAnchor.focus();
|
||||
expect(outsideAnchor).toHaveFocus();
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
expect(args.onDismiss).not.toHaveBeenCalled();
|
||||
expect(args.onInteractOutside).not.toHaveBeenCalled();
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
|
||||
|
||||
outsideContainer.focus();
|
||||
expect(args.onDismiss).not.toHaveBeenCalled();
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
|
||||
|
||||
await userEvent.click(outsideAnchor);
|
||||
expect(args.onDismiss).not.toHaveBeenCalled();
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(2);
|
||||
|
||||
await userEvent.click(inside);
|
||||
await userEvent.click(outsideContainer);
|
||||
expect(args.onDismiss).not.toHaveBeenCalled();
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
|
||||
|
||||
outsideAnchor.focus();
|
||||
outside.focus();
|
||||
await waitFor(() => expect(args.onDismiss).toHaveBeenCalledOnce());
|
||||
expect(args.onInteractOutside).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
args: {
|
||||
@@ -340,14 +320,14 @@ export const NestedPointerEvents: StoryObj<{
|
||||
|
||||
await fireEvent.pointerDown(outside);
|
||||
|
||||
await waitFor(() => {
|
||||
waitFor(() => {
|
||||
expect(args.root.onDismiss).not.toHaveBeenCalled();
|
||||
expect(args.nested.onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
await userEvent.click(outside);
|
||||
|
||||
await waitFor(() => {
|
||||
waitFor(() => {
|
||||
expect(args.root.onDismiss).toHaveBeenCalledTimes(1);
|
||||
expect(args.nested.onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -606,7 +586,7 @@ export const PreventEvents: Story = {
|
||||
expect(args.onDismiss).not.toHaveBeenCalled();
|
||||
|
||||
outsideFocus.focus();
|
||||
await waitFor(() => expect(args.onFocusOutside).toHaveBeenCalledOnce());
|
||||
|
||||
expect(args.onDismiss).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.click(outsideElement);
|
||||
@@ -616,7 +596,7 @@ export const PreventEvents: Story = {
|
||||
args: {
|
||||
onDismiss: fn(),
|
||||
onInteractOutside: (event) => event.preventDefault(),
|
||||
onFocusOutside: fn((event) => event.preventDefault()),
|
||||
onFocusOutside: (event) => event.preventDefault(),
|
||||
onEscapeKeyDown: (event) => event.preventDefault(),
|
||||
onPointerDownOutside: (event) => event.preventDefault(),
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@ import React, {
|
||||
useState,
|
||||
} from "react";
|
||||
import { composeEventHandlers, ownerDocument } from "../../helpers";
|
||||
import { useMergeRefs } from "../../hooks";
|
||||
import { useMergeRefs, useTimeout } from "../../hooks";
|
||||
import type { AsChildProps } from "../../types";
|
||||
import { Slot } from "../slot/Slot";
|
||||
import type {
|
||||
@@ -49,7 +49,7 @@ interface DismissableLayerBaseProps extends React.HTMLAttributes<HTMLDivElement>
|
||||
*/
|
||||
enablePointerUpOutside?: boolean;
|
||||
/**
|
||||
* Event handler called when focus moves outside the layer and its anchor.
|
||||
* Event handler called when the focus moves outside of the `DismissableLayer`.
|
||||
* Can be prevented.
|
||||
*/
|
||||
onFocusOutside?: (event: CustomFocusEvent) => void;
|
||||
@@ -118,6 +118,8 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
const context = useContext(DismissableLayerContext);
|
||||
|
||||
const triggerPointerDownRef = useRef<boolean>(false);
|
||||
const dismissedWithPointerRef = useRef<boolean>(false);
|
||||
const timeout = useTimeout();
|
||||
|
||||
const [, forceRerender] = useState({});
|
||||
const [node, setNode] = React.useState<DismissableLayerElement | null>(
|
||||
@@ -144,11 +146,14 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
* We want to prevent the Layer from closing when the trigger/anchor element or its child elements are interacted with.
|
||||
* To achieve this, we check if the event target is the trigger/anchor or a child. If it is, we prevent default event behavior.
|
||||
*/
|
||||
function handleOutsidePointerEvent(event: CustomPointerEvent) {
|
||||
function handleOutsideEvent(event: CustomFocusEvent | CustomPointerEvent) {
|
||||
if (!safeZone?.anchor) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventType = event.detail.originalEvent.type as
|
||||
"pointerup" | "pointerdown" | "focusin";
|
||||
|
||||
const target = event.target as HTMLElement;
|
||||
|
||||
const targetIsAnchor =
|
||||
@@ -163,7 +168,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
* Therefore, checking anchor.contains(target) etc. won't work in that case.
|
||||
*/
|
||||
if (
|
||||
event.detail.originalEvent.type === "pointerdown" &&
|
||||
eventType === "pointerdown" &&
|
||||
triggerPointerDownRef.current === true
|
||||
) {
|
||||
event.preventDefault();
|
||||
@@ -172,29 +177,23 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
triggerPointerDownRef.current = false;
|
||||
}
|
||||
|
||||
const focusOutside = useFocusOutside(
|
||||
(event) => {
|
||||
onFocusOutside?.(event);
|
||||
onInteractOutside?.(event);
|
||||
|
||||
if (!event.defaultPrevented) {
|
||||
onDismiss?.(event);
|
||||
}
|
||||
},
|
||||
node,
|
||||
safeZone?.anchor,
|
||||
enabled,
|
||||
);
|
||||
|
||||
const pointerDownOutside = usePointerDownOutside(
|
||||
(event) => {
|
||||
if (!shouldEnablePointerEvents) {
|
||||
return;
|
||||
}
|
||||
focusOutside.ignoreFocusOutsideAfterPointerDown();
|
||||
dismissedWithPointerRef.current = true;
|
||||
|
||||
/**
|
||||
* We call these before checking the safe zone to give consumers a chance to prevent dismissal.
|
||||
* We reset dismissedWithPointerRef on the next tick.
|
||||
* This allows pointerDown to run its effect, without re-running them here right after.
|
||||
*/
|
||||
timeout.start(0, () => {
|
||||
dismissedWithPointerRef.current = false;
|
||||
});
|
||||
|
||||
/**
|
||||
* We call these before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault.
|
||||
*/
|
||||
onPointerDownOutside?.(event);
|
||||
onInteractOutside?.(event);
|
||||
@@ -202,7 +201,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
/**
|
||||
* Add safeZone to prevent closing when interacting with trigger/anchor or its children.
|
||||
*/
|
||||
safeZone && handleOutsidePointerEvent(event);
|
||||
safeZone && handleOutsideEvent(event);
|
||||
|
||||
if (!event.defaultPrevented && onDismiss) {
|
||||
onDismiss(event);
|
||||
@@ -219,7 +218,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
}
|
||||
|
||||
/**
|
||||
* We call these before checking the safe zone to give consumers a chance to prevent dismissal.
|
||||
* We call these before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault based certain cases.
|
||||
*/
|
||||
onPointerUpOutside?.(event);
|
||||
onInteractOutside?.(event);
|
||||
@@ -227,10 +226,10 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
/**
|
||||
* Add safeZone to prevent closing when interacting with trigger/anchor or its children.
|
||||
*/
|
||||
safeZone && handleOutsidePointerEvent(event);
|
||||
safeZone && handleOutsideEvent(event);
|
||||
|
||||
/**
|
||||
* Both `onPointerUpOutside`, `onInteractOutside` and `handleOutsidePointerEvent`
|
||||
* Both `onPointerUpOutside`, `onInteractOutside` and `handleOutsideEvent`
|
||||
* are able to preventDefault the event, thus stopping call for `onDismiss`.
|
||||
*/
|
||||
if (!event.defaultPrevented && onDismiss) {
|
||||
@@ -241,6 +240,30 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
enabled,
|
||||
);
|
||||
|
||||
const focusOutside = useFocusOutside(
|
||||
(event) => {
|
||||
if (dismissedWithPointerRef.current) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* We call these before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault.
|
||||
*/
|
||||
onFocusOutside?.(event);
|
||||
onInteractOutside?.(event);
|
||||
|
||||
/**
|
||||
* Add safeZone to prevent closing when interacting with trigger/anchor or its children.
|
||||
*/
|
||||
safeZone && handleOutsideEvent(event);
|
||||
|
||||
if (!event.defaultPrevented && onDismiss) {
|
||||
onDismiss(event);
|
||||
}
|
||||
},
|
||||
ownerDoc,
|
||||
enabled,
|
||||
);
|
||||
|
||||
useEscapeKeydown(
|
||||
(event) => {
|
||||
/**
|
||||
@@ -253,7 +276,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Give consumers a chance to prevent dismissal.
|
||||
* We call this before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault based certain cases.
|
||||
*/
|
||||
onEscapeKeyDown?.(event);
|
||||
/**
|
||||
@@ -427,12 +450,16 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
|
||||
restProps.onFocusCapture,
|
||||
focusOutside.onFocusCapture,
|
||||
)}
|
||||
onBlurCapture={composeEventHandlers(
|
||||
restProps.onBlurCapture,
|
||||
focusOutside.onBlurCapture,
|
||||
)}
|
||||
onPointerDownCapture={composeEventHandlers(
|
||||
restProps.onPointerDownCapture,
|
||||
() => {
|
||||
pointerDownOutside.onPointerDownCapture();
|
||||
pointerUpOutside.onPointerDownCapture();
|
||||
focusOutside.ignoreFocusOutsideAfterPointerDown();
|
||||
focusOutside.onPointerDownCapture();
|
||||
},
|
||||
)}
|
||||
onPointerUpCapture={composeEventHandlers(
|
||||
|
||||
+1
-1
@@ -18,11 +18,11 @@ function dispatchCustomEvent<
|
||||
detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D>
|
||||
? D
|
||||
: never),
|
||||
target = detail.originalEvent.target,
|
||||
) {
|
||||
if (!handler) {
|
||||
return;
|
||||
}
|
||||
const target = detail.originalEvent.target;
|
||||
const event = new CustomEvent(name, {
|
||||
bubbles: false,
|
||||
cancelable: true,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type FocusEvent as ReactFocusEvent, useEffect, useRef } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEventCallback, useTimeout } from "../../../hooks";
|
||||
import {
|
||||
CUSTOM_EVENTS,
|
||||
@@ -7,123 +7,69 @@ import {
|
||||
} from "./dispatchCustomEvent";
|
||||
|
||||
/**
|
||||
* Tracks focus moving outside the layer's React subtree (including portals) and anchor.
|
||||
* Tracks focus outside a React subtree. Returns props for the subtree root.
|
||||
*/
|
||||
function useFocusOutside(
|
||||
callback: (event: CustomFocusEvent) => void,
|
||||
node: Element | null,
|
||||
anchor: Element | null | undefined,
|
||||
enabled: boolean,
|
||||
export function useFocusOutside(
|
||||
callback?: (event: CustomFocusEvent) => void,
|
||||
ownerDocument: Document = globalThis?.document,
|
||||
enabled: boolean = true,
|
||||
) {
|
||||
const handleFocusOutside = useEventCallback(callback);
|
||||
const insideFocusEventRef = useRef<Event | null>(null);
|
||||
const handleFocusOutside = useEventCallback(callback) as EventListener;
|
||||
const isFocusInsideReactTreeRef = useRef(false);
|
||||
const skipFocusCheckRef = useRef(false);
|
||||
const focusCheck = useTimeout();
|
||||
const pointerTimeout = useTimeout();
|
||||
const timeout = useTimeout();
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !node) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Focus moving between siblings in a shadow root may only reach that root.
|
||||
const roots = new Set<Node>([node.ownerDocument]);
|
||||
for (const element of [node, anchor]) {
|
||||
const view = element?.ownerDocument.defaultView;
|
||||
let root = element?.getRootNode();
|
||||
while (root && !roots.has(root)) {
|
||||
roots.add(root);
|
||||
root =
|
||||
view && root instanceof view.ShadowRoot
|
||||
? root.host.getRootNode()
|
||||
: undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const handleFocusIn = (event: FocusEvent) => {
|
||||
// Read now: the browser clears targets in shadow trees after dispatch.
|
||||
const target = event.target;
|
||||
const currentRoot =
|
||||
(event.currentTarget as Document | ShadowRoot | null) ??
|
||||
node.ownerDocument;
|
||||
if (!target || skipFocusCheckRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* Defer so React's onFocusCapture has also run (native vs. React listener order varies).
|
||||
* Comparing event identity confirms this focusin came from inside the React subtree (e.g. a portal).
|
||||
*/
|
||||
focusCheck.start(0, () => {
|
||||
const activeElement = getDeepActiveElement(currentRoot);
|
||||
if (
|
||||
insideFocusEventRef.current === event ||
|
||||
!node.isConnected ||
|
||||
hasFocusWithin(node) ||
|
||||
hasFocusWithin(anchor) ||
|
||||
/* Ignore fallback to body (e.g. removed target) */
|
||||
!activeElement ||
|
||||
activeElement === node.ownerDocument.body ||
|
||||
/* Focus guards redirect focus */
|
||||
activeElement.hasAttribute("data-aksel-focus-guard")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const handleFocus = (event: FocusEvent) => {
|
||||
if (
|
||||
event.target &&
|
||||
!isFocusInsideReactTreeRef.current &&
|
||||
!skipFocusCheckRef.current
|
||||
) {
|
||||
const eventDetail = { originalEvent: event };
|
||||
|
||||
/**
|
||||
* The `DismisableLayer`-API is based on the ability to stop events from propagating and in the end calling `onDismiss`
|
||||
* if `useFocusOutside`-callback runs `event.preventDefault()`.
|
||||
*
|
||||
* Because of the `focusin`-event not being cancelable,
|
||||
* we need to use a custom event to ensure that the event is cancelable.
|
||||
* https://developer.mozilla.org/en-US/docs/Web/API/Element/focusin_event
|
||||
* > The focusin event is not cancelable.
|
||||
*/
|
||||
dispatchCustomEvent(
|
||||
CUSTOM_EVENTS.FOCUS_OUTSIDE,
|
||||
handleFocusOutside,
|
||||
{ originalEvent: event },
|
||||
target,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
for (const root of roots) {
|
||||
root.addEventListener("focusin", handleFocusIn as EventListener, true);
|
||||
}
|
||||
return () => {
|
||||
for (const root of roots) {
|
||||
root.removeEventListener(
|
||||
"focusin",
|
||||
handleFocusIn as EventListener,
|
||||
true,
|
||||
eventDetail,
|
||||
);
|
||||
}
|
||||
focusCheck.clear();
|
||||
};
|
||||
}, [anchor, enabled, focusCheck, handleFocusOutside, node]);
|
||||
ownerDocument.addEventListener("focusin", handleFocus);
|
||||
return () => {
|
||||
ownerDocument.removeEventListener("focusin", handleFocus);
|
||||
};
|
||||
}, [ownerDocument, handleFocusOutside, enabled]);
|
||||
|
||||
/**
|
||||
* By directly setting isFocusInsideReactTreeRef on focus-events at the root of the "dismissable" element,
|
||||
* we can eliminate the need for DOM traversal to verify if the focused element is within the react tree.
|
||||
*/
|
||||
return {
|
||||
onFocusCapture: (event: ReactFocusEvent) => {
|
||||
insideFocusEventRef.current = event.nativeEvent;
|
||||
onFocusCapture: () => {
|
||||
isFocusInsideReactTreeRef.current = true;
|
||||
},
|
||||
/** Ignores focusin events triggered by an outside pointerdown until the next tick, since pointer handling already owns dismissal. */
|
||||
ignoreFocusOutsideAfterPointerDown: () => {
|
||||
focusCheck.clear();
|
||||
onBlurCapture: () => {
|
||||
isFocusInsideReactTreeRef.current = false;
|
||||
},
|
||||
onPointerDownCapture: () => {
|
||||
skipFocusCheckRef.current = true;
|
||||
pointerTimeout.start(0, () => {
|
||||
timeout.start(0, () => {
|
||||
skipFocusCheckRef.current = false;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Uses the element's own root because document.activeElement points to the shadow host instead of the focused element inside a shadow root. */
|
||||
function hasFocusWithin(element: Element | null | undefined) {
|
||||
if (!element?.isConnected) {
|
||||
return false;
|
||||
}
|
||||
const root = element.getRootNode() as Document | ShadowRoot;
|
||||
return element.contains(root.activeElement);
|
||||
}
|
||||
|
||||
function getDeepActiveElement(root: Document | ShadowRoot) {
|
||||
let activeElement = root.activeElement;
|
||||
while (activeElement?.shadowRoot?.activeElement) {
|
||||
activeElement = activeElement.shadowRoot.activeElement;
|
||||
}
|
||||
return activeElement;
|
||||
}
|
||||
|
||||
export { useFocusOutside };
|
||||
+3
-1
@@ -32,7 +32,9 @@ export function usePointerDownOutside(
|
||||
* The `DismisableLayer`-API is based on the ability to stop events from propagating and in the end calling `onDismiss`
|
||||
* if `usePointerDownOutside` runs `event.preventDefault()`.
|
||||
*
|
||||
* Use the same cancelable event contract as the other outside interactions.
|
||||
* Altrough `pointerdown` is already a cancelable event,
|
||||
* to to make sure the batching of events works corretly with `focusIn` in `useFocusOutside`,
|
||||
* we still use a custom event like in `useFocusOutside`.
|
||||
*/
|
||||
function dispatchPointerEvent() {
|
||||
dispatchCustomEvent(
|
||||
|
||||
+2
-1
@@ -44,7 +44,8 @@ export const Loop: Story = {
|
||||
const middle = canvas.getByLabelText(Field_TWO);
|
||||
const last = canvas.getByText(BUTTON_THREE);
|
||||
|
||||
/* Mount focus lands on the first field in the next frame. Wait so it can't steal focus mid-test */
|
||||
/* Regular focus */
|
||||
first.focus();
|
||||
await waitFor(() => expect(first).toHaveFocus());
|
||||
|
||||
await userEvent.tab();
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# @navikt/ds-tailwind
|
||||
|
||||
## 8.23.1
|
||||
|
||||
## 8.23.0
|
||||
|
||||
## 8.22.1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@navikt/ds-tailwind",
|
||||
"version": "8.23.1",
|
||||
"version": "8.23.0",
|
||||
"description": "Tailwind config based on @navikt/ds-tokens",
|
||||
"author": "Aksel | Nav designsystem team",
|
||||
"keywords": [
|
||||
@@ -28,7 +28,7 @@
|
||||
},
|
||||
"homepage": "https://aksel.nav.no/grunnleggende/kode/tailwind/",
|
||||
"devDependencies": {
|
||||
"@navikt/ds-tokens": "^8.23.1",
|
||||
"@navikt/ds-tokens": "^8.23.0",
|
||||
"@types/node": "^24.10.9",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"tsx": "^4.23.15",
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# @navikt/ds-tokens
|
||||
|
||||
## 8.23.1
|
||||
|
||||
## 8.23.0
|
||||
|
||||
## 8.22.1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@navikt/ds-tokens",
|
||||
"version": "8.23.1",
|
||||
"version": "8.23.0",
|
||||
"description": "Design-tokens for Nav designsystem",
|
||||
"author": "Aksel | Nav designsystem team",
|
||||
"keywords": [
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 8.23.1
|
||||
|
||||
### @navikt/ds-css
|
||||
|
||||
- DataGrid: Change `overflow:hidden` to `min-height:0` and `min-width:0` on root ([#5568](https://github.com/navikt/aksel/pull/5568))
|
||||
|
||||
### @navikt/ds-react
|
||||
|
||||
- DataGrid: Keyboard navigation in table no longer prevents shift+tabbing away from the table ([`7dbf1d5`](https://github.com/navikt/aksel/commit/7dbf1d5382367837b1f43fc76ca57d986218b64d))
|
||||
|
||||
- Button: Preserve keyboard modifiers during native Space activation. ([#5564](https://github.com/navikt/aksel/pull/5564))
|
||||
|
||||
- DataGrid.Table: Temporarily removed `topContent` and `bottomContent` props. ([#5579](https://github.com/navikt/aksel/pull/5579))
|
||||
|
||||
## 8.23.0
|
||||
|
||||
### @navikt/aksel-icons
|
||||
|
||||
@@ -11,11 +11,11 @@
|
||||
"sanity:update": "yarn workspace website update:sanity"
|
||||
},
|
||||
"dependencies": {
|
||||
"@navikt/aksel": "^8.23.1",
|
||||
"@navikt/aksel-icons": "^8.23.1",
|
||||
"@navikt/ds-css": "^8.23.1",
|
||||
"@navikt/ds-react": "^8.23.1",
|
||||
"@navikt/ds-tailwind": "^8.23.1",
|
||||
"@navikt/ds-tokens": "^8.23.1"
|
||||
"@navikt/aksel": "^8.23.0",
|
||||
"@navikt/aksel-icons": "^8.23.0",
|
||||
"@navikt/ds-css": "^8.23.0",
|
||||
"@navikt/ds-react": "^8.23.0",
|
||||
"@navikt/ds-tailwind": "^8.23.0",
|
||||
"@navikt/ds-tokens": "^8.23.0"
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,12 @@
|
||||
"dependencies": {
|
||||
"@portabletext/react": "^8.0.1",
|
||||
"@sanity/client": "7.27.0",
|
||||
"@sanity/code-input": "7.3.16",
|
||||
"@sanity/color-input": "6.1.10",
|
||||
"@sanity/code-input": "7.3.8",
|
||||
"@sanity/color-input": "6.1.8",
|
||||
"@sanity/image-url": "2.1.1",
|
||||
"@sanity/locale-nb-no": "1.1.39",
|
||||
"@sanity/preview-url-secret": "4.1.5",
|
||||
"@sanity/table": "3.1.21",
|
||||
"@sanity/table": "3.1.20",
|
||||
"@sanity/vision": "6.17.0",
|
||||
"date-fns": "^4.0.0",
|
||||
"lodash": "4.18.1",
|
||||
@@ -31,15 +31,15 @@
|
||||
"react-rx": "^5.1.1",
|
||||
"rxjs": "^7.8.2",
|
||||
"sanity": "6.17.0",
|
||||
"sanity-plugin-iframe-pane": "5.0.43",
|
||||
"sanity-plugin-media": "6.6.3",
|
||||
"sanity-plugin-iframe-pane": "5.0.41",
|
||||
"sanity-plugin-media": "6.1.8",
|
||||
"sanity-plugin-references": "1.2.0",
|
||||
"styled-components": "6.6.0",
|
||||
"swr": "^2.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sanity/blueprints": "0.34.1",
|
||||
"@sanity/export": "7.1.1",
|
||||
"@sanity/blueprints": "0.28.0",
|
||||
"@sanity/export": "7.0.3",
|
||||
"@sanity/functions": "1.11.0",
|
||||
"@sanity/schema": "6.17.0",
|
||||
"@types/lodash": "4.17.25",
|
||||
|
||||
@@ -11,7 +11,7 @@ export const locations: DocumentLocationResolver = (params, context) => {
|
||||
const doc$ = context.documentStore.listenQuery(
|
||||
`*[(_type != $type && references($id)) || _id == $id && _type in $articleTypes ]{_type, slug, title, heading, "tema": undertema[]->tema->title}`,
|
||||
{ id: params.id, type: params.type, articleTypes: validTypes },
|
||||
{ perspective: "drafts" },
|
||||
{ perspective: "previewDrafts" },
|
||||
) as Observable<
|
||||
| {
|
||||
_type: string;
|
||||
|
||||
@@ -6,11 +6,4 @@ if (process.env.LOCAL_DATASET_OVERRIDE === "development") {
|
||||
SANITY_DATASET = "development";
|
||||
}
|
||||
|
||||
const DEFAULT_OUTDATED_THRESHOLD = 365;
|
||||
|
||||
export {
|
||||
SANITY_API_VERSION,
|
||||
SANITY_DATASET,
|
||||
SANITY_PROJECT_ID,
|
||||
DEFAULT_OUTDATED_THRESHOLD,
|
||||
};
|
||||
export { SANITY_API_VERSION, SANITY_DATASET, SANITY_PROJECT_ID };
|
||||
@@ -1,4 +1,4 @@
|
||||
import { differenceInDays, format } from "date-fns";
|
||||
import { differenceInDays, differenceInMonths, format } from "date-fns";
|
||||
import { type ComponentType, useState } from "react";
|
||||
import {
|
||||
type ObjectFieldProps,
|
||||
@@ -8,11 +8,8 @@ import {
|
||||
useFormValue,
|
||||
} from "sanity";
|
||||
import { HourglassBottomFilledIcon } from "@navikt/aksel-icons";
|
||||
import { BodyLong, Button, InfoCard } from "@navikt/ds-react";
|
||||
import {
|
||||
DEFAULT_OUTDATED_THRESHOLD,
|
||||
SANITY_API_VERSION,
|
||||
} from "../../sanity.env";
|
||||
import { BodyLong, Box, Button, InfoCard } from "@navikt/ds-react";
|
||||
import { SANITY_API_VERSION } from "../../sanity.env";
|
||||
|
||||
const UpdateInfoInput: ComponentType<ObjectInputProps> = (props) => {
|
||||
const { onChange, readOnly } = props;
|
||||
@@ -48,31 +45,37 @@ const UpdateInfoInput: ComponentType<ObjectInputProps> = (props) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
loading={updating}
|
||||
onClick={handleUpdate}
|
||||
disabled={readOnly}
|
||||
data-color="neutral"
|
||||
>
|
||||
Oppdater godkjenningsdato
|
||||
</Button>
|
||||
<Box marginBlock="space-16 space-0">
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
loading={updating}
|
||||
onClick={handleUpdate}
|
||||
disabled={readOnly}
|
||||
data-color="neutral"
|
||||
>
|
||||
Oppdater godkjenningsdato
|
||||
</Button>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const UpdateInfo: ComponentType<ObjectFieldProps> = (props) => {
|
||||
const articleType = useFormValue(["_type"]);
|
||||
|
||||
const verified = useFormValue(["updateInfo", "lastVerified"]);
|
||||
|
||||
if (typeof verified !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// oxlint-disable-next-line react/purity -- Age relative to now is intended.
|
||||
const diff = differenceInMonths(new Date(), new Date(verified));
|
||||
// oxlint-disable-next-line react/purity -- Age relative to now is intended.
|
||||
const diffInDays = differenceInDays(new Date(), new Date(verified));
|
||||
const outdated = diffInDays >= DEFAULT_OUTDATED_THRESHOLD;
|
||||
const outDated = diff >= (articleType === "aksel_artikkel" ? 12 : 6);
|
||||
|
||||
if (!outdated) {
|
||||
if (!outDated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -88,8 +91,10 @@ const UpdateInfo: ComponentType<ObjectFieldProps> = (props) => {
|
||||
Artikkelen trenger ny godkjenning. Les gjennom og oppdater innholdet,
|
||||
for så å oppdatere godkjenningsdatoen.
|
||||
</BodyLong>
|
||||
<BodyLong size="small" spacing>
|
||||
En artikkel regnes som utdatert etter 12 måneder.
|
||||
<BodyLong size="small">
|
||||
{articleType === "aksel_artikkel"
|
||||
? "En God praksis-artikkel regnes som utdatert etter 12 måneder."
|
||||
: "En Designsystem-artikkel regnes som utdatert etter 6 måneder."}
|
||||
</BodyLong>
|
||||
{props.children}
|
||||
</InfoCard.Content>
|
||||
|
||||
@@ -16,7 +16,7 @@ export const GrunnleggendeArtikkel = defineType({
|
||||
name: "ds_artikkel",
|
||||
type: "document",
|
||||
groups: SanityTabGroups,
|
||||
...artikkelPreview("Grunnleggende"),
|
||||
...artikkelPreview("Grunnleggende", 6),
|
||||
renderMembers: (members) => {
|
||||
return [
|
||||
...members,
|
||||
|
||||
@@ -18,7 +18,7 @@ export const KomponentArtikkel = defineType({
|
||||
name: "komponent_artikkel",
|
||||
type: "document",
|
||||
groups: SanityTabGroups,
|
||||
...artikkelPreview("Komponenter"),
|
||||
...artikkelPreview("Komponenter", 6),
|
||||
renderMembers: (members) => {
|
||||
return [
|
||||
...members,
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import { differenceInDays } from "date-fns";
|
||||
import { differenceInMonths } from "date-fns";
|
||||
import { HourglassBottomFilledIcon } from "@navikt/aksel-icons";
|
||||
import { DEFAULT_OUTDATED_THRESHOLD } from "../../../sanity.env";
|
||||
|
||||
const isAfter = (date: string, threshold: number) =>
|
||||
differenceInDays(new Date(), new Date(date)) >= threshold;
|
||||
differenceInMonths(new Date(), new Date(date)) >= threshold;
|
||||
|
||||
/**
|
||||
* @param _type document type
|
||||
* @param threshold number of days before article is considered outdated
|
||||
* @param threshold number of months before article is considered outdated in **months**
|
||||
*/
|
||||
export const artikkelPreview = (
|
||||
_type: string,
|
||||
threshold: number = DEFAULT_OUTDATED_THRESHOLD,
|
||||
) => {
|
||||
export const artikkelPreview = (_type: string, threshold: number = 12) => {
|
||||
return {
|
||||
preview: {
|
||||
select: {
|
||||
|
||||
@@ -16,7 +16,7 @@ export const TemplatesArtikkel = defineType({
|
||||
name: "templates_artikkel",
|
||||
type: "document",
|
||||
groups: SanityTabGroups,
|
||||
...artikkelPreview("Mønster/Maler"),
|
||||
...artikkelPreview("Mønster/Maler", 6),
|
||||
renderMembers: (members) => {
|
||||
return [
|
||||
...members,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type { StructureBuilder } from "sanity/structure";
|
||||
import { FileXMarkIcon, HouseIcon } from "@navikt/aksel-icons";
|
||||
import { DEFAULT_OUTDATED_THRESHOLD, SANITY_API_VERSION } from "../sanity.env";
|
||||
import { SANITY_API_VERSION } from "../sanity.env";
|
||||
import type { AllArticleDocumentsT } from "../schema/schema.config";
|
||||
|
||||
type ArticleDocumentType = AllArticleDocumentsT;
|
||||
@@ -55,7 +55,7 @@ export function listDraftArticles(
|
||||
export function listOutdatedArticles(
|
||||
S: StructureBuilder,
|
||||
type: ArticleDocumentType,
|
||||
threshold: number = DEFAULT_OUTDATED_THRESHOLD,
|
||||
threshold: number = 365,
|
||||
) {
|
||||
return S.listItem({
|
||||
id: `article_${type}_outdated`,
|
||||
@@ -65,7 +65,7 @@ export function listOutdatedArticles(
|
||||
S.documentTypeList(type)
|
||||
.title("Artikler")
|
||||
.filter(
|
||||
`_type == $type && (dateTime(updateInfo.lastVerified + "T00:00:00Z") < dateTime(now()) - 60*60*24*$threshold)`,
|
||||
`_type == $type && (dateTime(updateInfo.lastVerified + "T00:00:00Z") < dateTime(now()) - 60*60*24*$threshold) && ${IS_PUBLISHED}`,
|
||||
)
|
||||
.apiVersion(SANITY_API_VERSION)
|
||||
.params({ type, threshold })
|
||||
|
||||
@@ -19,7 +19,7 @@ export function grunnleggendeStructure(S: StructureBuilder) {
|
||||
landingssideItem(S, "grunnleggende_landingsside"),
|
||||
S.divider(),
|
||||
listDraftArticles(S, "ds_artikkel"),
|
||||
listOutdatedArticles(S, "ds_artikkel"),
|
||||
listOutdatedArticles(S, "ds_artikkel", 180),
|
||||
|
||||
S.divider(),
|
||||
...categoryPanes(
|
||||
|
||||
@@ -19,7 +19,7 @@ export function komponenterStructure(S: StructureBuilder) {
|
||||
landingssideItem(S, "komponenter_landingsside"),
|
||||
S.divider(),
|
||||
listDraftArticles(S, "komponent_artikkel"),
|
||||
listOutdatedArticles(S, "komponent_artikkel"),
|
||||
listOutdatedArticles(S, "komponent_artikkel", 180),
|
||||
|
||||
S.divider(),
|
||||
...categoryPanes(
|
||||
|
||||
@@ -19,7 +19,7 @@ export function monsterStructure(S: StructureBuilder) {
|
||||
landingssideItem(S, "templates_landingsside"),
|
||||
S.divider(),
|
||||
listDraftArticles(S, "templates_artikkel"),
|
||||
listOutdatedArticles(S, "templates_artikkel"),
|
||||
listOutdatedArticles(S, "templates_artikkel", 180),
|
||||
|
||||
S.divider(),
|
||||
...categoryPanes(
|
||||
|
||||
+4
-5
@@ -1,5 +1,4 @@
|
||||
import { DEFAULT_OUTDATED_THRESHOLD } from "aksel-sanity-studio/env";
|
||||
import { differenceInDays, isSameDay } from "date-fns";
|
||||
import { differenceInMonths, isSameDay } from "date-fns";
|
||||
import type { Metadata } from "next";
|
||||
import { type PortableTextBlock, stegaClean } from "next-sanity";
|
||||
import { draftMode } from "next/headers";
|
||||
@@ -178,11 +177,11 @@ async function CachedArticle({
|
||||
pageData?.updateInfo?.lastVerified ??
|
||||
pageData?.publishedAt ??
|
||||
pageData?._updatedAt;
|
||||
// oxlint-disable-next-line react/purity -- Server Component, rendered once per request.
|
||||
const diffInDays = differenceInDays(new Date(), new Date(verifiedDate));
|
||||
const outdated = diffInDays >= DEFAULT_OUTDATED_THRESHOLD;
|
||||
|
||||
// oxlint-disable-next-line react/purity -- Server Component, rendered once per request.
|
||||
const outdated = differenceInMonths(new Date(), new Date(verifiedDate)) >= 12;
|
||||
const writers = getValidRenderArray(pageData.writers);
|
||||
|
||||
const undertema = getValidRenderArray(pageData.undertema);
|
||||
const relevanteArtikler = getValidRenderArray(pageData.relevante_artikler);
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
"cp:assets:with-playroom": "yarn cp:playroom && yarn cp:assets"
|
||||
},
|
||||
"dependencies": {
|
||||
"@navikt/analytics-types": "0.0.13",
|
||||
"@navikt/analytics-types": "0.0.9",
|
||||
"@navikt/next-logger": "5.0.2",
|
||||
"@navikt/oasis": "4.2.2",
|
||||
"@portabletext/react": "^8.0.1",
|
||||
@@ -73,7 +73,7 @@
|
||||
"@babel/core": "^7.19.0",
|
||||
"@babel/parser": "^7.27.5",
|
||||
"@babel/traverse": "^7.27.4",
|
||||
"@google-cloud/bigquery": "^9.6.1",
|
||||
"@google-cloud/bigquery": "^9.5.0",
|
||||
"@playwright/test": "1.61.1",
|
||||
"@portabletext/block-tools": "^6.0.7",
|
||||
"@portabletext/markdown": "^2.5.1",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Fieldset, Switch, VStack } from "@navikt/ds-react";
|
||||
import { Switch, VStack } from "@navikt/ds-react";
|
||||
import { withDsExample } from "@/web/examples/withDsExample";
|
||||
|
||||
const Example = () => {
|
||||
@@ -8,10 +8,6 @@ const Example = () => {
|
||||
<Switch readOnly checked>
|
||||
Slå på notifikasjoner
|
||||
</Switch>
|
||||
<Fieldset legend="Hvordan ønsker du å bli varslet?" readOnly>
|
||||
<Switch>E-post</Switch>
|
||||
<Switch defaultChecked>SMS</Switch>
|
||||
</Fieldset>
|
||||
</VStack>
|
||||
);
|
||||
};
|
||||
@@ -26,5 +22,5 @@ export const Demo = {
|
||||
|
||||
export const args: ExampleArgsT = {
|
||||
index: 98,
|
||||
desc: "Readonly-attributtet gjør at tilstanden ikke kan endres. Til forskjell fra `disabled` vil brukere fortsatt kunne tabbe til feltet, og verdien vil inkluderes når skjemaet sendes inn. Sett `readOnly` på `Fieldset` for å låse hele gruppen.",
|
||||
desc: "Readonly-attributtet gjør at tilstanden ikke kan endres. Til forskjell fra `disabled` vil brukere fortsatt kunne tabbe til feltet, og verdien vil inkluderes når skjemaet sendes inn.",
|
||||
};
|
||||
@@ -11,9 +11,9 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@navikt/aksel-icons": "^8.23.1",
|
||||
"@navikt/ds-css": "^8.23.1",
|
||||
"@navikt/ds-react": "^8.23.1",
|
||||
"@navikt/aksel-icons": "^8.23.0",
|
||||
"@navikt/ds-css": "^8.23.0",
|
||||
"@navikt/ds-react": "^8.23.0",
|
||||
"fuse.js": "7.4.2",
|
||||
"react": "19.3.1",
|
||||
"react-dom": "19.3.1"
|
||||
@@ -25,7 +25,7 @@
|
||||
"@types/node": "^24.10.9",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@vitejs/plugin-react": "^6.3.0",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"typescript": "6.0.3",
|
||||
"vite": "^8.3.5",
|
||||
"vite-plugin-singlefile": "^2.3.4"
|
||||
|
||||
@@ -19,9 +19,9 @@
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/inspector": "^2.11.0",
|
||||
"@modelcontextprotocol/sdk": "^1.32.0",
|
||||
"@navikt/aksel": "^8.23.1",
|
||||
"@navikt/aksel-icons": "^8.23.1",
|
||||
"@navikt/ds-tokens": "^8.23.1",
|
||||
"@navikt/aksel": "^8.23.0",
|
||||
"@navikt/aksel-icons": "^8.23.0",
|
||||
"@navikt/ds-tokens": "^8.23.0",
|
||||
"@sanity/client": "7.27.0",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/node": "^24.10.9",
|
||||
|
||||
@@ -28,13 +28,6 @@ describe("Resources", () => {
|
||||
// Should NOT have verbose fields like rawValue, jsValue, etc.
|
||||
expect(firstToken).not.toHaveProperty("rawValue");
|
||||
expect(firstToken).not.toHaveProperty("jsValue");
|
||||
|
||||
// Should include dynamic data-color base tokens without duplicating names
|
||||
const names = tokenList.map((t: { name: string }) => t.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
expect(names).toContain("text-default");
|
||||
expect(names).toContain("bg-soft");
|
||||
expect(names).toContain("border-default");
|
||||
});
|
||||
|
||||
test("should have proper metadata", () => {
|
||||
|
||||
@@ -1,33 +1,9 @@
|
||||
import {
|
||||
type TokenDocT,
|
||||
tokens as dsTokens,
|
||||
} from "@navikt/ds-tokens/token_docs";
|
||||
import { tokens } from "@navikt/ds-tokens/token_docs";
|
||||
import type { McpResource } from "../types.js";
|
||||
|
||||
const URI = "aksel-tokens://catalog";
|
||||
const MIME_TYPE = "application/json";
|
||||
|
||||
type ThemedBaseCategory = {
|
||||
category: "backgroundColor" | "textColor" | "borderColor";
|
||||
categoryTitle: "Bakgrunnsfarger" | "Tekstfarger" | "Kantlinjefarger";
|
||||
};
|
||||
|
||||
type ThemedBaseToken = {
|
||||
name: string;
|
||||
value: string;
|
||||
cssValue: string;
|
||||
resolvesTo: string;
|
||||
defaultRole: "accent";
|
||||
comment: string;
|
||||
type: "themed-role";
|
||||
category: ThemedBaseCategory["category"];
|
||||
categoryTitle: ThemedBaseCategory["categoryTitle"];
|
||||
role: "themed-role";
|
||||
modifier: string;
|
||||
};
|
||||
|
||||
type CatalogToken = TokenDocT | ThemedBaseToken;
|
||||
|
||||
type TokenSummary = {
|
||||
name: string;
|
||||
comment?: string;
|
||||
@@ -35,74 +11,6 @@ type TokenSummary = {
|
||||
type: string;
|
||||
};
|
||||
|
||||
const themedBaseCategories: Record<
|
||||
"bg" | "text" | "border",
|
||||
ThemedBaseCategory
|
||||
> = {
|
||||
bg: { category: "backgroundColor", categoryTitle: "Bakgrunnsfarger" },
|
||||
text: { category: "textColor", categoryTitle: "Tekstfarger" },
|
||||
border: { category: "borderColor", categoryTitle: "Kantlinjefarger" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Dynamic CSS-only base tokens emitted per `[data-color="<role>"]` by
|
||||
* `@navikt/ds-tokens` (`semantic-themed-base.tokens.ts`), which are not
|
||||
* included in `@navikt/ds-tokens/token_docs` or JS/SCSS/LESS exports.
|
||||
*/
|
||||
const themedBaseSpecs: ReadonlyArray<{
|
||||
prefix: "bg" | "text" | "border";
|
||||
modifier: string;
|
||||
resolvesSuffix?: string;
|
||||
}> = [
|
||||
{ prefix: "bg", modifier: "soft" },
|
||||
{ prefix: "bg", modifier: "softA" },
|
||||
{ prefix: "bg", modifier: "moderate" },
|
||||
{ prefix: "bg", modifier: "moderateA" },
|
||||
{ prefix: "bg", modifier: "moderate-hover" },
|
||||
{ prefix: "bg", modifier: "moderate-hoverA" },
|
||||
{ prefix: "bg", modifier: "moderate-pressed" },
|
||||
{ prefix: "bg", modifier: "moderate-pressedA" },
|
||||
{ prefix: "bg", modifier: "strong" },
|
||||
{ prefix: "bg", modifier: "strong-hover" },
|
||||
{ prefix: "bg", modifier: "strong-pressed" },
|
||||
{ prefix: "text", modifier: "default", resolvesSuffix: "" },
|
||||
{ prefix: "text", modifier: "subtle" },
|
||||
{ prefix: "text", modifier: "decoration" },
|
||||
{ prefix: "text", modifier: "contrast" },
|
||||
{ prefix: "border", modifier: "default", resolvesSuffix: "" },
|
||||
{ prefix: "border", modifier: "subtle" },
|
||||
{ prefix: "border", modifier: "subtleA" },
|
||||
{ prefix: "border", modifier: "strong" },
|
||||
];
|
||||
|
||||
const themedBaseTokens: ThemedBaseToken[] = themedBaseSpecs.map(
|
||||
({ prefix, modifier, resolvesSuffix }) => {
|
||||
const name = `${prefix}-${modifier}`;
|
||||
const suffix =
|
||||
resolvesSuffix === undefined ? `-${modifier}` : resolvesSuffix;
|
||||
const resolvesTo = `var(--ax-${prefix}-<color>${suffix})`;
|
||||
const exampleNeutral = `${prefix}-neutral${suffix}`;
|
||||
const exampleAccent = `${prefix}-accent${suffix}`;
|
||||
const { category, categoryTitle } = themedBaseCategories[prefix];
|
||||
|
||||
return {
|
||||
name,
|
||||
value: `var(--ax-${name})`,
|
||||
cssValue: `var(--ax-${name})`,
|
||||
resolvesTo,
|
||||
defaultRole: "accent",
|
||||
comment: `Dynamic CSS-only base token scoped by data-color (defaults to 'accent' on :root). Resolves to ${resolvesTo}. Not exported in JS/SCSS/LESS; use explicit role tokens (e.g. ${exampleNeutral}, ${exampleAccent}) for static usage.`,
|
||||
type: "themed-role",
|
||||
category,
|
||||
categoryTitle,
|
||||
role: "themed-role",
|
||||
modifier,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const tokens: CatalogToken[] = [...dsTokens, ...themedBaseTokens];
|
||||
|
||||
const tokenSummary: TokenSummary[] = tokens.map((token) => ({
|
||||
name: token.name,
|
||||
comment: token.comment,
|
||||
@@ -130,4 +38,4 @@ const tokensCatalogResource: McpResource = {
|
||||
};
|
||||
|
||||
export { tokensCatalogResource, tokens, tokenSummary };
|
||||
export type { CatalogToken, ThemedBaseToken, TokenSummary };
|
||||
export type { TokenSummary };
|
||||
@@ -162,45 +162,6 @@ describe("Tools", () => {
|
||||
expect(token).toHaveProperty("jsValue");
|
||||
});
|
||||
|
||||
test("should fetch details for dynamic data-color base tokens without JS/SCSS/LESS accessors", async () => {
|
||||
const textDefault = JSON.parse(
|
||||
await getTokenDetailsTool.callback({ tokenName: "text-default" }),
|
||||
);
|
||||
expect(textDefault).toMatchObject({
|
||||
name: "text-default",
|
||||
cssValue: "var(--ax-text-default)",
|
||||
resolvesTo: "var(--ax-text-<color>)",
|
||||
defaultRole: "accent",
|
||||
type: "themed-role",
|
||||
category: "textColor",
|
||||
});
|
||||
expect(textDefault).not.toHaveProperty("jsValue");
|
||||
expect(textDefault).not.toHaveProperty("scssValue");
|
||||
expect(textDefault).not.toHaveProperty("lessValue");
|
||||
|
||||
const bgSoft = JSON.parse(
|
||||
await getTokenDetailsTool.callback({ tokenName: "bg-soft" }),
|
||||
);
|
||||
expect(bgSoft).toMatchObject({
|
||||
name: "bg-soft",
|
||||
cssValue: "var(--ax-bg-soft)",
|
||||
resolvesTo: "var(--ax-bg-<color>-soft)",
|
||||
type: "themed-role",
|
||||
category: "backgroundColor",
|
||||
});
|
||||
|
||||
const borderDefault = JSON.parse(
|
||||
await getTokenDetailsTool.callback({ tokenName: "border-default" }),
|
||||
);
|
||||
expect(borderDefault).toMatchObject({
|
||||
name: "border-default",
|
||||
cssValue: "var(--ax-border-default)",
|
||||
resolvesTo: "var(--ax-border-<color>)",
|
||||
type: "themed-role",
|
||||
category: "borderColor",
|
||||
});
|
||||
});
|
||||
|
||||
test("should return error with suggestions for similar tokens", async () => {
|
||||
const result = await getTokenDetailsTool.callback({
|
||||
tokenName: "shadow",
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"sync-imports": "tsx --tsconfig ./scripts/tsconfig.json ./scripts/generate-imports.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.29.14",
|
||||
"@babel/preset-env": "^7.29.0",
|
||||
"@babel/preset-react": "^7.28.5",
|
||||
"@babel/preset-typescript": "^7.28.5",
|
||||
"@types/node": "^24.10.9",
|
||||
@@ -20,9 +20,9 @@
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@navikt/aksel-icons": "^8.23.1",
|
||||
"@navikt/ds-css": "^8.23.1",
|
||||
"@navikt/ds-react": "^8.23.1",
|
||||
"@navikt/aksel-icons": "^8.23.0",
|
||||
"@navikt/ds-css": "^8.23.0",
|
||||
"@navikt/ds-react": "^8.23.0",
|
||||
"react": "19.3.1"
|
||||
}
|
||||
}
|
||||
+8
-8
@@ -76,12 +76,12 @@
|
||||
"@actions/core": "^3.0.1",
|
||||
"@changesets/cli": "2.31.1",
|
||||
"@github-ui/storybook-addon-performance-panel": "^1.3.1",
|
||||
"@storybook/addon-a11y": "^10.6.7",
|
||||
"@storybook/addon-docs": "^10.6.7",
|
||||
"@storybook/addon-themes": "^10.6.7",
|
||||
"@storybook/addon-vitest": "^10.6.7",
|
||||
"@storybook/nextjs-vite": "^10.6.7",
|
||||
"@storybook/react-vite": "^10.6.7",
|
||||
"@storybook/addon-a11y": "^10.6.3",
|
||||
"@storybook/addon-docs": "^10.6.3",
|
||||
"@storybook/addon-themes": "^10.6.3",
|
||||
"@storybook/addon-vitest": "^10.6.3",
|
||||
"@storybook/nextjs-vite": "^10.6.3",
|
||||
"@storybook/react-vite": "^10.6.3",
|
||||
"@svitejs/changesets-changelog-github-compact": "^1.1.0",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
"@types/node": "^24.10.9",
|
||||
@@ -94,7 +94,7 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-plugin-aksel-local": "*",
|
||||
"eslint-plugin-storybook": "^10.6.7",
|
||||
"eslint-plugin-storybook": "^10.6.3",
|
||||
"eslint-plugin-testing-library": "^7.16.0",
|
||||
"fast-glob": "3.3.3",
|
||||
"husky": "^9.1.7",
|
||||
@@ -105,7 +105,7 @@
|
||||
"react": "19.3.1",
|
||||
"react-docgen-typescript": "2.4.0",
|
||||
"react-dom": "19.3.1",
|
||||
"storybook": "^10.6.7",
|
||||
"storybook": "^10.6.3",
|
||||
"stylelint": "^17.15.0",
|
||||
"stylelint-config-standard": "^40.0.0",
|
||||
"stylelint-declaration-block-no-ignored-properties": "^3.0.0",
|
||||
|
||||
+4
-24
@@ -2,14 +2,6 @@ import { storybookTest } from "@storybook/addon-vitest/vitest-plugin";
|
||||
import { playwright } from "@vitest/browser-playwright";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
/*
|
||||
* Firefox and WebKit can't launch inside the cplt sandbox used by Copilot CLI on macOS,
|
||||
* so agents only run Chromium. CI runs all three. Filter with `--browser.name=<browser>`.
|
||||
*/
|
||||
const browsers = process.env.COPILOT_CLI
|
||||
? (["chromium"] as const)
|
||||
: (["chromium", "firefox", "webkit"] as const);
|
||||
|
||||
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
|
||||
export default defineConfig({
|
||||
test: {
|
||||
@@ -31,22 +23,10 @@ export default defineConfig({
|
||||
enabled: true,
|
||||
headless: true,
|
||||
provider: playwright(),
|
||||
instances: browsers.map((browser) => {
|
||||
return {
|
||||
browser,
|
||||
/*
|
||||
* Parallel WebKit pages interfere with each other's focus, so focus
|
||||
* assertions (e.g. Dialog mount focus) fail at random. Run WebKit files serially.
|
||||
*/
|
||||
fileParallelism: browser !== "webkit",
|
||||
provider:
|
||||
browser === "chromium"
|
||||
? playwright({
|
||||
launchOptions: { args: ["--font-render-hinting=none"] },
|
||||
})
|
||||
: undefined,
|
||||
};
|
||||
}),
|
||||
/* Firefox can't start inside the cplt sandbox used by Copilot CLI */
|
||||
instances: [
|
||||
{ browser: process.env.COPILOT_CLI ? "chromium" : "firefox" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user