From 9799b057bd78e8bca05ca0b074fb5270a2a3973b Mon Sep 17 00:00:00 2001 From: Kirill Kolesnikov Date: Tue, 17 Nov 2026 12:53:02 +0700 Subject: [PATCH 1/7] Finalize CodeMonster UI visual review candidate --- .githooks/pre-push | 7 +- .github/workflows/ci.yml | 22 +- .markdownlint-cli2.jsonc | 11 +- .prettierignore | 3 + .vscode/tasks.json | 25 +- README.md | 28 +- contracts/date-picker/contract.md | 3 + contracts/icon-button/cases/default.case.json | 4 +- contracts/icon-button/cases/default.html | 2 +- .../icon-button/cases/disabled.case.json | 4 +- contracts/icon-button/cases/disabled.html | 2 +- contracts/icon-button/cases/warn.case.json | 4 +- contracts/icon-button/cases/warn.html | 2 +- contracts/tooltip/contract.md | 6 + docs/codemonster-ui-2.0-release-notes.md | 5 +- docs/components/data-tables.md | 4 + docs/components/overlays.md | 3 + docs/recipes/code-block.md | 2 +- docs/recipes/playground.md | 2 +- docs/release-checklist.md | 7 +- docs/vanilla.md | 11 +- .../visual-excellence-design-review.md | 199 +++ .../visual-excellence-initiative.md | 202 +++ examples/shared/application-example-data.mts | 69 - examples/shared/application-examples.css | 328 ---- examples/shared/showcase-colors.css | 71 +- examples/shared/showcase-colors.mts | 7 +- .../shared/showcase-component-reference.css | 290 +--- .../shared/showcase-component-reference.d.ts | 1 + .../shared/showcase-component-reference.js | 76 +- .../shared/showcase-component-reference.mts | 158 +- examples/shared/showcase-core-matrix.mts | 13 +- examples/shared/showcase-core-recipes.html | 70 +- examples/shared/showcase-groups.json | 10 - examples/shared/showcase-guide-copy.d.ts | 1 - examples/shared/showcase-guide-copy.js | 17 - examples/shared/showcase-guide-links.mts | 5 - examples/shared/showcase-guides.css | 269 ---- examples/shared/showcase-icon-gallery.css | 200 +-- examples/shared/showcase-layout-data.mts | 87 +- examples/shared/showcase-layout-recipes.js | 75 +- examples/shared/showcase-layout-samples.mts | 99 +- examples/shared/showcase-navigation.d.ts | 2 +- examples/shared/showcase-navigation.js | 226 +-- examples/shared/showcase-navigation.mts | 51 +- examples/shared/showcase-pages.json | 24 +- examples/shared/showcase-reference.js | 5 +- examples/shared/showcase-reference.mts | 133 +- examples/shared/showcase-shell.css | 1313 +++-------------- examples/shared/showcase-theme-samples.html | 4 +- examples/shared/showcase-typography.css | 225 +-- examples/shared/showcase-typography.html | 255 +--- examples/ui-showcase/README.md | 57 +- examples/ui-showcase/case.html | 2 +- examples/ui-showcase/guides-plugin.d.mts | 3 - examples/ui-showcase/guides-plugin.mjs | 60 - examples/ui-showcase/layout-example.html | 13 + examples/ui-showcase/package.json | 10 +- .../ui-showcase/showcase-pages-plugin.d.mts | 3 + .../ui-showcase/showcase-pages-plugin.mjs | 29 + examples/ui-showcase/src/App.vue | 93 +- .../ui-showcase/src/ApplicationExamples.vue | 301 ---- .../ui-showcase/src/CodeBlockShowcase.vue | 262 ---- examples/ui-showcase/src/ColorsShowcase.vue | 72 +- .../ui-showcase/src/ComponentReference.vue | 3 - examples/ui-showcase/src/CoreFeedback.vue | 12 +- examples/ui-showcase/src/CoreMatrix.vue | 2 +- examples/ui-showcase/src/CoreNavigation.vue | 27 +- examples/ui-showcase/src/CoreSurfaces.vue | 13 +- examples/ui-showcase/src/CoreTheme.vue | 22 +- .../ui-showcase/src/DocumentationShowcase.vue | 48 - examples/ui-showcase/src/IconsShowcase.vue | 81 +- examples/ui-showcase/src/LayoutExample.vue | 331 +++++ .../ui-showcase/src/LayoutPageRecipes.vue | 87 -- examples/ui-showcase/src/LayoutPreview.vue | 55 + examples/ui-showcase/src/LayoutPrimitives.vue | 18 +- examples/ui-showcase/src/LayoutShowcase.vue | 377 +---- .../ui-showcase/src/PlaygroundShowcase.vue | 323 ---- examples/ui-showcase/src/case.ts | 22 +- examples/ui-showcase/src/layout-example.ts | 15 + .../src/playground/ViteLikeDemoPreview.vue | 73 - .../src/playground/custom-resolver-smoke.ts | 48 - .../src/playground/virtual-modules.d.ts | 6 - .../src/playground/vue-runtime-smoke.ts | 48 - examples/ui-showcase/src/scrollable-table.ts | 11 + examples/ui-showcase/src/showcase.css | 581 +------- examples/ui-showcase/vite.config.ts | 37 +- examples/ui-showcase/workspace-development.ts | 80 + examples/vanilla/application-examples.js | 163 -- examples/vanilla/application-examples.mjs | 204 --- examples/vanilla/layout-example.js | 113 ++ examples/vanilla/package.json | 20 + examples/vanilla/showcase-demo.js | 23 +- examples/vanilla/showcase-layouts.js | 119 +- examples/vanilla/showcase.css | 10 +- examples/vanilla/showcase.js | 7 +- examples/vanilla/vite.config.mjs | 96 ++ package-lock.json | 118 +- package.json | 28 +- .../advanced-input-components.test.mjs | 2 +- packages/css/__tests__/card.test.mjs | 5 +- .../__tests__/data-table-components.test.mjs | 12 +- .../__tests__/field-visual-parity.test.mjs | 2 +- packages/css/__tests__/foundation.test.mjs | 2 +- .../native-picker-visual-parity.test.mjs | 28 +- packages/css/src/components/accordion.css | 13 +- packages/css/src/components/admin-shell.css | 1 + packages/css/src/components/alert.css | 10 +- packages/css/src/components/breadcrumbs.css | 2 +- packages/css/src/components/button.css | 4 +- packages/css/src/components/card.css | 3 +- packages/css/src/components/checkbox.css | 2 +- .../css/src/components/command-palette.css | 4 +- packages/css/src/components/data-table.css | 67 +- packages/css/src/components/date-picker.css | 134 +- packages/css/src/components/icon-button.css | 4 +- packages/css/src/components/input.css | 62 +- packages/css/src/components/link.css | 4 +- packages/css/src/components/menu-bar.css | 12 +- packages/css/src/components/menu.css | 10 +- packages/css/src/components/nav-menu.css | 15 +- packages/css/src/components/panel.css | 3 +- packages/css/src/components/popover.css | 2 +- packages/css/src/components/progress-bar.css | 54 +- packages/css/src/components/radio.css | 26 +- packages/css/src/components/select.css | 91 +- packages/css/src/components/stepper.css | 2 +- packages/css/src/components/switch.css | 2 +- packages/css/src/components/table.css | 13 +- packages/css/src/components/tabs.css | 6 +- packages/css/src/components/textarea.css | 2 +- packages/css/src/components/theme-switch.css | 23 +- packages/css/src/components/tooltip.css | 59 +- packages/css/src/foundation/preferences.css | 7 +- .../src/primitives/anchored-disclosure.css | 2 +- packages/css/src/primitives/modal-surface.css | 8 +- packages/icons/package.json | 2 +- packages/layouts/package.json | 2 +- packages/runtime/package.json | 2 +- packages/runtime/src/date-picker.ts | 1 + packages/runtime/src/tooltip.ts | 45 +- packages/tokens/package.json | 2 +- packages/tokens/src/semantic-colors.ts | 12 +- .../__tests__/portable-expansion-ssr.test.mjs | 4 +- .../components/date-picker/CmDatePicker.vue | 1 + .../vue/src/components/tooltip/CmTooltip.vue | 44 +- scripts/build/build-vanilla-showcase.mjs | 160 +- scripts/build/build-vanilla.mjs | 13 +- .../render-showcase-component-reference.mjs | 3 +- scripts/build/render-showcase-layout.mjs | 90 +- scripts/build/showcase-documentation.mjs | 236 --- scripts/build/showcase-search-index.mjs | 42 - .../check-code-monster-ui-packed-consumer.mjs | 2 +- scripts/ci/css-token-references.test.mjs | 32 +- scripts/ci/test-without-dist.sh | 27 +- .../contracts/component-selectors.test.mjs | 5 +- scripts/visual/check-date-picker-reflow.mjs | 222 +++ .../check-display-navigation-states.mjs | 106 ++ scripts/visual/check-form-visual-states.mjs | 248 ++++ scripts/visual/check-showcase-ux.mjs | 334 +++-- scripts/visual/check-tooltip-position.mjs | 151 ++ scripts/visual/compare-showcase.mjs | 18 +- scripts/visual/compare-showcase.test.mjs | 32 +- scripts/visual/cross-platform-fixture/main.ts | 4 + scripts/visual/serve-cross-platform-cases.mjs | 6 + 165 files changed, 3872 insertions(+), 7440 deletions(-) create mode 100644 docs/verification/visual-excellence-design-review.md create mode 100644 docs/verification/visual-excellence-initiative.md delete mode 100644 examples/shared/application-example-data.mts delete mode 100644 examples/shared/application-examples.css delete mode 100644 examples/shared/showcase-guide-copy.d.ts delete mode 100644 examples/shared/showcase-guide-copy.js delete mode 100644 examples/shared/showcase-guide-links.mts delete mode 100644 examples/shared/showcase-guides.css delete mode 100644 examples/ui-showcase/guides-plugin.d.mts delete mode 100644 examples/ui-showcase/guides-plugin.mjs create mode 100644 examples/ui-showcase/layout-example.html create mode 100644 examples/ui-showcase/showcase-pages-plugin.d.mts create mode 100644 examples/ui-showcase/showcase-pages-plugin.mjs delete mode 100644 examples/ui-showcase/src/ApplicationExamples.vue delete mode 100644 examples/ui-showcase/src/CodeBlockShowcase.vue delete mode 100644 examples/ui-showcase/src/DocumentationShowcase.vue create mode 100644 examples/ui-showcase/src/LayoutExample.vue delete mode 100644 examples/ui-showcase/src/LayoutPageRecipes.vue create mode 100644 examples/ui-showcase/src/LayoutPreview.vue delete mode 100644 examples/ui-showcase/src/PlaygroundShowcase.vue create mode 100644 examples/ui-showcase/src/layout-example.ts delete mode 100644 examples/ui-showcase/src/playground/ViteLikeDemoPreview.vue delete mode 100644 examples/ui-showcase/src/playground/custom-resolver-smoke.ts delete mode 100644 examples/ui-showcase/src/playground/virtual-modules.d.ts delete mode 100644 examples/ui-showcase/src/playground/vue-runtime-smoke.ts create mode 100644 examples/ui-showcase/src/scrollable-table.ts create mode 100644 examples/ui-showcase/workspace-development.ts delete mode 100644 examples/vanilla/application-examples.js delete mode 100644 examples/vanilla/application-examples.mjs create mode 100644 examples/vanilla/layout-example.js create mode 100644 examples/vanilla/package.json create mode 100644 examples/vanilla/vite.config.mjs delete mode 100644 scripts/build/showcase-documentation.mjs delete mode 100644 scripts/build/showcase-search-index.mjs create mode 100644 scripts/visual/check-date-picker-reflow.mjs create mode 100644 scripts/visual/check-display-navigation-states.mjs create mode 100644 scripts/visual/check-form-visual-states.mjs create mode 100644 scripts/visual/check-tooltip-position.mjs diff --git a/.githooks/pre-push b/.githooks/pre-push index c5d59aec..60a6a5de 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -4,8 +4,11 @@ set -e echo "Checking clean dependency installation..." npm run check:clean-install +echo "Building workspace packages..." +npm run build + echo "Running workspace typecheck..." -npm run typecheck --workspaces --if-present +npm run typecheck echo "Running workspace tests..." -npm run test:ci-like +npm test --workspaces --if-present --include-workspace-root=false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b093902..13823ae4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,7 +87,7 @@ jobs: run: npm run build - name: Check repository contracts - run: npm run check:repository-contracts + run: npm run check:docs - name: Check CodeMonster UI contracts, accessibility, and visual fixtures run: npm run test:ui @@ -114,12 +114,7 @@ jobs: - name: Install dependencies run: npm ci - # The suite hides dist itself; the build is still needed for its other output, such as - # generated CSS that some workspaces' own tests read back. - - name: Build packages - run: npm run build - - - name: Run workspace tests without build output + - name: Run workspace tests from a clean build run: npm run test:ci-like packaging: @@ -259,11 +254,14 @@ jobs: done npm run visual:cross-platform:capture -- --origin=http://127.0.0.1:5176 --output="${CROSS_PLATFORM_CAPTURE}" --label=ci-actual-adapters - node scripts/visual/compare-showcase.mjs --baseline=visual-baselines/vueforge-cross-platform --current="${CROSS_PLATFORM_CAPTURE}/vue" --diff="${CROSS_PLATFORM_VUE_DIFF}" --threshold=4 - node scripts/visual/compare-showcase.mjs --baseline=visual-baselines/vueforge-cross-platform --current="${CROSS_PLATFORM_CAPTURE}/vanilla" --diff="${CROSS_PLATFORM_VANILLA_DIFF}" --threshold=4 - - CHROME_PATH="${chrome_for_testing_path}" CM_PARITY_REPORT="${RUNNER_TEMP}/codemonster-pair-visual.json" node scripts/visual/check-vanilla-parity.mjs - CHROME_PATH="${chrome_for_testing_path}" CM_PARITY_REPORT="${RUNNER_TEMP}/codemonster-pair-behavior.json" CM_PARITY_BEHAVIOR=1 node scripts/visual/check-vanilla-parity.mjs + # Keep the gate strict while collecting both adapters' results and behavior evidence. + result=0 + node scripts/visual/compare-showcase.mjs --baseline=visual-baselines/vueforge-cross-platform --current="${CROSS_PLATFORM_CAPTURE}/vue" --diff="${CROSS_PLATFORM_VUE_DIFF}" --threshold=4 || result=1 + node scripts/visual/compare-showcase.mjs --baseline=visual-baselines/vueforge-cross-platform --current="${CROSS_PLATFORM_CAPTURE}/vanilla" --diff="${CROSS_PLATFORM_VANILLA_DIFF}" --threshold=4 || result=1 + + CHROME_PATH="${chrome_for_testing_path}" CM_PARITY_REPORT="${RUNNER_TEMP}/codemonster-pair-visual.json" node scripts/visual/check-vanilla-parity.mjs || result=1 + CHROME_PATH="${chrome_for_testing_path}" CM_PARITY_REPORT="${RUNNER_TEMP}/codemonster-pair-behavior.json" CM_PARITY_BEHAVIOR=1 node scripts/visual/check-vanilla-parity.mjs || result=1 + exit "$result" - name: Upload cross-platform visual differences if: failure() diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc index c3152d47..3343ed82 100644 --- a/.markdownlint-cli2.jsonc +++ b/.markdownlint-cli2.jsonc @@ -5,13 +5,8 @@ "MD012": false, "MD025": false, "MD024": { - "siblings_only": true - } + "siblings_only": true, + }, }, - "ignores": [ - "**/node_modules/**", - "**/dist/**", - "**/coverage/**", - "**/LICENSE" - ] + "ignores": ["artifacts/**", "**/node_modules/**", "**/dist/**", "**/coverage/**", "**/LICENSE"], } diff --git a/.prettierignore b/.prettierignore index ed96f99d..8a1843d8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -5,6 +5,9 @@ **/showcase-dist package-lock.json +# Machine-local settings +**/.claude/settings.local.json + # Icon geometry is generated by packages/icons/scripts/generate-icons.mjs and committed, because the # Razor adapter reads it without running Node. Unlike .generated, these are tracked artifacts: their # shape is the generator's business, not a formatter's. diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c524ace5..74d2cc56 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,22 +1,10 @@ { "version": "2.0.0", "tasks": [ - { - "label": "monorepo:typecheck:watch", - "type": "shell", - "command": "npm run typecheck --workspaces --if-present -- --watch --preserveWatchOutput", - "isBackground": true, - "problemMatcher": "$tsc-watch", - "presentation": { - "reveal": "always", - "panel": "shared", - "clear": false - } - }, { "label": "monorepo:lint:once", "type": "shell", - "command": "npm run lint --workspaces --if-present", + "command": "npm run lint", "isBackground": false, "problemMatcher": "$eslint-stylish", "presentation": { @@ -90,19 +78,10 @@ "dependsOn": ["monorepo:lint:once", "monorepo:styles-html:once", "monorepo:md-data:once"], "problemMatcher": [] }, - { - "label": "monorepo:diagnostics:watch", - "dependsOrder": "parallel", - "dependsOn": ["monorepo:typecheck:watch", "monorepo:quality:once"], - "runOptions": { - "runOn": "folderOpen" - }, - "problemMatcher": [] - }, { "label": "monorepo:check:once", "type": "shell", - "command": "npm run lint:all && npm run typecheck --workspaces --if-present", + "command": "npm run build && npm run lint:all && npm run typecheck", "problemMatcher": "$tsc", "presentation": { "reveal": "always", diff --git a/README.md b/README.md index ecb6fad9..0d46db30 100644 --- a/README.md +++ b/README.md @@ -17,12 +17,28 @@ See the [CodeMonster UI 1.1 release notes](./docs/codemonster-ui-1.1-release-not ## Preview locally -Run `npm ci` from the repository root once. Run `npm run preview` to build and open the Vue -showcase, or `npm run preview:vanilla` to build and open the full Vanilla HTML showcase. Both -commands are available under the root `package.json` in the VS Code NPM Scripts panel. - -Use `npm run dev` for the Vue showcase with hot reload. See the -[Vanilla guide](./docs/vanilla.md) for the static assets and template integration. +The Vue and Vanilla showcases are development tools for trying components, states, and layouts. +Both open on the **Visual matrix** for reviewing variants by category. + +Run `npm ci` from the repository root once. Use the following root commands in the terminal or +under the root `package.json` in VS Code's NPM Scripts panel. + +| Task | Vue showcase | Vanilla showcase | +| --- | --- | --- | +| Develop with browser updates | `npm run dev` · [5177](http://127.0.0.1:5177) | `npm run dev:vanilla` · [5178](http://127.0.0.1:5178) | +| Build the local showcase | `npm run build:showcase` | `npm run build:vanilla` | +| Open the existing build | `npm run preview` · [4173](http://127.0.0.1:4173) | `npm run preview:vanilla` · [4174](http://127.0.0.1:4174) | + +The NPM Scripts panel also lists `dev`, `build`, and `preview` under `examples/ui-showcase/package.json` +for Vue and `examples/vanilla/package.json` for Vanilla. + +Run the build before the first preview and whenever you want to refresh the previewed artifact. +`npm run build` builds the seven npm packages. Use `npm test` for package and UI contract tests, +`npm run check` for documentation and package checks, and `npm run verify` for release checks. +After the first package build, use `-w` to focus a command on one workspace, for example +`npm test -w @codemonster-ru/ui-vue`. +The [showcase README](./examples/ui-showcase/README.md) explains which files to edit and serve; +the [Vanilla guide](./docs/vanilla.md) covers static assets and template integration. ## VueForge diff --git a/contracts/date-picker/contract.md b/contracts/date-picker/contract.md index ef9e9919..3dd1a9ca 100644 --- a/contracts/date-picker/contract.md +++ b/contracts/date-picker/contract.md @@ -16,6 +16,9 @@ Page Down change month. Movement respects the date bounds. Escape closes the cal returns focus to the trigger. An outside click or focus move closes the calendar without moving focus back. +If the available width cannot fit its localized weekday and date columns, the grid can scroll +horizontally within the calendar. Keyboard navigation scrolls the focused date into view. + The calendar prefers `bottom-start` placement and can flip above the trigger near an edge. Choose `bottom-end` to align its trailing edge. Vue `teleportTo` accepts a selector or element and `disableTeleport` keeps the calendar inline. Vanilla accepts diff --git a/contracts/icon-button/cases/default.case.json b/contracts/icon-button/cases/default.case.json index 26926113..739a90f7 100644 --- a/contracts/icon-button/cases/default.case.json +++ b/contracts/icon-button/cases/default.case.json @@ -3,5 +3,7 @@ "id": "icon-button-default", "description": "Ghost icon button with the default medium size and native button type.", "props": { "label": "Search" }, - "slots": { "default": "" } + "slots": { + "default": "" + } } diff --git a/contracts/icon-button/cases/default.html b/contracts/icon-button/cases/default.html index 22ae7324..8200b3a7 100644 --- a/contracts/icon-button/cases/default.html +++ b/contracts/icon-button/cases/default.html @@ -1,3 +1,3 @@ diff --git a/contracts/icon-button/cases/disabled.case.json b/contracts/icon-button/cases/disabled.case.json index d5d6f3e6..d9fb599c 100644 --- a/contracts/icon-button/cases/disabled.case.json +++ b/contracts/icon-button/cases/disabled.case.json @@ -3,5 +3,7 @@ "id": "icon-button-disabled", "description": "Disabled primary small icon button.", "props": { "label": "Delete", "variant": "primary", "size": "sm", "disabled": true }, - "slots": { "default": "" } + "slots": { + "default": "" + } } diff --git a/contracts/icon-button/cases/disabled.html b/contracts/icon-button/cases/disabled.html index 253646b5..88af7bed 100644 --- a/contracts/icon-button/cases/disabled.html +++ b/contracts/icon-button/cases/disabled.html @@ -1,3 +1,3 @@ diff --git a/contracts/icon-button/cases/warn.case.json b/contracts/icon-button/cases/warn.case.json index c291a1f2..5fb7949b 100644 --- a/contracts/icon-button/cases/warn.case.json +++ b/contracts/icon-button/cases/warn.case.json @@ -3,5 +3,7 @@ "id": "icon-button-warn", "description": "Warning-toned icon action with the default medium size.", "props": { "label": "Flag item for review", "variant": "warn" }, - "slots": { "default": "" } + "slots": { + "default": "" + } } diff --git a/contracts/icon-button/cases/warn.html b/contracts/icon-button/cases/warn.html index e93dea74..35871d0d 100644 --- a/contracts/icon-button/cases/warn.html +++ b/contracts/icon-button/cases/warn.html @@ -1,3 +1,3 @@ diff --git a/contracts/tooltip/contract.md b/contracts/tooltip/contract.md index 1fe151db..92080fe6 100644 --- a/contracts/tooltip/contract.md +++ b/contracts/tooltip/contract.md @@ -22,6 +22,12 @@ focused or hovered without moving focus. The panel remains in the DOM and `hidde whether it is visible. `defaultVisible` sets only the initial render state. +Once enhanced, an inline tooltip moves in the viewport and flips to the opposite side when +needed. The panel remains inside its authored container and can still be clipped by an ancestor +with `overflow: hidden`, scrolling overflow, or paint containment. To escape such an ancestor, +choose a portal target outside the clipping container. Before enhancement the Tooltip follows +its CSS placement. + The visible tooltip can be positioned in another container. Use `teleportTo` with a selector or element in Vue, or `data-cm-tooltip-teleport-to` with a selector in Vanilla. A `body` target inside an open dialog keeps the tooltip in that dialog. Vue `disableTeleport`, `null`, or diff --git a/docs/codemonster-ui-2.0-release-notes.md b/docs/codemonster-ui-2.0-release-notes.md index c94a649c..89ee0652 100644 --- a/docs/codemonster-ui-2.0-release-notes.md +++ b/docs/codemonster-ui-2.0-release-notes.md @@ -26,8 +26,8 @@ Vue and Layouts require Vue `^3.5.0`. For Node consumers, including SSR, use Nod ## Added -- Vue and Vanilla reference sites with a searchable component catalog, interactive previews, - copyable examples, integrated guides and a Release Workspace demo. +- Vue and Vanilla reference sites with interactive component previews, copyable examples, and links + to the developer guides. - A dedicated Layouts package for shells, page layouts, regions and shared breakpoint helpers. - Opt-in historical Vue and Layouts entry points for incremental migration, including component subpaths with automatic CSS in browser builds and CSS-free entries for server rendering. @@ -43,7 +43,6 @@ Vue and Layouts require Vue `^3.5.0`. For Node consumers, including SSR, use Nod ## Fixed -- Matching `Vue` in site search now surfaces local installation and Vue quick start first. - The compact Select preview reserves space for its two-option listbox. - Sorting the DataTable preview reorders the example rows in both directions. - Dialog and Drawer descriptions describe how to open the previews and remain accurate when open. diff --git a/docs/components/data-tables.md b/docs/components/data-tables.md index 8472bfed..e5971046 100644 --- a/docs/components/data-tables.md +++ b/docs/components/data-tables.md @@ -25,6 +25,10 @@ Table supplies ``, ``, and `` wrappers but does not infer h relationships. Its outer element owns forwarded attributes and horizontal scrolling. No runtime is needed. +Table and auto-layout DataTable use the available width and scroll when their content needs more +room. DataTable retains the scrollable minimum for fixed columns so pinning and resizing have room +to work. Column headings use the label scale, while tabular numerals align figures in data cells. + ## DataTable data model Columns have a unique kebab-case `key`, non-empty `header`, optional `sortable`, and optional diff --git a/docs/components/overlays.md b/docs/components/overlays.md index 18f56806..75fad889 100644 --- a/docs/components/overlays.md +++ b/docs/components/overlays.md @@ -163,6 +163,9 @@ when the surface flips or shifts to fit the viewport. - Rich Tooltip content must remain brief and cannot contain controls. You can move the pointer onto the tooltip to read it, or press Escape to dismiss it without moving focus. Provide required instructions where they do not depend on a tooltip. +- Enhanced inline tooltips shift or flip at viewport edges. A clipping ancestor can still hide + an inline tooltip. Choose a portal target outside that ancestor when the panel must extend + beyond its bounds. - Keep content inside a component-owned trigger button noninteractive. Use authored trigger composition for existing buttons: Tooltip accepts one in its default slot, and Vue Popover and Dropdown accept one with `triggerAsChild` or through their historical entries. diff --git a/docs/recipes/code-block.md b/docs/recipes/code-block.md index ff2e8db3..6945f8d3 100644 --- a/docs/recipes/code-block.md +++ b/docs/recipes/code-block.md @@ -1,6 +1,6 @@ # Vanilla code block recipe -Run `npm run preview:vanilla` from the repository root and open `code-block-example.html` on the local preview server. For deployment, run `npm run build:vanilla` and serve `examples/vanilla/dist` over HTTP. [Example HTML](../../examples/vanilla/code-block-example.html) · [Styles](../../examples/vanilla/code-block-example.css) · [Copy module](../../examples/vanilla/code-block-example.mjs) +Run `npm run dev:vanilla` from the repository root and open `code-block-example.html` on the local server. For deployment, run `npm run build:vanilla` and serve `examples/vanilla/dist` over HTTP. [Example HTML](../../examples/vanilla/code-block-example.html) · [Styles](../../examples/vanilla/code-block-example.css) · [Copy module](../../examples/vanilla/code-block-example.mjs) Render an escaped code sample inside `
` and use a `
` for its filename or language. Give each caption a unique ID and use it to name the scrollable region. The source preserves indentation and long lines. The scroll region can receive keyboard focus, and the code remains readable and selectable with JavaScript disabled. If your server already highlights code, render its escaped text and trusted highlighting spans inside ``. The recipe stylesheet uses CodeMonster UI tokens and the shared button styles. diff --git a/docs/recipes/playground.md b/docs/recipes/playground.md index 98b6eb8d..8e5f614e 100644 --- a/docs/recipes/playground.md +++ b/docs/recipes/playground.md @@ -1,6 +1,6 @@ # Vanilla playground recipe -Run `npm run preview:vanilla` from the repository root and open `playground-example.html` on the local preview server. For deployment, run `npm run build:vanilla` and serve `examples/vanilla/dist` over HTTP. [Example HTML](../../examples/vanilla/playground-example.html) · [Styles](../../examples/vanilla/playground-example.css) · [Preview module](../../examples/vanilla/playground-example.mjs) +Run `npm run dev:vanilla` from the repository root and open `playground-example.html` on the local server. For deployment, run `npm run build:vanilla` and serve `examples/vanilla/dist` over HTTP. [Example HTML](../../examples/vanilla/playground-example.html) · [Styles](../../examples/vanilla/playground-example.css) · [Preview module](../../examples/vanilla/playground-example.mjs) Enter a body fragment in HTML, styles in CSS, and a browser script in JavaScript. Run replaces the preview with a fresh document. Reset restores the sample source and starting preview. The example source and starting preview are visible with JavaScript disabled. The recipe accepts HTML, CSS, and JavaScript directly. Vue single-file component compilation requires the Vue playground. diff --git a/docs/release-checklist.md b/docs/release-checklist.md index d836cf51..156c8589 100644 --- a/docs/release-checklist.md +++ b/docs/release-checklist.md @@ -51,7 +51,7 @@ npm run typecheck npm run lint:all npm run build npm run check:packed-consumers -npm run build:demo +npm run build:showcase npm run build:vanilla npm run prepublish:all ``` @@ -70,9 +70,8 @@ All commands must pass on the release commit. Also confirm: ## 4. Inspect tarballs -`npm run prepublish:all` builds and runs dry-run packs for every npm package. For a CodeMonster UI -only train, `npm run prepublish:ui` provides the focused build and dry run. Dry runs print proposed -archive contents but do not create `.tgz` files. Review those file lists and inspect each target +`npm run prepublish:all` builds and runs dry-run packs for every npm package. Dry runs print +proposed archive contents but do not create `.tgz` files. Review those file lists and inspect each target explicitly when release metadata changes: ```bash diff --git a/docs/vanilla.md b/docs/vanilla.md index 59ae2f2c..4433fafb 100644 --- a/docs/vanilla.md +++ b/docs/vanilla.md @@ -76,14 +76,15 @@ native submission or application validation behavior. ## Browser assets -Run `npm run preview:vanilla` from the repository root to build and open the full catalog. -Browse Core, Reference, Examples, Layouts, Colors, and Icons on separate pages. Reference -pages include copyable Vue and Vanilla examples. Core shows variants, and Examples shows how -the components work together in a release workspace. All pages share the theme selector. +Run `npm run dev:vanilla` from the repository root to edit the showcase with browser reloads. +To inspect production output, run `npm run build:vanilla` followed by `npm run preview:vanilla`. +Browse component variants in the Visual matrix or visit Layouts, Colors, and Icons. Component +detail routes such as `/components/button/` provide copyable Vue and Vanilla examples. All pages +share the theme selector. For assets to deploy, run `npm run build:vanilla` and serve the contents of `examples/vanilla/dist` over HTTP. Keep the `tokens` and `css` directories intact so -their relative imports resolve. Open `index.html` for the catalog, `accordion-example.html` +their relative imports resolve. Open `index.html` for the Visual matrix, `accordion-example.html` for minimal integration, `confirm-dialog-example.html` for a confirmation flow, `code-block-example.html` for the [code block recipe](recipes/code-block.md), or `playground-example.html` for the [Vanilla playground recipe](recipes/playground.md). diff --git a/docs/verification/visual-excellence-design-review.md b/docs/verification/visual-excellence-design-review.md new file mode 100644 index 00000000..2ef2c5ed --- /dev/null +++ b/docs/verification/visual-excellence-design-review.md @@ -0,0 +1,199 @@ +# CodeMonster UI — независимая дизайнерская приёмка + +## Вердикт по первому проходу + +Первый проход устранил подтверждённые дефекты состояний и сделал каталог удобнее. До уровня +образцовой дизайн-системы оставались как минимум иерархия заголовков внутри компонентов, +сопоставимость вариантов в showcase, читаемость плотных таблиц и видимые состояния при +взаимодействии. Например, прежний [отчёт](visual-excellence-initiative.md) относит все обычные +изменения в 12 исторических кадрах к обводкам трёх полей. На этих кадрах сохранились их размер, +контент, шрифт и радиус. Совпадение двух адаптеров подтверждало переносимость этих изменений. + +Сравнение исходников использует две сохранённые копии рабочей папки. Первая снята перед +первоначальным проходом, вторая перед этим ревью. Обе включают имевшуюся в работе реорганизацию +showcase. Это даёт возможность отделить её от правок, сделанных в рамках инициативы. Чистый +`857c0e396077a7703a6b0b28c7c731fdb7f7befb` — опубликованный исходный коммит, а не точное +содержимое любой из этих рабочих копий. + +| Область | Что действительно сделал первый проход | Почему результат был недостаточным | +| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Палитра | Переназначил три семантические роли `border-interactive`, `border-strong` и `text-muted` в [semantic-colors.ts](../../packages/tokens/src/semantic-colors.ts). Примитивные OKLCH-шкалы и статусные цвета сохранились. | Улучшение контраста реально. На поднятой тёмной поверхности интерактивная обводка выросла с 2.51:1 до 3.14:1. Расстановка уровней текста и поверхностей внутри конкретных компонентов требовала дальнейшей работы. | +| Типографика | Поднял H1 матрицы с 20 px до 28/34 px и добавил кириллический образец. | Вес заголовка Card и Panel оставался 400 при размере 16 px, как у основного текста. Заголовки Dialog и Drawer также выглядели как обычный текст. Шкала пакета и его гарнитуры не менялись. | +| Геометрия и состояния | Вернул видимость фокуса и выбранных значений в forced colors. Восстановил точку выбранного Radio на hover и press. | Размеры компонентов и их внутренние отступы почти не изменились. В компактном Input две встроенные кнопки оказались в одной позиции. В DataTable минимум 576 px обрезал даже простые таблицы при доступных 270 px. | +| Spacing, radii, borders, shadows | В матрице изменились заголовок, отступы навигации и секционные ссылки. В пакете изменился цвет некоторых обводок и появилась резервная обводка фокуса. | Шкалы отступов, радиусов, толщин и теней остались прежними. Начальная работа не давала основания считать ритм каждой композиции измеренным. | +| Showcase | Добавил девять секционных ссылок, устойчивые ориентиры для клавиатуры и оформил warehouse-таблицу. | Матрица всё ещё начиналась с трёх карточек про тему, а на Layouts рабочий интерфейс находился после абстрактных примитивов. На широком экране одиночный Button терялся в сцене шириной 1248 px. | + +Получили прямые правки отдельные формы, состояния навигации и меню, фокус ссылок и кнопок. +Card, Panel, Table, DataTable, компоненты обратной связи и большинство layout-компонентов +сохранили свою CSS-геометрию и визуальную иерархию. Глобальная семантическая палитра могла +косвенно изменить их приглушённый текст или обводку. Первый проход был сосредоточен на +конкретных дефектах доступности и showcase, поэтому его покрытие не равнозначно дизайнерской +приёмке каждого компонента. + +## Метод и критерии этого ревью + +Исходные и новые кадры получены из раздельно собранных каталогов. Для основных страниц +сопоставляются Vue и Vanilla, обе темы и ширины 360/1440 px. Для отдельных компонентов +сравниваются опубликованные reference-превью и контрактные варианты. Для интерактивных +недостатков используются живые измерения DOM и отдельные кадры hover, press, focus и open. +Оценка опирается на видимую иерархию, читаемость, геометрию, выравнивание, интервалы и +различимость состояний в двух темах. Проверки контракта и axe вынесены в раздел верификации. + +Для каждой группы приоритет отдан дефектам с воспроизводимым влиянием на чтение или действие. +Веса и поверхности взяты из текущих ролей, чтобы сохранить характер системы и исключить новую +палитру или отдельные правила адаптера. Статусы итоговой приёмки разделены на локальную +верификацию, открытые дизайнерские наблюдения и два релизных шлюза. + +## Покомпонентное ревью + +Архив `artifacts/codemonster-ui-visual-excellence-design-review.zip` содержит 13 заключений +по действиям и формам в `controls/audit.md` и 24 заключения по 81 варианту обратной связи, +навигации и оверлеев в `family-review/README.md`. Ниже описаны остальные 25 компонентов с +контрактными кадрами. Имена в последней колонке соответствуют снимкам атласа. + +| Компонент | Наблюдение и решение | Доказательство | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | +| Link | В базовом примере ссылка без подчёркивания выделяется только акцентом. Для ссылки в сплошном тексте важен предусмотренный вариант с постоянным подчёркиванием. Геометрия читается, прежние уровни и варианты сохранены. | `link-default`, `link.css` | +| Card | Заголовок 16 px / 400 выглядел как первая строка основного текста. Вес 600 даёт отчётливое начало карточки с той же высотой строки. Длинные слова переносятся. | `card-title`, `table/*/chromium/` | +| Panel | В Activity заголовок и содержимое имели равный визуальный вес. Вес 600 применён по тому же правилу, включая subtle-поверхность. | `panel-default`, `panel-subtle` | +| GroupBox | Легенда пересекает границу намеренно. Отступы заголовка, пиктограммы и начала содержимого читаются как одна конструкция. Нативный input здесь оптически отличается от библиотечных полей. Нужен длинный заголовок для отдельной проверки обрезки легенды. | `group-box-default` | +| Table | Простая таблица прятала столбец Status на узком экране. Авторазмер даёт место обеим колонкам. Заголовки 14 px / 600 на отдельной поверхности лучше отделяются от строк 16 px. | `table-default`, `table-presentation` | +| DataTable | В Accounts за правым краем оказывались сумма и имя. Авторасчёт ширины освобождает простые данные от минимума 576 px. Выбранная строка видна по подложке и checkbox, активная сортировка выделяется цветом, ширина маркера стабильна. Фиксированные колонки сохраняют прокрутку. | `data-table-interactive`, `data-table-pinned`, `data-table-resizable` | +| ColumnChooser | Контур кнопки различим в обеих темах. В открытом состоянии список выровнен по началу, с отдельным разделителем для Select all. Размер панели наследуется от Popover. | `column-chooser-default` | +| PageHeader | Заголовок 26 px / 600, описание 16 px и отдельная строка действия на узкой ширине уже дают ясную иерархию. Оставлен как образец пропорций. | `page-header-default` | +| Container | Ровное смещение контента от края. Default и fluid выглядят одинаково на узком кадре. Разница назначения видна в Layouts с управлением шириной. | `container-default`, `container-fluid` | +| Grid | На узком контрактном кадре колонки переходят в одну без горизонтальной обрезки. Сопоставление широкой сетки берётся из Layouts. | `grid-default`, Layouts | +| Inline | Save и Cancel сидят на общей оптической оси. Контрактный кадр намеренно включает нативную кнопку. | `inline-default` | +| Stack | Интервал между First и Second отделяет строки. Более содержательная проверка плотности есть в многострочном примере формы. | `stack-default`, Forms | +| Section | Вариант surface сохраняет внутренний отступ и низкий контур. Нативный заголовок Report и строка Ready разделены минимально. Для оценки ритма длинного содержимого нужен содержательный образец. | `section-surface` | +| AppShell | Product, Filters, Navigation и Content сохраняют порядок, границы и начало строки на узком экране. Закрываемый вариант показывает нативную кнопку. Живая область Aside проверяется на Layouts. | `app-shell-default`, `app-shell-collapsible` | +| DocumentLayout | Guide, Version 2 и Chapters разделены полосами и правилом. Пустое пространство вокруг Body требует проверки на длинной статье со sticky-областями. | `document-layout-default`, Layouts | +| AdminLayout | На узком кадре меню, Projects и Dashboard выделены в три зоны. Плотность Dashboard остаётся свойством слота приложения. | `admin-layout-default`, `admin-layout-collapsed` | +| AdminShell | Контрастная верхняя полоса и вложенная карточка задают характер. При прокрутке на 175 px панель пропускала фон страницы и инверсный заголовок терялся. Теперь панель держит свою инверсную поверхность. | `before/*-admin-sticky.png`, `after/*-admin-sticky.png` | +| AuthLayout | Узкая центральная панель и заголовок Sign in дают оптический центр в обеих темах. Ошибки авторской формы требуют отдельной композиции. | `auth-layout-default`, Auth preview | +| SetupLayout | Заголовок и короткое пояснение сидят над отделённым действием. Многошаговая композиция на Layouts дополняет короткий контракт. | `setup-layout-default`, Setup preview | +| ErrorLayout | Код, заголовок и действие образуют центрированную вертикальную ось. Для пары действий и длинного описания нужны дополнительные примеры. | `error-layout-default`, Error preview | +| HeaderArea | Нижняя граница читается как конструктивная линия. Отступ Workspace совпадает с соседними регионами в композиции. | `header-area-default` | +| SidebarArea | Внутренний отступ и линия на логическом конце видны в обеих темах. Меню и плотность определяет содержимое слота. | `sidebar-area-default` | +| ContentArea | Текст начинается на общей сетке, граница отсутствует. В одиночном кадре видна только роль поверхности. | `content-area-default` | +| AsideArea | Линия стоит на логическом начале, зеркально к SidebarArea. Длинное содержимое проверяется в живых shell-примерах. | `aside-area-default` | +| FooterArea | Верхняя линия и отдельный уровень поверхности тихо завершают композицию. Текст Support использует общий ритм. | `footer-area-default` | + +Из двух публичных композиций вне манифестов **ConfirmDialog** проверяется как Dialog с +действиями и наследует новую иерархию заголовка. **ThemeProvider** оценивается на смене темы +и наследовании токенов в обеих сборках. Его вклад виден в Theme на матрице. + +## Подтверждённые изменения + +- **Геометрия и состояния форм.** Две кнопки компактного Input имели одинаковые координаты. + Теперь это две площадки 24×24 px с зазором 4 px, и обе работают от указателя. Select оставляет + стрелку при наличии clear, а длинный пункт перестал расширять страницу с 390 до 698 px. + Новый предел высоты вмещает трёхстрочный пункт и соседнюю строку. Hover DatePicker теперь + различим, а readonly получает отдельное состояние. У ThemeSwitch реакция на hover и press + остаётся спокойной, обводка фокуса укладывается в 4 px между сегментами. +- **Типографическая иерархия.** Card и Panel используют 16 px / 600 для заголовка без увеличения + занятой строки. Dialog и Drawer используют 18 px / 600, Alert отделяет заголовок весом 600. + В Alert и модальном заголовке длинный кириллический фрагмент в 554,5 px теперь переносится + внутри контейнера. ProgressBar вынес процент из 8 px шкалы в отдельный 13 px слот с табличными + цифрами. В исходном 1% виден обрывок знака процента. Новая подпись читается от 0 до 100%, + в том числе в RTL. +- **Поверхности и данные.** В контейнере 270 px обычные Table и DataTable теперь занимают + 270 px вместо 576 px. Зафиксированные примеры по-прежнему занимают 576–612 px и прокручиваются. + Роль подложки заголовка, табличные цифры и отдельная подсветка выбранных строк делают + чтение по горизонтали проще. У AdminShell во время прокрутки текст отделён от рабочего + содержимого непрозрачным фоном. Это видно в обоих адаптерах и обеих темах. +- **Цвет и ритм.** Наведение больше не стирает текущий пункт NavMenu, а выключенные + Accordion и Menu отличаются по весу и тону. Для новых состояний использованы имеющиеся + семантические поверхности, цвета текста и размеры. Новые примитивные цвета, гарнитуры, + глобальные шкалы отступов, радиусов или теней не понадобились. Изменения относятся к + конкретным случаям, где предыдущие роли давали слабую иерархию или неверную геометрию. + +## Приёмка showcase + +На Layouts реальный складской интерфейс вышел на первый экран. Его таблица использует +семантический caption, правое выравнивание чисел, цветовые статусы с текстом и работающую +пагинацию. Рядом находится навигация к примерам построения оболочек. В Theme вместо трёх +разрозненных панелей две согласованные области. Начало Typography на репрезентативном +снимке сместилось вверх с y=545 до y=497 на десктопе и с y=849 до y=595 на планшете. + +В reference-страницах читаемая сценическая колонка на 1440 px сузилась с 1248 до 1000 px. +Навигация по странице вынесена в отдельную колонку, простой Button получил одинаковую +высоту сцены 80 px в двух сборках вместо 112 px в Vue. Автоподгонка обычных превью +использует одну логику, а вложенные модальные и layout-превью сохраняют заданные минимумы. +Пустые SVG образцов IconButton заменены штатными пиктограммами. В Vanilla без JS обе +демонстрационные нативные селекции Plan снова показывают системную стрелку. Клавиатура +достигает секционных ссылок и warehouse-пагинации. + +Страницы матрицы стали организованнее, а warehouse-композиция даёт конкретную причину изучать +API. Слабое место — вертикальная форма шириной 384 px внутри 1248 px пространства. Vue +показывает компонент Select, Vanilla показывает нативный выбор. Последний теперь узнаваем, +однако примеры остаются оптически разными. Для дизайнерского эталона нужны одинаковые +контекст и задумка сценария в обеих реализациях. Также по прямой ссылке на Forms в Vanilla +без JS видны одновременно рамки секции и заголовка. + +В архиве ревью `showcase/measurements-after.jsonl` содержит парные замеры, а `index.html` +открывает офлайн-атлас исходных и финальных состояний. Эти файлы можно рассмотреть независимо +от результатов тестов. + +## Проверки и релизные шлюзы + +- В двух темах сняты все 181 контрактный вариант до и после, по 362 кадра на фазу. + Совпали 273; изменились 89, из них у 18 различаются размеры кадра. + Различия относятся к оформлению форм, таблиц, заголовков, состояния навигации, процента + выполнения и пиктограммам. Списки и размеры записаны в `atlas/component-before-after.json`. +- Сняты 248 reference-превью на фазу для обеих тем и адаптеров. До и после также сохранены + кадры основных страниц и отдельно 28 пар композиционных скриншотов. +- В первичном замере двух светлых reference-превью измерялась ещё меняющаяся высота + iframe. После стабилизации Accordion совпал по геометрии и пикселям при 998×99 px, + Textarea совпал при 998×120 px. Повтор охватил обе темы. Доказательства находятся в + `showcase/reference-recheck`. +- В пакетном Chrome 151 совпали **362 пары Vue/Vanilla**. Прошли **144 поведенческих** + прогона с одинаковыми сигнатурами движения. Для тёмного внешнего результата + CommandPalette до/после отмечено 11 пикселей только на закруглениях контура фокуса. +- Финальные production-сборки прошли **300 комбинаций** showcase в Chromium 157, + Firefox 148 и WebKit 26.4, 24 axe-проверки страниц и 12 контрастных проверок открытого + календаря. Более ранние полные проходы Chromium 149 и локального 151 прерывались на + инициализации страницы или переходе по хлебным крошкам. В Chromium 151 девять из девяти + изолированных переходов прошли в ширинах 320, 360 и 1440 px. Логи обоих типов сохранены. +- Измерения таблиц, типографики и нелинейных состояний дали 18 совпадающих пар Vue/Vanilla + в каждом из трёх браузеров. Шесть разных вариантов включают простую таблицу, сортировку, + выделение, фиксированные и изменяемые колонки. Кадры закреплённой панели сопоставлены + в четырёх комбинациях адаптера и темы. +- `npm test`, production-сборки, исходные контракты, SSR, типы, проверка размера пакетов + и 181 контрактная проверка доступности прошли локально. Формы дали 9 тестов в каждом + из Chromium, Firefox и WebKit. Контрольные состояния Display/Navigation дали 12 пар + адаптера и темы в трёх движках. Для нативных связей проверялись отдельные сценарии без JS. +- Для 48 исторических кадров на адаптер локальный Chrome for Testing 151.0.7922.138 показал + 20 новых различий до/после на пороге 0. Изменились Alert, Card, Input, Select и DatePicker. + Строгая проверка утверждённых PNG на прежнем пороге 4 даёт 44 расхождения на адаптере. + Это локальный рендер: прежний остаток растеризации шрифта и намеренные дизайн-изменения. + Исходные PNG и значения порогов сохранены. + +| Релизный шлюз | Статус | Проверенное основание | +| --------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pinned hosted renderer | **BLOCKED** | GitHub Actions доступен. Последний успешный visual job относится к опубликованному `857c0e39` и не содержит локальный кандидат. Настроены `macos-26` и Chrome for Testing `151.0.7922.138`. Точный кандидат должен получить проверочный SHA и запуск с этими настройками. [Visual job](https://github.com/codemonster-ru/ui/actions/runs/43869846096/job/133307803414) | +| Native assistive technology | **BLOCKED** | VoiceOver установлен. Попытка запуска через нативный мост завершилась `timeoutReached`, приложение оставалось неактивным. Единственная обнаруженная локальная Windows VM приостановлена и относится к другой задаче, активная сессия NVDA не обнаружена. Условия ручной проверки перечислены в [чеклисте RC.2](codemonster-ui-2.0-rc.2.md#manual-assistive-technology-acceptance). | + +## Что остаётся открытым + +1. **DatePicker при 320 px и 200% текста.** Шесть соседних пар дат пересекаются, + ширина содержимого доходит до 335 px. Проверенная CSS-проба убрала наложение, но рвала + подписи дней и сближала двузначные даты. Требуется общая локализованная компактная + раскладка со сквозной проверкой диапазонов, времени и навигации. Исходный и финальный + кадры находятся в `controls/{before,after}`, замеры в `supplemental-measurements.json`. +2. **Непортальный Tooltip у края.** На ширине 390 px всплывающая подпись начинается + в x=−4,25 px при триггере x=24 px. Текст читается, левая граница обрезается. Портальный + режим умеет учитывать viewport. Для обычного режима нужна проверенная стратегия + позиционирования на поддерживаемых версиях браузеров. +3. **Последние композиционные детали.** Спроектировать равноправную форму для двух showcase, + проверить глубокую ссылку с одной понятной индикацией фокуса и показать полные циклы + пустых, выполняющихся, ошибочных и успешных состояний в реальных композициях. +4. **Покрытие первичного задания.** Инвентарь, обе темы, сопоставление обычных состояний, + архитектура и целевые изменения проверены. Исчерпывающее сочетание всех публичных + вариантов, пользовательских слотов, RTL, локалей, 200% текста и реальных тач-устройств + остаётся открытым. В частности, измерения интерфейсных состояний в эмуляции не заменяют + прохождение сценариев с нативной речью. + +**Дизайнерская приёмка остаётся открытой.** Локальный результат демонстрирует конкретные +улучшения и пригоден для ревью. Закрытие DatePicker и проверка принятого набора эталонов +на штатной инфраструктуре остаются обязательными для окончательной приёмки. diff --git a/docs/verification/visual-excellence-initiative.md b/docs/verification/visual-excellence-initiative.md new file mode 100644 index 00000000..103aeeaf --- /dev/null +++ b/docs/verification/visual-excellence-initiative.md @@ -0,0 +1,202 @@ +# Visual excellence initiative + +## Work register + +| Status | Objective | Scope and evidence | +| ------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | +| DONE | Identify the accepted reference and preserve the comparison input | RC.2 hosted verification and a separate copy of the starting worktree, including its pending showcase changes. | +| DONE | Audit the inventory and define shared visual rules | Reviewed 64 public entries, 62 manifests, CSS and token sources, and representative browser states. | +| DONE | Repair shared visual defects at their source | Shared CSS and theme roles, with packaged focus and selection verification across three engines. | +| DONE | Refine reference pages and compositions | Both production showcases, with comparison captures and four clean Core axe scans. | +| DONE | Verify rendering, interactions and package boundaries | Final package and SSR suites, paired component checks, and three production showcase browser sweeps. | +| DONE | Record independent critique and release disposition | Reviewed before and after captures and documented release gates. | +| BLOCKED | Approve the new release baseline | Requires the pinned hosted renderer and manual native verification. | + +## Baseline and scope + +The branch started at `857c0e396077a7703a6b0b28c7c731fdb7f7befb`. The latest accepted hosted +run belongs to `3b292a929732714adb6fe5f8c756206dc492cf65`. It passed all eight jobs, including +the strict stored visual comparison. See the [RC.2 verification record](codemonster-ui-2.0-rc.2.md). +The before comparison uses the actual starting worktree, which already contained a showcase +reorganization and build changes. The approved historical PNGs remain a separate reference. + +The [package boundaries](../architecture/package-boundaries.md) place the visual system in +CSS and design tokens. Canonical HTML and behavior scenarios describe shared public behavior. +Vue renders the component markup and Vanilla can enhance HTML in place. Native HTML, progressive +enhancement and optional font loading are part of the review criteria. + +## Design specification + +- Use semantic roles at the point of consumption. Preserve the neutral surfaces and use the + accent for actions, focus and selection. Verify foreground and boundary colors against their + actual adjacent surfaces in both themes. Pair feedback color with a label, icon, or state cue. +- Align mixed controls by size and baseline. Keep compact geometry for dense toolbars, use the + default size for forms, and let translated text wrap or grow. Reserve fully rounded shapes for + meaningful pills and circular controls. +- Use heading, body, label and caption roles for predictable hierarchy. The bundled Inter faces + cover Latin and Cyrillic. Treat the system fallback as a supported composition and allow for + different glyph metrics. Use tabular numerals where values need to compare down a column. +- A shared surface, border and shadow hierarchy should read in both themes. Use elevation for + an overlay boundary and keep focus visible when shadows are suppressed. Reserve motion for + state changes and follow the system's reduced-motion preference. +- Prefer an information-first showcase. Keep navigation and content on a shared alignment grid, + use the real component APIs in examples, and give long or wide content its own usable reflow + or scroll behavior. + +Design references include [Linear's visual hierarchy and alignment](https://linear.app/now/how-we-redesigned-the-linear-ui), +[Geist's color roles](https://vercel.com/geist/colors), [Radix Themes' color steps](https://www.radix-ui.com/themes/docs/theme/color), +[Stripe's distinction between layout and appearance](https://docs.stripe.com/payments/mobile/embedded), +and [Apple's typography guidance](https://developer.apple.com/design/human-interface-guidelines/typography). +Use the [WCAG 2.2 criteria](https://www.w3.org/TR/WCAG22/) for enabled text contrast, +non-text state cues, focus visibility, target size and reflow. + +## Token specification + +The [consumer token guide](../tokens/getting-started.md#design-tokens) describes the public CSS +variables. The package serializes the same theme graph for both adapters. The neutral 260° ramp +sets the surfaces and the neutral text hierarchy. The 247° primary ramp gives actions, selection +and focus a shared accent. Status roles map to independent success, warning, danger, info and help +ramps. Component-local properties resolve shared roles into specific dimensions and states. + +| Area | Rule and source | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Colors | Keep the existing [OKLCH primitives](../../packages/tokens/src/primitive-colors.ts). In the [semantic mappings](../../packages/tokens/src/semantic-colors.ts), place the interactive border between neutral 400 and 500 in each theme. Strong borders use neutral 500 in light mode and 400 in dark. Muted text sits between 500 and 600 in light and between 300 and 400 in dark. | +| Space and size | The [spacing scale](../../packages/tokens/src/spacing-sizing.ts) starts at 0.25 rem and reaches 4 rem. Shared control minimums are 1.75, 2.25 and 2.5 rem. [Control padding and icon sizes](../../packages/tokens/src/control.ts) allow optical offsets. | +| Typography | The [type scale](../../packages/tokens/src/typography.ts) spans 0.75 to 1.25 rem, with body at 1 rem, label at 0.875 rem and caption at 0.8125 rem. Weights 400, 500, 600 and 700 establish hierarchy. Inter's [optional Latin and Cyrillic faces](../../packages/css/src/fonts.css) fall back to installed UI fonts. | +| Border, corner and elevation | Use the [1 px boundary, 2 px strong stroke, and radius and shadow roles](../../packages/tokens/src/borders.ts). Default control, surface and overlay radii are 0.625, 0.75 and 0.875 rem. The keyboard focus outline uses the 3 px control focus token. | +| Motion and stacking | [Motion](../../packages/tokens/src/motion.ts) uses 220 ms fast, 320 ms normal and a standard ease, with reduced motion controlled by [preference CSS](../../packages/css/src/foundation/preferences.css). Native modal dialogs use the browser top layer. Inline overlays stack locally. Portaled Popover and Tooltip sit above the documented sticky layer. | + +## Component inventory and verification boundaries + +The public source inventory is 64 named `Cm*` components across `packages/vue/src/index.ts` (52) and `packages/layouts/src/index.ts` (12), described in `docs/components/index.md`. ConfirmDialog is a Dialog/Button composition and ThemeProvider defines scope and client/server theme behavior. They have recipes and targeted tests but no standalone fixture manifests. Historical `Vf*` exports include aliases and compatibility wrappers, so the public component count is not a count of distinct export names. + +All 62 manifest-backed slugs appear below. Counts are canonical cases and executable behavior scenarios discovered under `contracts//{cases,behavior}`. Their source coverage was reviewed against the public exports, `examples/shared/showcase-matrices.mts`, package CSS and existing fixture runners. + +| Family and inventory | Cases / behaviors | Covered examples and visual limits | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Actions and forms — Button, IconButton, Link, Field, Fieldset, Input, Textarea, Checkbox, Radio, Switch, Select, DatePicker, FormLayout, ThemeSwitch | 58 / 16 | Existing Button/IconButton showcase grids cover the nine visual variants, three sizes and disabled samples. Shared form variants cover three sizes; examples add required, invalid, disabled, readonly, enhanced, checked and mixed cases where supported. Canonical captures omit most size × state combinations (for example Input sm, Select lg, Radio lg). DatePicker’s nine canonical fixtures include value, clear, range, multiple, month, year, time and portal; opening and contrast require the browser harness. Forced colors exposed lost focus and choice-state defects. | +| Navigation — Accordion, Breadcrumbs, Tabs, Stepper, NavMenu, MenuBar, TableOfContents | 25 / 18 | Cases cover representative active, expanded, collapsed and disabled paths plus roving focus; ordinary appearance is shared. Canonical cases do not span every layout, long title, nested depth or Stepper content placement. Tabs’ selected underline survived the dark forced-colors probe. | +| Menus and overlays — Menu, Dropdown, Popover, Tooltip, Dialog, Drawer, CommandPalette | 32 / 25 | Cases and browser interactions exercise the open and closed, escape, containment, focus return, menu activation and empty/filtered paths. Shared motion and surface selectors are reused. Drawer right/full and Tooltip start/end/long do not have standalone canonical captures; showcase controls supplement most of these. ConfirmDialog adds separate composition/runtime and modal-focus tests. | +| Display and feedback — Icon, Alert, Avatar, Badge, Tag, Divider, Skeleton, SkeletonGate, ProgressBar, ProgressSpinner | 24 / 0 | Static states include image/initials, semantic tones, two divider orientations, loading/ready, determinate/indeterminate and animation checks. Showcase adds tone and icon variant controls. Canonical screenshots sample rather than exhaust semantic tones, Icon family/weight combinations and ProgressSpinner size/tone combinations. | +| Data — Table, DataTable, ColumnChooser | 10 / 8 | Cases cover basic/compact presentation, empty, raw/interactive rows, pins, resizers and expansion; scenarios exercise sorting, selection, paging and column visibility. Showcase variants add the loading/error/density controls. Combinations such as long labels, narrow pinned responsive tables, RTL, and reorder/resize under real touch require additional evidence. | +| Layout and surfaces — Container, Grid, Inline, Section, Stack, Card, GroupBox, Panel, PageHeader | 18 / 1 | Static examples cover representative geometry, semantic element variants and surfaces. GroupBox has collapse behavior. The fixtures omit many visual combinations of slot content, heading level, label length and intrinsic wrapping. | +| Shells, pages and areas — AdminLayout, AdminShell, AppShell, AuthLayout, DocumentLayout, ErrorLayout, SetupLayout, HeaderArea, SidebarArea, ContentArea, AsideArea, FooterArea | 14 / 4 | Fixtures sample collapsed/open sidebar, sticky shell, document offsets and setup keyboard advancement. The grouped styles in `layout-areas.css` and `page-layouts.css` implement seven region/page manifests. The designed showcase compositions exercise real library layout APIs, while the contract cases sample shell widths and region combinations. | + +The stored PNG gate in `contracts/cross-platform-visual-baselines.json` selects 12 case IDs, 2 themes and 2 viewports (48 images for each adapter). The broader 362-capture comparison covers 181 canonical cases at both themes, one default viewport, and compares Vue-mounted to enhanced Vanilla, with separate behavior after input. Existing `packages/vue/__tests__/*-ssr.test.mjs` compare Vue SSR with canonical HTML via the significant-DOM comparator. Hydration and native fallback have targeted tests, for example `packages/vue/src/components/tabs/CmTabs.hydration.test.ts`, `packages/runtime/__tests__/hydrated-elements.test.mjs`, and `packages/runtime/__tests__/native-modal.test.mjs`. These verify distinct lifecycle states and do not make every paired visual case a hydrated SSR test. + +Canonical content is predominantly English. The typography specimen samples Latin and Cyrillic. +Localizing entire examples would exercise additional wrapping, number formatting and truncation +combinations. The optional Inter CSS contains Latin, Latin Extended, Cyrillic and Cyrillic +Extended subsets. + +## Visual audit and component refinements + +| Priority | Impact and architectural cause | Candidate change | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| P1 | In forced colors, the browser suppresses shadows, removing the visible keyboard cue from multiple controls that set `outline: none`. Hidden native choice fields were especially affected because they delegate drawing to a sibling. | Keep a transparent outline beside the normal focus shadow in shared form, action and navigation CSS. Use a system-painted outline in forced colors. | +| P1 | Radio used the same paint for the checked dot and its track on hover and press, hiding the state. The checked marker also blended into the forced-colors background. | Use the semantic primary boundary color for the mark and a neutral hover or press surface. Use a system color for the forced-colors mark. See [Radio CSS](../../packages/css/src/components/radio.css). | +| P1 | Forced colors flattened the ThemeSwitch selection and the Select option set when focus moved away. DatePicker's distinct border for today could merge with ordinary dates. | Mark selection and current date explicitly in forced colors in their shared component CSS. | +| P2 | Default interactive borders were weak where the component was laid over an elevated or tinted surface. Enabled muted text fell below 4.5:1 on some of the same surfaces. | Adjust semantic mappings across both themes. Use existing OKLCH stops and keep the stronger border at a distinct emphasis. | +| P2 | The showcase matrix begins with a 20 px H1 and 24 px section headings. Deep demos were difficult to reach directly from the top. | Build a stronger title hierarchy and a native section index from the showcase's shared structure. | +| P2 | The screenshot comparator silently ignored a manifest-listed file missing from disk. | Make missing files fail the run, including in report-only mode, and record the owning capture. See the [comparator regression](../../scripts/visual/compare-showcase.test.mjs). | + +Chromium reported the following sRGB ratios from the resolved token pairs. + +| Role and adjacent surface | Light before → after | Dark before → after | +| ------------------------------------------------ | -------------------: | ------------------: | +| Interactive border, subtle light / elevated dark | 2.85 → 3.63 | 2.51 → 3.14 | +| Muted text, subtle light / elevated dark | 4.29 → 4.90 | 3.78 → 4.74 | + +The minimum interactive border ratio over the six sampled base surfaces was 3.04 in light mode +and 3.14 in dark. Active text and state indicators use 4.5:1 and 3:1 respectively for the +relevant comparisons. Native inactive controls use the [WCAG inactive exception](https://www.w3.org/TR/WCAG22/#non-text-contrast). + +## Showcase refinements + +- The [Vue matrix](../../examples/ui-showcase/src/App.vue) and [Vanilla generator](../../scripts/build/build-vanilla-showcase.mjs) + use the same section order and native hash destinations. The [shared shell](../../examples/shared/showcase-shell.css) + applies the responsive title hierarchy and spacing. At 360 px, the heading grows from 20 to + 28 px. At 1,440 px, it grows to 34 px. The section headings stay at 24 px. Nine links make + the matrix navigable by keyboard immediately below the title. +- The [typography specimen](../../examples/shared/showcase-typography.html) includes Russian text + with its language declared. Rendered glyph inspection confirms use of the bundled Cyrillic Inter face. +- The warehouse example at `/layouts/#demo-admin-shell` uses the public DataTable caption and + end-aligns quantities in the [Vue layout](../../examples/ui-showcase/src/LayoutExample.vue) and + [generated Vanilla layout](../../scripts/build/render-showcase-layout.mjs). Its narrow preview + allows keyboard scrolling. The browser suite checks paging, changing page size, and resuming + the composition at the narrow width. +- Matrix landmarks have distinct names and overflowing table examples can receive keyboard focus. + The shared examples compose native and library components, including tables, forms, navigation, + surfaces and overlays. The existing route set carries the new presentation. +- The [Vanilla demo frame](../../examples/vanilla/showcase-demo.js) defers iframe size changes to + the next animation frame and skips duplicate values. The button and DatePicker reference pages + reproduced an intermittent WebKit resize observer warning before this change. + +## Before and after + +The local evidence uses Chrome for Testing `151.0.7922.138` on macOS 27.2.1 (`26B131`) for the +stored component comparison. The captured matrix covers 12 fixtures in two themes at +390 and 1,280 px in each adapter. Strict comparison uses the repository's existing threshold 4. + +| Comparison | Result | +| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Same renderer, starting worktree to candidate | 12 of 48 images changed per adapter at threshold 0. The changed regions are the outlines of Input, Select and DatePicker, at both widths and in both themes. Dimensions are identical; 644 pixel positions changed per affected image. | +| Candidate Vue to candidate Vanilla | 48 of 48 matches at threshold 0, including all changed borders. | +| Historical approved PNGs to the local candidate | 44 of 48 images differ per adapter. Of 8,014 flagged pixel positions per adapter, 520 reproduce the [known renderer residual](stored-visual-renderer.md) and 7,494 fall within the reviewed component border changes. Zero positions fall outside those two measured regions. | + +The independent reviewer compared desktop and mobile, enforced visible focus in forced colors, +and inspected actual screenshot pixels. Early forced-colors iterations mapped an outline to the +canvas color and mapped selected text to its browser-painted backplate. The final review checked +separate visible focus and selection on Checkbox, Switch and Radio, readable selected labels on +Select and ThemeSwitch, and an underline distinguishing today's DatePicker cell from another +focused date. The type review checked the loaded font and hash-navigation focus on the live matrix. + +See `artifacts/visual-excellence` for raw images and reports. `before/component` and +`after/component` contain the fixture matrices. `showcase/{before,after}` contains the Core and +warehouse captures on mobile dark and desktop light. The warehouse element crops gained one +raster row at both widths, with the same 36 rem iframe height in CSS. The CSS preview widths +are 320 and 1,024 px in both builds. `diff/renderer-attribution.json` records the per-image +attribution and `diff/same-renderer` includes pixel overlays. Baseline PNG approval remains on +the release register below. + +## Engineering and accessibility verification + +| Check | Candidate result | +| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Canonical behavior and parity | Pinned Chromium passed 144 runs across 72 existing behavior scenarios with matching motion signatures. All 362 enhanced Vanilla and mounted Vue image pairs matched across the full suite and a targeted retry for transient fixture navigation. In the independent Chromium forced-colors review, effective style and geometry measurements matched across 20 fixture and theme pairs. | +| Initial and enhanced rendering | `npm test` passed the package tests and contract checks, including Vue SSR significant-DOM assertions, native HTML fallback and targeted hydration. A live JavaScript-disabled Vanilla matrix reached the Forms section by keyboard. The fixture capture reflects the enhanced or mounted outputs. | +| Published CSS, two themes and three engines | [The packaged browser regression](../../scripts/visual/check-form-visual-states.mjs) passed all 24 adapter, theme and mode combinations. It checks 14 focus targets, visible focus contrast, the checked Radio dot through hover and press, and the selected/current cues. The preserved before worktree failed all eight Chromium combinations. | +| Radio non-text contrast | Rest, hover and press measure 4.62, 4.14 and 3.47 in light and 4.91, 4.39 and 3.80 in dark. The ratios match between adapters. | +| Accessible markup and references | The canonical structural and axe check passed all 181 cases. Four full Core matrix axe scans covering both adapters at 360 px dark and 1,440 px light found zero violations. Chromium opened a named preview on each of the 124 manifest-backed component routes. | +| Distribution | Workspace type checks, documentation, package contracts, visual fixture validation, tree shaking and all seven package size budgets passed locally. | + +The final production showcase passed 300 route, width and theme combinations, 24 top-level axe +checks and 12 open DatePicker contrast scans in Chromium 149, Firefox 148 and WebKit 26.4. The +suite included narrow-width reflow, 200% text, keyboard navigation and the warehouse composition. +The final Chromium run served the production files through a static server with directory listings +disabled. Earlier runs through the preview server had intermittent initialization or tab-click +timeouts. The targeted Chromium 147 App Shell recheck passed ten direct trials and three +full route-prefix trials. Both sets of logs are in the evidence archive. + +Run the packaged regression after `npm run build` with `npm run visual:cross-platform:serve` +active. Set `SHOWCASE_PLAYWRIGHT` to an installed Playwright module when needed, then run +`node --test scripts/visual/check-form-visual-states.mjs` with `SHOWCASE_BROWSER` set to `chromium`, +`firefox` or `webkit`. Browser coverage used the aggregate package stylesheet, public tokens and +optional font entry. Selective CSS consumers use the documented `foundation.css` entry. + +## Remaining issues and release recommendation + +**Hold release approval.** The product and showcase changes can proceed to review. Approving +updated historical reference images requires a capture and review on the pinned hosted renderer. +The stored PNGs, comparison thresholds, package versions and release baseline are preserved. + +- Native VoiceOver and NVDA speech, Windows High Contrast and real iOS/Android touch remain open. + The three engine runs use headless browsers and emulated preferences. +- Compact clear and password actions retain their existing target-size limitations. The sample + matrices and automated checks provide partial WCAG 2.2 evidence. Full variant-by-variant, + locale, native-device and assistive-technology coverage is still open. +- The light-theme muted foreground measures 4.11:1 on the transient neutral active surface. + Reserve that foreground for the documented neutral canvas and resting surfaces. Custom themes + need to measure foregrounds against the surfaces they supply. +- Consumer migration is unnecessary. Theme overrides may need to be rechecked for the new + semantic defaults if they depend on the old border or muted text values. diff --git a/examples/shared/application-example-data.mts b/examples/shared/application-example-data.mts deleted file mode 100644 index 00f8b46f..00000000 --- a/examples/shared/application-example-data.mts +++ /dev/null @@ -1,69 +0,0 @@ -export const workspaceViews = [ - { value: 'overview', label: 'Overview' }, - { value: 'new-release', label: 'New release' }, - { value: 'settings', label: 'Settings' }, - { value: 'sign-in', label: 'Sign in' }, -]; - -export const releaseEnvironments = ['Production', 'Staging', 'Preview'].map((value) => ({ value, label: value })); - -export const releaseStates = { - released: { label: 'Released', tone: 'success' }, - queued: { label: 'Queued', tone: 'info' }, - review: { label: 'In review', tone: 'warning' }, -} as const; - -export type ReleaseState = keyof typeof releaseStates; - -export interface ReleaseRecord { - id: string; - name: string; - environment: string; - state: ReleaseState; - note?: string; -} - -export const initialReleases: readonly ReleaseRecord[] = [ - { id: 'payments', name: 'Payments API', environment: 'Production', state: 'released' }, - { id: 'reporting', name: 'International settlement reports', environment: 'Staging', state: 'review' }, - { id: 'search', name: 'Catalog search', environment: 'Production', state: 'released' }, - { id: 'permissions', name: 'Workspace permissions', environment: 'Preview', state: 'queued' }, - { id: 'billing', name: 'Billing statements', environment: 'Production', state: 'released' }, - { id: 'onboarding', name: 'Customer onboarding', environment: 'Staging', state: 'queued' }, -]; - -export const stateFilters = [ - { value: 'all', label: 'All states' }, - ...Object.entries(releaseStates).map(([value, { label }]) => ({ value, label })), -]; - -export const defaultWorkspaceName = 'Northstar'; -export const sampleSignIn = { email: 'operator@example.test', password: 'demo-release' }; - -export function filterReleases(releases: readonly ReleaseRecord[], query: string, state: string): ReleaseRecord[] { - const search = query.trim().toLowerCase(); - return releases.filter( - (release) => - (state === 'all' || release.state === state) && - `${release.name} ${release.environment}`.toLowerCase().includes(search), - ); -} - -export function summarizeReleases(releases: readonly ReleaseRecord[]) { - const counts = { released: 0, queued: 0, review: 0 }; - for (const { state } of releases) counts[state]++; - return Object.entries(releaseStates).map(([state, { label }]) => ({ - state, - label, - count: counts[state as ReleaseState], - })); -} - -export function validateReleaseName(releases: readonly ReleaseRecord[], value: string, environment: string): string { - const name = value.trim().toLowerCase(); - if (name.length < 3) return 'Enter at least three characters.'; - if (releases.some((release) => release.environment === environment && release.name.toLowerCase() === name)) { - return 'This release already exists in the selected environment.'; - } - return ''; -} diff --git a/examples/shared/application-examples.css b/examples/shared/application-examples.css deleted file mode 100644 index 572fcfc7..00000000 --- a/examples/shared/application-examples.css +++ /dev/null @@ -1,328 +0,0 @@ -.release-workspace { - --release-workspace-gutter: clamp(var(--cm-space-3), 3vw, var(--cm-space-6)); - - min-inline-size: 0; - border: var(--cm-border-width) solid var(--cm-color-border-default); - border-radius: var(--cm-radius-surface); - background: var(--cm-color-background-surface-subtle); -} - -.release-workspace :where(h2, h3, p) { - margin: 0; -} - -.release-workspace__heading { - padding: var(--release-workspace-gutter); - padding-block-end: var(--cm-space-3); - border-start-start-radius: inherit; - border-start-end-radius: inherit; - background: var(--cm-color-background-surface); -} - -.release-workspace__heading p { - color: var(--cm-color-text-secondary); - font-size: var(--cm-text-label-font-size); - font-weight: var(--cm-font-weight-medium); -} - -.release-workspace__heading h2 { - margin-block-start: var(--cm-space-1); - font-size: clamp(1.65rem, 4vw, 2.25rem); - font-weight: var(--cm-font-weight-semibold); - letter-spacing: -0.035em; - line-height: 1.12; - overflow-wrap: anywhere; -} - -.release-workspace .cm-tabs { - gap: 0; - overflow: visible; -} - -.release-workspace .cm-tabs__list { - padding-inline: var(--release-workspace-gutter); - background: var(--cm-color-background-surface); -} - -.release-workspace .cm-tabs__tab { - min-block-size: calc(var(--cm-space-10) + var(--cm-space-1)); -} - -.release-workspace .cm-tabs__panel { - min-inline-size: 0; - padding: var(--release-workspace-gutter); -} - -.release-workspace__view, -.release-workspace__form { - display: grid; - gap: var(--cm-space-4); - align-content: start; -} - -.release-workspace__toolbar, -.release-workspace__actions { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--cm-space-3); -} - -.release-workspace__toolbar { - grid-column: 1 / -1; - justify-content: space-between; -} - -.release-workspace__toolbar h3, -.release-workspace__section .cm-card__title { - margin: 0; - color: var(--cm-color-text-primary); - font-size: var(--cm-text-heading-3-font-size, 1.25rem); - font-weight: var(--cm-font-weight-semibold); - line-height: 1.25; -} - -.release-workspace__metrics { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - margin: 0; -} - -.release-workspace__metrics > div { - display: grid; - align-items: center; - gap: var(--cm-space-2); - padding-inline: var(--cm-space-2); -} - -.release-workspace__metrics > div + div { - border-inline-start: var(--cm-border-width) solid var(--cm-color-border-divider); -} - -.release-workspace__metrics > div:first-child { - padding-inline-start: 0; -} - -.release-workspace__metrics dt { - display: flex; - align-items: baseline; - gap: var(--cm-space-1); - font-size: var(--cm-text-label-font-size); - line-height: 1.25; - overflow-wrap: anywhere; -} - -.release-workspace__metrics dt::before { - display: inline-block; - inline-size: 0.5rem; - block-size: 0.5rem; - flex: 0 0 auto; - border-radius: 50%; - background: var(--release-state-color); - content: ''; -} - -[data-release-state='released'] { - --release-state-color: var(--cm-color-status-success-icon); -} - -[data-release-state='queued'] { - --release-state-color: var(--cm-color-status-info-icon); -} - -[data-release-state='review'] { - --release-state-color: var(--cm-color-status-warning-icon); -} - -.release-workspace__metrics dd { - margin: 0; - color: var(--cm-color-text-primary); - font-size: 1.5rem; - font-variant-numeric: tabular-nums; - font-weight: var(--cm-font-weight-semibold); - line-height: 1; -} - -.release-workspace__section { - align-self: start; - padding: clamp(var(--cm-space-3), 2vw, var(--cm-space-5)); -} - -.release-workspace__section > .cm-card__body { - display: grid; - gap: var(--cm-space-3); -} - -.release-workspace__filters { - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(0, 12rem); - gap: var(--cm-space-3); -} - -.release-workspace__filters > .cm-field { - min-inline-size: 0; -} - -.release-workspace__results, -.release-workspace__environment, -.release-workspace__note { - color: var(--cm-color-text-secondary); - font-size: var(--cm-text-body-font-size); -} - -.release-workspace__results { - font-size: var(--cm-text-label-font-size); - font-variant-numeric: tabular-nums; -} - -.release-workspace__table .cm-table { - min-inline-size: 0; - table-layout: fixed; -} - -.release-workspace__table .cm-table__caption { - position: absolute; - inline-size: 1px; - block-size: 1px; - overflow: hidden; - padding: 0; - border: 0; - clip-path: inset(50%); - white-space: nowrap; -} - -.release-workspace__table tr > :first-child { - overflow-wrap: anywhere; -} - -.release-workspace__table tr > :last-child { - inline-size: 6.75rem; -} - -.release-workspace__table :is(th, td) { - vertical-align: middle; -} - -.release-workspace__table tbody th { - font-weight: var(--cm-font-weight-medium); -} - -.release-workspace__table tbody tr + tr th { - border-block-start: var(--cm-border-width) solid var(--cm-color-border-divider); -} - -.release-workspace__environment, -.release-workspace__note { - display: block; - font-weight: var(--cm-font-weight-regular); -} - -.release-workspace__note { - margin-block-start: var(--cm-space-1); - white-space: pre-wrap; -} - -.release-workspace__empty { - display: grid; - justify-items: start; - gap: var(--cm-space-3); - padding: var(--cm-space-4); - border: var(--cm-border-width) dashed var(--cm-color-border-default); - border-radius: var(--cm-radius-surface); -} - -.release-workspace__editor { - max-inline-size: 44rem; -} - -.release-workspace__editor > .cm-card__body { - gap: var(--cm-space-5); -} - -.release-workspace__preferences { - display: grid; - min-inline-size: 0; - justify-items: start; - gap: var(--cm-space-2); - padding: var(--cm-space-3); - border: var(--cm-border-width) solid var(--cm-color-border-default); - border-radius: var(--cm-radius-surface); - margin: 0; - color: var(--cm-color-text-primary); -} - -.release-workspace__preferences legend { - padding-inline: var(--cm-space-1); - font-weight: var(--cm-font-weight-medium); -} - -.release-workspace__message { - overflow-wrap: anywhere; -} - -.release-workspace__message:empty { - margin-block-start: calc(-1 * var(--cm-space-4)); -} - -.release-workspace code { - overflow-wrap: anywhere; -} - -@media (width <= 36rem) { - .release-workspace__filters { - grid-template-columns: minmax(0, 1fr); - } - - .release-workspace :is(.cm-button, .cm-input, .cm-select) { - min-block-size: calc(var(--cm-space-10) + var(--cm-space-1)); - } -} - -@media (width > 36rem) { - .release-workspace__environment { - display: inline; - margin-inline-start: var(--cm-space-2); - } -} - -@media (width >= 62rem) { - .release-workspace__view { - grid-template-columns: minmax(12rem, 1fr) minmax(0, 3fr); - } - - .release-workspace__metrics { - grid-template-columns: minmax(0, 1fr); - } - - .release-workspace__metrics > div { - grid-template-columns: minmax(0, 1fr) auto; - padding: var(--cm-space-3) 0; - } - - .release-workspace__metrics > div + div { - border-block-start: var(--cm-border-width) solid var(--cm-color-border-divider); - border-inline-start: 0; - } - - .release-workspace__metrics > div:first-child { - padding-block-start: 0; - } - - .release-workspace__metrics > div:last-child { - padding-block-end: 0; - } -} - -@media (width <= 32rem) { - .release-workspace .cm-tabs__list { - display: grid; - grid-template-columns: 1fr 1.24fr 1fr 0.8fr; - align-items: stretch; - } - - .release-workspace .cm-tabs__tab { - padding-inline: var(--cm-space-1); - font-size: var(--cm-text-label-font-size); - white-space: normal; - } -} diff --git a/examples/shared/showcase-colors.css b/examples/shared/showcase-colors.css index f2f60a7a..cbcdd135 100644 --- a/examples/shared/showcase-colors.css +++ b/examples/shared/showcase-colors.css @@ -2,7 +2,6 @@ display: grid; gap: var(--cm-space-4); padding-inline: var(--cm-space-4); - line-height: normal; color: var(--cm-color-text-primary); } @@ -14,16 +13,14 @@ } .color-system__hero { - padding: clamp(1.5rem, 4vw, 3rem); + padding: clamp(var(--cm-space-6), 4vw, var(--cm-space-12)); border: var(--cm-border-width) solid var(--cm-color-border-default); border-radius: var(--cm-radius-surface); background: var(--cm-color-background-surface-elevated); } .color-system__hero h1, -.color-system__hero p, .color-system__section-heading h2, -.color-system__section-heading p, .color-system__family h3, .color-system__theme-header h3 { margin: 0; @@ -31,30 +28,14 @@ .color-system__hero h1 { max-inline-size: 18ch; - font-size: clamp(2rem, 5vw, 4rem); - line-height: 1.05; + font-family: var(--cm-font-family-heading); } -.color-system__section-heading p, -.color-system__hero > p:last-child, .color-system__theme-header span, .color-system__overlay-card span { color: var(--cm-color-text-secondary); } -.color-system__eyebrow { - color: var(--cm-color-text-link); - font-size: var(--cm-text-label-font-size); - font-weight: var(--cm-font-weight-semibold); - letter-spacing: 0.04em; - text-transform: uppercase; -} - -.color-system__section-heading { - display: grid; - gap: 0.25rem; -} - .color-system__families { display: grid; gap: var(--cm-space-6); @@ -70,12 +51,12 @@ .color-system__scale { display: grid; grid-template-columns: repeat(auto-fit, minmax(3.25rem, 1fr)); - gap: 0.375rem; + gap: var(--cm-space-2); } .color-system__primitive { display: grid; - gap: 0.25rem; + gap: var(--cm-space-1); color: var(--cm-color-text-muted); font-size: var(--cm-text-caption-font-size); } @@ -108,7 +89,7 @@ display: flex; align-items: baseline; justify-content: space-between; - gap: 1rem; + gap: var(--cm-space-4); } .color-system__theme-header h3 { @@ -118,12 +99,12 @@ .color-system__semantic-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 0.5rem; + gap: var(--cm-space-2); } .color-system__semantic { display: grid; - gap: 0.25rem; + gap: var(--cm-space-1); color: var(--cm-color-text-muted); font-size: var(--cm-text-caption-font-size); } @@ -139,11 +120,11 @@ .color-system__chips { display: flex; flex-wrap: wrap; - gap: 0.5rem; + gap: var(--cm-space-2); } .color-system__state { - padding: 0.5rem 0.75rem; + padding: var(--cm-space-2) var(--cm-space-3); border: var(--cm-border-width) solid var(--cm-color-border-default); border-radius: var(--cm-radius-control); background: var(--cm-color-background-surface); @@ -184,18 +165,18 @@ .color-system__field-states { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 0.5rem; + gap: var(--cm-space-2); } .color-system__overlay-sample { - padding: 2rem; + padding: var(--cm-space-8); border-radius: var(--cm-radius-surface); background: var(--cm-color-background-backdrop); } .color-system__overlay-card { display: grid; - gap: 0.25rem; + gap: var(--cm-space-1); padding: var(--cm-space-4); border: var(--cm-border-width) solid var(--cm-color-border-strong); border-radius: var(--cm-radius-overlay); @@ -203,34 +184,6 @@ box-shadow: var(--cm-shadow-overlay); } -.color-system__contrast-table-wrap { - overflow-x: auto; - border: var(--cm-border-width) solid var(--cm-color-border-default); - border-radius: var(--cm-radius-surface); -} - -.color-system__contrast-table { - inline-size: 100%; - border-collapse: collapse; - color: var(--cm-color-text-primary); - background: var(--cm-color-background-surface); -} - -.color-system__contrast-table th, -.color-system__contrast-table td { - padding: var(--cm-space-3) var(--cm-space-4); - border-block-end: var(--cm-border-width) solid var(--cm-color-border-subtle); - text-align: left; -} - -.color-system__contrast-table thead { - background: var(--cm-color-background-surface-subtle); -} - -.color-system__contrast-table tbody tr:last-child > * { - border-block-end: 0; -} - @media (width <= 960px) { .color-system__theme-grid { grid-template-columns: minmax(0, 1fr); diff --git a/examples/shared/showcase-colors.mts b/examples/shared/showcase-colors.mts index 5a2a6ddb..3d4e1aad 100644 --- a/examples/shared/showcase-colors.mts +++ b/examples/shared/showcase-colors.mts @@ -4,12 +4,7 @@ import { serializeCmThemeTokensToCssVars, } from '@codemonster-ru/ui-tokens'; -export const colorHero = { - eyebrow: 'CodeMonster UI color system · semantic palette', - title: 'Perceptual materials, semantic decisions', - description: - 'Primitive OKLCH scales feed semantic roles. Components consume only the canonical UI semantic token layer.', -}; +export const colorsTitle = 'Perceptual materials, semantic decisions'; export const families = new Map(); for (const variable of Object.keys(serializeCmThemeTokensToCssVars(cmPrimitiveColorTokens))) { diff --git a/examples/shared/showcase-component-reference.css b/examples/shared/showcase-component-reference.css index 637d1f97..ec71fc75 100644 --- a/examples/shared/showcase-component-reference.css +++ b/examples/shared/showcase-component-reference.css @@ -6,8 +6,7 @@ } .reference-intro, -.reference-section, -.reference-body { +.reference-section { display: grid; min-inline-size: 0; gap: var(--cm-space-3); @@ -19,149 +18,101 @@ } .reference-intro h1 { - font-size: clamp(2rem, 4vw, 3.25rem); - line-height: 1.12; + font-family: var(--cm-font-family-heading); } -.reference-intro p, -.reference-section p, -.reference-group :where(header) p { - max-inline-size: 70ch; - color: var(--cm-color-text-secondary); -} - -.reference-links, -.reference-api-index { - display: flex; - flex-wrap: wrap; - gap: 0 var(--cm-space-4); -} - -.reference-links a, -.reference-breadcrumb a, -.reference-api-index a { - display: inline-flex; - min-block-size: 2.75rem; - align-items: center; +.reference-content, +.reference-sections { + display: grid; + min-inline-size: 0; + gap: var(--cm-space-6); } -.reference-api-index a { - gap: var(--cm-space-2); +.reference-contents { + min-inline-size: 0; + align-self: start; + padding-block-end: var(--cm-space-3); + border-block-end: var(--cm-border-width) solid var(--cm-color-border-subtle); } -.reference-search { - display: grid; - gap: var(--cm-space-2); - padding: var(--cm-space-4); - border: 1px solid var(--cm-color-border-subtle); - border-radius: var(--cm-radius-surface); - background: var(--cm-color-background-surface); +.reference-contents p { + color: var(--cm-color-text-secondary); + font-size: var(--cm-text-label-font-size); + font-weight: var(--cm-font-weight-semibold); } -.reference-search-controls { +.reference-contents ul { display: flex; flex-wrap: wrap; - align-items: end; - gap: var(--cm-space-3); + gap: 0 var(--cm-space-4); + padding: 0; + margin: var(--cm-space-1) 0 0; + list-style: none; } -.reference-search label { - display: grid; - min-inline-size: 0; - flex: 0 1 14rem; - gap: var(--cm-space-1); +.reference-contents .cm-link { + min-block-size: var(--cm-control-height-sm); + align-items: center; font-size: var(--cm-text-label-font-size); - font-weight: var(--cm-font-weight-semibold); } -.reference-search label:first-child { - flex: 1 1 20rem; -} +@media (width >= 60rem) { + .reference-content { + grid-template-columns: minmax(0, 1fr) 13rem; + gap: var(--cm-space-10); + } -.reference-search :is(input, select, button) { - box-sizing: border-box; - min-block-size: 2.75rem; - max-inline-size: 100%; -} + .reference-contents { + position: sticky; + inset-block-start: calc(var(--cm-layout-header-height) + var(--cm-space-4)); + grid-row: 1; + grid-column: 2; + padding-block-end: 0; + padding-inline-start: var(--cm-space-4); + border-block-end: 0; + border-inline-start: var(--cm-border-width) solid var(--cm-color-border-subtle); + } -.reference-search select { - min-inline-size: 0; - padding-inline: var(--cm-space-2); - border: 1px solid var(--cm-color-border-default); - border-radius: var(--cm-radius-control); - color: var(--cm-color-text-primary); - background: var(--cm-color-background-surface); - font: inherit; - font-weight: var(--cm-font-weight-regular); -} + .reference-contents ul { + flex-direction: column; + } -.component-reference [hidden] { - display: none; + .reference-sections { + grid-row: 1; + grid-column: 1; + } } -.reference-count { +.reference-intro p, +.reference-section p { + max-inline-size: 70ch; color: var(--cm-color-text-secondary); - font-size: var(--cm-text-label-font-size); -} - -.reference-groups { - display: grid; - gap: var(--cm-space-8); } -.reference-group, -.reference-group header { - display: grid; - gap: var(--cm-space-2); -} - -.reference-group ul { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(min(100%, 17rem), 1fr)); - gap: var(--cm-space-3); - padding: 0; - margin: var(--cm-space-1) 0 0; - list-style: none; +.reference-links, +.reference-api-index { + display: flex; + flex-wrap: wrap; + gap: 0 var(--cm-space-4); } -.reference-card { - display: grid; - box-sizing: border-box; +.reference-links a, +.reference-breadcrumb a, +.reference-api-index a { + display: inline-flex; min-block-size: 2.75rem; - block-size: 100%; - align-content: start; - gap: var(--cm-space-1); - padding: var(--cm-space-3) var(--cm-space-4); - border: 1px solid var(--cm-color-border-subtle); - border-radius: var(--cm-radius-surface); - color: var(--cm-color-text-primary); - background: var(--cm-color-background-surface); - text-decoration: none; -} - -.reference-card strong { - color: var(--cm-color-interactive-primary-subtle-foreground); - font-weight: var(--cm-font-weight-semibold); -} - -.reference-card span { - color: var(--cm-color-text-secondary); - font-size: var(--cm-text-label-font-size); - line-height: var(--cm-line-height-relaxed); + align-items: center; } -.reference-card:is(:hover, :focus-visible) { - border-color: var(--cm-color-border-default); - background: var(--cm-color-background-surface-hover); +.reference-api-index a { + gap: var(--cm-space-2); } -.reference-card:is(:hover, :focus-visible) strong { - text-decoration: underline; - text-underline-offset: 0.2em; +.component-reference [hidden] { + display: none; } .reference-breadcrumb ol, -.reference-contents ul, .reference-api-index, .reference-states { padding: 0; @@ -186,57 +137,24 @@ content: '/' / ''; } -.reference-detail { - align-items: start; -} - -.reference-contents { - border-block: 1px solid var(--cm-color-border-subtle); - font-size: var(--cm-text-label-font-size); -} - -.reference-contents summary { - box-sizing: border-box; - min-block-size: 2.75rem; - padding-block: var(--cm-space-3); - font-weight: var(--cm-font-weight-semibold); - cursor: pointer; -} - -.reference-contents ul { - display: flex; - flex-wrap: wrap; - gap: 0 var(--cm-space-4); -} - -.reference-contents a { - display: flex; - min-block-size: 2.75rem; - align-items: center; - color: var(--cm-color-text-secondary); - text-decoration: none; -} - -.reference-contents a:is(:hover, :focus-visible) { - color: var(--cm-color-text-primary); - text-decoration: underline; - text-underline-offset: 0.2em; -} - .reference-section + .reference-section { padding-block-start: var(--cm-space-5); - border-block-start: 1px solid var(--cm-color-border-subtle); -} - -.reference-body { - gap: var(--cm-space-6); + border-block-start: var(--cm-border-width) solid var(--cm-color-border-subtle); } -.reference-group h2, .reference-section h2 { font-size: var(--cm-font-size-3xl); } +.reference-section :is(h2, h3)[tabindex='-1'] { + scroll-margin-block-start: var(--cm-space-4); +} + +.reference-section :is(h2, h3):focus-visible { + outline: var(--cm-focus-ring-width) solid var(--cm-color-focus-ring); + outline-offset: var(--cm-border-width-thick); +} + .reference-preview :is(.reference-example, .showcase-example), .reference-variant-grid :is(.reference-example, .showcase-example) { display: grid; @@ -249,7 +167,8 @@ box-sizing: border-box; inline-size: 100%; block-size: 7rem; - border: 1px solid var(--cm-color-border-subtle); + min-block-size: 5rem; + border: var(--cm-border-width) solid var(--cm-color-border-subtle); border-radius: var(--cm-radius-surface); background: var(--cm-color-background-surface); } @@ -302,7 +221,7 @@ .reference-snippets { display: grid; min-inline-size: 0; - border: 1px solid var(--cm-color-border-subtle); + border: var(--cm-border-width) solid var(--cm-color-border-subtle); border-radius: var(--cm-radius-surface); background: var(--cm-color-background-surface); } @@ -315,7 +234,6 @@ } .reference-snippet-tabs button { - min-block-size: 2.75rem; white-space: normal; } @@ -338,10 +256,6 @@ font-size: var(--cm-text-label-font-size); } -.reference-source-heading button { - min-block-size: 2.75rem; -} - .reference-copy-status { color: var(--cm-color-text-secondary); font-size: var(--cm-text-label-font-size); @@ -352,7 +266,7 @@ max-inline-size: 100%; max-block-size: 28rem; padding: var(--cm-space-4); - border-block-start: 1px solid var(--cm-color-border-subtle); + border-block-start: var(--cm-border-width) solid var(--cm-color-border-subtle); border-end-end-radius: var(--cm-radius-surface); border-end-start-radius: var(--cm-radius-surface); margin: 0; @@ -361,21 +275,10 @@ background: var(--cm-color-background-surface-subtle); font-family: var(--cm-font-family-mono); font-size: var(--cm-text-label-font-size); - line-height: 1.65; + line-height: var(--cm-line-height-relaxed); white-space: pre-wrap; } -.reference-api-index span, -.reference-states li, -.reference-api-badge { - padding: var(--cm-space-1) var(--cm-space-2); - border-radius: var(--cm-radius-control); - color: var(--cm-color-text-secondary); - background: var(--cm-color-background-surface-subtle); - font-size: var(--cm-text-caption-font-size); - line-height: var(--cm-text-caption-line-height); -} - .reference-api-section { min-inline-size: 0; } @@ -393,7 +296,7 @@ grid-template-columns: minmax(10rem, 1fr) minmax(0, 2.5fr); gap: var(--cm-space-1) var(--cm-space-4); padding: var(--cm-space-3); - border-block-start: 1px solid var(--cm-color-border-subtle); + border-block-start: var(--cm-border-width) solid var(--cm-color-border-subtle); } .reference-api-list > div:nth-child(odd) { @@ -434,42 +337,7 @@ gap: var(--cm-space-2); } -@media (width >= 62rem) { - .reference-detail { - grid-template-columns: minmax(0, 55rem) minmax(11rem, 1fr); - column-gap: var(--cm-space-8); - } - - .reference-detail .reference-intro { - grid-column: 1 / -1; - } - - .reference-contents { - position: sticky; - grid-column: 2; - grid-row: 2; - inset-block-start: calc(var(--cm-space-16) + var(--cm-space-4)); - padding-inline-start: var(--cm-space-4); - border-block: 0; - border-inline-start: 1px solid var(--cm-color-border-subtle); - } - - .reference-contents ul { - display: grid; - } - - .reference-body { - grid-column: 1; - grid-row: 2; - } -} - @media (width <= 35rem) { - .reference-search label, - .reference-search label:first-child { - flex: 1 1 100%; - } - .reference-api-list > div { grid-template-columns: minmax(0, 1fr); } diff --git a/examples/shared/showcase-component-reference.d.ts b/examples/shared/showcase-component-reference.d.ts index 9b1e3ee9..20775525 100644 --- a/examples/shared/showcase-component-reference.d.ts +++ b/examples/shared/showcase-component-reference.d.ts @@ -1,3 +1,4 @@ import type { CmRuntime } from '@codemonster-ru/ui-runtime'; export function mountComponentReference(root: ParentNode, runtime: CmRuntime): void; +export function fitShowcaseFrame(demo: HTMLElement): void; diff --git a/examples/shared/showcase-component-reference.js b/examples/shared/showcase-component-reference.js index 65a9c51c..f8ea0d0b 100644 --- a/examples/shared/showcase-component-reference.js +++ b/examples/shared/showcase-component-reference.js @@ -1,63 +1,3 @@ -function mountCatalogFilters(reference) { - const search = reference.querySelector('[data-reference-search]'); - if (!search) return; - const query = search.querySelector('#reference-query'); - const category = search.querySelector('#reference-category'); - const clear = search.querySelector('[data-reference-clear]'); - const count = search.querySelector('[data-reference-count]'); - const groups = [...reference.querySelectorAll('[data-reference-group]')].map((group) => ({ - group, - items: [...group.querySelectorAll('[data-reference-item]')].map((item) => ({ - item, - searchable: item.dataset.referenceTerms.toLowerCase(), - })), - })); - const parameters = new URLSearchParams(location.search); - query.value = parameters.get('q') ?? ''; - category.value = parameters.get('category') ?? ''; - if (category.selectedIndex < 0) category.selectedIndex = 0; - search.hidden = false; - - const filter = () => { - const value = query.value.trim(); - const terms = value.toLowerCase().split(/\s+/u).filter(Boolean); - let matches = 0; - for (const { group, items } of groups) { - for (const { item, searchable } of items) { - item.hidden = !terms.every((term) => searchable.includes(term)); - } - const visible = items.filter(({ item }) => !item.hidden).length; - group.hidden = visible === 0 || Boolean(category.value && category.value !== group.id); - if (!group.hidden) matches += visible; - } - count.textContent = matches ? `${matches} component${matches === 1 ? '' : 's'}` : 'No matching components.'; - clear.hidden = !query.value && !category.value; - }; - - function updateFilters() { - filter(); - const url = new URL(location.href); - for (const [key, value] of [ - ['q', query.value.trim()], - ['category', category.value], - ]) { - if (value) url.searchParams.set(key, value); - else url.searchParams.delete(key); - } - if (url.href !== location.href) history.replaceState(history.state, '', url); - } - - query.addEventListener('input', updateFilters); - category.addEventListener('change', updateFilters); - clear.addEventListener('click', () => { - query.value = ''; - category.value = ''; - updateFilters(); - query.focus(); - }); - filter(); -} - function mountSnippetTabs(reference, runtime) { const snippets = reference.querySelector('[data-reference-snippets]'); const tabList = snippets?.querySelector('[role="tablist"]'); @@ -78,10 +18,7 @@ function mountSnippetTabs(reference, runtime) { export function mountComponentReference(root, runtime) { const reference = root.querySelector('[data-component-reference]'); if (!reference) return; - mountCatalogFilters(reference); mountSnippetTabs(reference, runtime); - const contents = reference.querySelector('[data-reference-contents]'); - if (contents) contents.open = matchMedia('(min-width: 62rem)').matches; // Vue mounts the reference asynchronously, after the browser's first fragment lookup. const target = document.getElementById(location.hash.slice(1)); @@ -106,3 +43,16 @@ export function mountComponentReference(root, runtime) { }); } } + +export function fitShowcaseFrame(demo) { + const frame = window.frameElement; + if (!frame || frame.matches('.showcase-frame--tall, .reference-frame--tall')) return; + + new ResizeObserver(() => { + requestAnimationFrame(() => { + const border = frame.clientHeight === 0 ? 0 : frame.offsetHeight - frame.clientHeight; + const blockSize = `${Math.ceil(demo.getBoundingClientRect().height) + border}px`; + if (frame.style.blockSize !== blockSize) frame.style.blockSize = blockSize; + }); + }).observe(demo); +} diff --git a/examples/shared/showcase-component-reference.mts b/examples/shared/showcase-component-reference.mts index cf188f24..0319ce3f 100644 --- a/examples/shared/showcase-component-reference.mts +++ b/examples/shared/showcase-component-reference.mts @@ -1,9 +1,6 @@ -import { documentationUrl } from './showcase-guide-links.mts'; - export interface ReferenceGroup { id: string; title: string; - description?: string; components: string[]; } @@ -21,7 +18,6 @@ interface ReferenceProp extends ReferenceEntry { export interface ReferenceComponent { slug: string; name: string; - description?: string; props: Record; slots: Record; events: Record; @@ -42,7 +38,6 @@ export const referenceSupplements = [ slug: 'theme-provider', name: 'ThemeProvider', group: 'theme', - description: 'Provide theme preferences to Vue descendants and apply the selected mode to the document root.', guide: 'recipes/theme-switch.md', target: './core/#theme', }, @@ -50,7 +45,6 @@ export const referenceSupplements = [ slug: 'confirm-dialog', name: 'ConfirmDialog', group: 'modals', - description: 'Ask for confirmation before a consequential action and handle the confirm or cancel result.', guide: 'recipes/confirm-dialog.md', target: './core/#modals', }, @@ -61,7 +55,7 @@ export function referenceCatalog(groups: ReferenceGroup[], components: Map components.get(slug)).filter((item): item is ReferenceComponent => Boolean(item)), ...referenceSupplements.filter(({ group }) => id === group), - ].map(({ slug, name, description }) => ({ slug, name, description, category: title, categoryId: id })), + ].map(({ slug, name }) => ({ slug, name, category: title, categoryId: id })), ); } @@ -187,8 +181,8 @@ export function publicName(name: string) { return name.replace(/([a-z0-9])([A-Z])/gu, '$1 $2'); } -function guideLink(path: string, base: string, label = 'Developer guide') { - return `${label}`; +function guideLink(path: string, label = 'Developer guide') { + return `${label}`; } export function referenceFrameClass(slug: string) { @@ -255,6 +249,7 @@ function vueSource(component: ReferenceComponent, example: ReferenceCase) { `import { ${componentName} } from '@codemonster-ru/${packageName}';`, ...(typeof icon === 'string' ? [`import { ${icon} } from '@codemonster-ru/ui-icons';`] : []), "import '@codemonster-ru/ui-tokens/tokens.css';", + "import '@codemonster-ru/ui-css/fonts.css';", "import '@codemonster-ru/ui-css/styles.css';", ]; const setup = [ @@ -326,71 +321,13 @@ export function vanillaReferenceSource(slug: string, markup: string) { '', '', ].join('\n'); } -export function renderReferenceIndex( - groups: ReferenceGroup[], - components: Map, - base = '.', -) { - const orderedGroups = [...groups.filter(({ id }) => id !== 'theme'), ...groups.filter(({ id }) => id === 'theme')]; - const catalog = referenceCatalog(orderedGroups, components); - return `
-
-

Component reference

-

Find a component, try it in the browser, and copy a working Vue or Vanilla example.

-
- -
- ${orderedGroups - .map( - ({ id, title, description }) => `
-
-

${escapeReference(title)}

- ${description ? `

${escapeReference(description)}

` : ''} -
- -
`, - ) - .join('')} -
-
`; -} - function renderReferenceEntry( kind: 'props' | 'slots' | 'events', entries: Record, @@ -406,8 +343,8 @@ function renderReferenceEntry( return `
${escapeReference(name)} - ${entry.required ? 'Required' : ''} - ${'native' in entry && entry.native ? 'Native' : ''} + ${entry.required ? 'Required' : ''} + ${'native' in entry && entry.native ? 'Native' : ''}
${type ? `${escapeReference(type)}` : ''} @@ -433,11 +370,16 @@ function renderSource(id: 'vue' | 'vanilla', title: string, source: string) { `; } +function categoryPath(categoryId?: string) { + if (categoryId === 'layouts' || categoryId === 'icons') return `/${categoryId}/`; + return categoryId ? `/core/#${categoryId}` : '/core/'; +} + function breadcrumb(base: string, entry?: ReturnType[number]) { return ``; } @@ -463,7 +405,7 @@ function renderRelated( return `
@@ -471,13 +413,12 @@ function renderRelated( } export function renderReferenceDetail({ component, example, preview, variants, catalog, base = '.' }: DetailOptions) { - const { slug, name, description, props, slots, events, states } = component; + const { slug, name, props, slots, events, states } = component; const guide = guidesBySlug[slug] ?? (layoutPrimitives.has(slug) ? 'components/layout-primitives.md' : 'components/layouts.md'); const accessibility = accessibilityNotes[slug]; const catalogEntry = catalog.find((entry) => entry.slug === slug); - const gallery = slug === 'icon' ? '/icons/' : catalogEntry?.categoryId === 'layouts' ? '/layouts/' : '/core/'; - const galleryAnchor = gallery === '/core/' && catalogEntry ? `#${catalogEntry.categoryId}` : ''; + const gallery = categoryPath(catalogEntry?.categoryId); const detailUrl = `${base}/components/${slug}/`; const apiEntries = ( [ @@ -486,39 +427,46 @@ export function renderReferenceDetail({ component, example, preview, variants, c ['slots', 'Content slots', slots], ] as const ).filter(([, , entries]) => Object.keys(entries).length > 0); - const sections = [ + const displayName = escapeReference(publicName(name)); + const activeAdapter = base ? 'vanilla' : 'vue'; + const accessibilityGuide = + accessibilityGuides[slug] ?? + (catalogEntry?.categoryId === 'forms' ? 'components/forms.md#native-form-and-accessibility-rules' : guide); + const sectionLinks = [ ['preview', 'Live preview'], - ['usage', 'Basic usage'], ...(variants || states.length ? [['variants', 'Variants and states']] : []), + ['usage', 'Basic usage'], ...(apiEntries.length ? [['api', 'API reference']] : []), ['accessibility', 'Accessibility'], ['related', 'Related resources'], ]; - const displayName = escapeReference(publicName(name)); - const activeAdapter = base ? 'vanilla' : 'vue'; - const accessibilityGuide = - accessibilityGuides[slug] ?? - (catalogEntry?.categoryId === 'forms' ? 'components/forms.md#native-form-and-accessibility-rules' : guide); - return `
+ return `
${breadcrumb(base, catalogEntry)}

${displayName}

- ${description ? `

${escapeReference(description.replaceAll('`', ''))}

` : ''}
-
- On this page - -
-
+
+ +

Live preview

${preview}
+ ${ + variants || states.length + ? `
+

Variants and states

+ ${states.length ? `
    ${states.map((state) => `
  • ${escapeReference(state)}
  • `).join('')}
` : ''} + ${variants ? `
More examples and states
${variants}
` : ''} +
` + : '' + }

Basic usage

-

These examples use the 2.0 packages and a build tool such as Vite. ${guideLink('getting-started.md', base, 'Installation guide')}

+

${guideLink('getting-started.md', 'Installation guide')}

${ example.canonicalHtml @@ -532,26 +480,16 @@ export function renderReferenceDetail({ component, example, preview, variants, c ${example.canonicalHtml ? renderSource('vanilla', 'Vanilla HTML', vanillaReferenceSource(slug, example.canonicalHtml)) : ''}
- ${ - variants || states.length - ? `
-

Variants and states

- ${states.length ? `
    ${states.map((state) => `
  • ${escapeReference(state)}
  • `).join('')}
` : ''} - ${variants ? `
More examples and states
${variants}
` : ''} -
` - : '' - } ${ apiEntries.length ? `

API reference

-

Names below come from the shared component contract. The developer guide explains how to use them as Vue props, events and slots, or as Vanilla markup and runtime settings.

${apiEntries.map(([kind, , entries]) => renderReferenceEntry(kind, entries)).join('')}
` @@ -560,9 +498,10 @@ export function renderReferenceDetail({ component, example, preview, variants, c

Accessibility

${accessibility ? `

${escapeReference(accessibility)}

` : ''} -

${guideLink(accessibilityGuide, base, 'Integration and accessibility guidance')}

+

${guideLink(accessibilityGuide, 'Integration and accessibility guidance')}

- ${renderRelated(slug, catalog, base, guide, `Showcase examples`)} + ${renderRelated(slug, catalog, base, guide, `Showcase examples`)} +
`; } @@ -582,9 +521,8 @@ export function renderReferenceSupplement( catalog.find((entry) => entry.slug === supplement.slug), )}

${publicName(supplement.name)}

-

${supplement.description}

@@ -595,6 +533,6 @@ export function renderReferenceMissing(base = '.') { return `
${breadcrumb(base)}

Component unavailable

-

Choose a component from the reference index.

+

Browse component examples in the visual matrix.

`; } diff --git a/examples/shared/showcase-core-matrix.mts b/examples/shared/showcase-core-matrix.mts index 79e50da1..cf840f0c 100644 --- a/examples/shared/showcase-core-matrix.mts +++ b/examples/shared/showcase-core-matrix.mts @@ -64,6 +64,9 @@ export function renderCoreMatrix(slug: string, read: (id: string) => string | un if (source === undefined) throw new Error(`Missing showcase matrix case: ${id}`); const ids = new Set([...source.matchAll(/\bid="([^"]+)"/gu)].map((match) => match[1])); const prefix = `matrix-${id}-`; + const exampleTitle = name.replaceAll('-', ' '); + const matrixLabel = `${coreComponentTitle(slug)} · ${exampleTitle}`; + const labelId = `${prefix}label`; const closedSource = slug === 'dropdown' && (name === 'composed' || name === 'pills') ? source @@ -73,6 +76,11 @@ export function renderCoreMatrix(slug: string, read: (id: string) => string | un : source; const html = closedSource .replaceAll('src="/avatar.png"', `src="${avatar}"`) + .replace(/(]*\baria-label="[^"]+)"/gu, `$1 · ${matrixLabel}"`) + .replace( + /class="(cm-(?:data-)?table__scroll)"/gu, + `class="$1" role="region" aria-label="${matrixLabel}" tabindex="0"`, + ) .replace( /\b(id|name|for|form|list|aria-controls|aria-describedby|aria-labelledby|aria-activedescendant|aria-owns)="([^"]+)"/gu, (_, attribute: string, value: string) => @@ -83,9 +91,10 @@ export function renderCoreMatrix(slug: string, read: (id: string) => string | un ) .replace(/href="#([^"]+)"/gu, (match, target: string) => ids.has(target) ? `href="#${prefix}${target}"` : match, - ); + ) + .replace(/(class="cm-accordion__panel"[^>]*\baria-labelledby="[^"]+)"/gu, `$1 ${labelId}"`); const modal = ['dialog', 'drawer', 'command-palette'].includes(slug); - return `

${name.replaceAll('-', ' ')}

+ return `

${exampleTitle}

${modal ? `` : ''} ${html}
`; }) diff --git a/examples/shared/showcase-core-recipes.html b/examples/shared/showcase-core-recipes.html index c6458110..552ba6da 100644 --- a/examples/shared/showcase-core-recipes.html +++ b/examples/shared/showcase-core-recipes.html @@ -1,5 +1,5 @@