diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bb39f058..82afecf6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,8 +1,9 @@ name: Release -# Fully automatic releases. Successful CI on a master push starts this workflow; -# if the commits since the last published version warrant a release, it bumps -# the version, publishes to npm and tags it. No version-bump PR, no manual step. +# Successful CI on a master push starts this workflow automatically. An +# owner-authorized local-QA run can also be dispatched for the exact current +# master SHA. If the commits since the last published version warrant a release, +# it bumps the version, publishes to npm and tags it. No version-bump PR. # # The version comes from conventional commits (scripts/next-version.ts): # type! / BREAKING CHANGE -> major, feat -> minor, fix|perf|revert -> patch. @@ -23,6 +24,12 @@ on: workflow_run: workflows: [CI] types: [completed] + workflow_dispatch: + inputs: + master_sha: + description: Full current master SHA after the owner-authorized local QA gate + required: true + type: string permissions: contents: read @@ -30,10 +37,20 @@ permissions: jobs: decide: if: >- - github.event.workflow_run.conclusion == 'success' && - github.event.workflow_run.event == 'push' && - github.event.workflow_run.head_branch == 'master' + ( + github.event_name == 'workflow_run' && + github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'master' + ) || + ( + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/master' && + inputs.master_sha == github.sha + ) runs-on: ubicloud-standard-2 + env: + TARGET_SHA: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || inputs.master_sha }} outputs: mode: ${{ steps.decide.outputs.mode }} version: ${{ steps.decide.outputs.version }} @@ -41,13 +58,21 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 # next-version.ts reads commit history - ref: ${{ github.event.workflow_run.head_sha }} + ref: ${{ env.TARGET_SHA }} - - name: Require the tested revision to remain master + - name: Require the exact selected revision to remain master before running it run: | + if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ]; then + test "$GITHUB_REF" = "refs/heads/master" + test "$TARGET_SHA" = "$GITHUB_SHA" + fi + if [[ ! "$TARGET_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "TARGET_SHA must be a full lowercase 40-character commit SHA" >&2 + exit 1 + fi git fetch origin master - test "$(git rev-parse HEAD)" = "${{ github.event.workflow_run.head_sha }}" - test "$(git rev-parse origin/master)" = "${{ github.event.workflow_run.head_sha }}" + test "$(git rev-parse HEAD)" = "$TARGET_SHA" + test "$(git rev-parse origin/master)" = "$TARGET_SHA" - uses: oven-sh/setup-bun@v1 with: @@ -86,16 +111,18 @@ jobs: release_sha: ${{ steps.release-sha.outputs.value }} env: VERSION: ${{ needs.decide.outputs.version }} + TARGET_SHA: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || inputs.master_sha }} steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - ref: ${{ github.event.workflow_run.head_sha }} + ref: ${{ env.TARGET_SHA }} - - name: Require the tested revision to remain master + - name: Require the selected revision to remain master before release preparation run: | git fetch origin master - test "$(git rev-parse HEAD)" = "$(git rev-parse origin/master)" + test "$(git rev-parse HEAD)" = "$TARGET_SHA" + test "$(git rev-parse origin/master)" = "$TARGET_SHA" # Mirrors ci.yml — the build resolves this plugin from a sibling directory. - name: Checkout rsbuild-plugin-ui-css-purge diff --git a/AGENTS.md b/AGENTS.md index ed518705..677720e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,18 +17,19 @@ natively, and Claude Code loads it through the `@AGENTS.md` import in implementation files.** It is the frontend working agreement: SolidJS/`@pathscale/ui` conventions, and a context-efficient workflow. Reading it first keeps context small and avoids re-deriving patterns that already exist. -- **Releases are automatic — never run `npm publish` by hand.** A successful CI run for - `master` starts [`.github/workflows/release.yml`](.github/workflows/release.yml) at the - exact revision CI tested. The workflow stops if `master` advances before release, - derives the version from conventional commits, bumps `package.json`, publishes through - npm Trusted Publishing (OIDC), and tags the published revision. There is no `NPM_TOKEN` - in this repository, so a local publish cannot authenticate anyway, and a hand-written - version bump only fights the workflow. Publishing is irreversible and a version can - never be reused, so if a release looks wrong, read the workflow run before touching - anything. -- **After a merge, confirm the fix actually published.** The release is gated by CI and - fails closed when another merge advances `master`. Confirm the npm version and tag both - point at the expected release revision: +- **Releases use the guarded workflow — never run `npm publish` by hand.** A successful + CI run for `master` starts the automatic path at the exact revision CI tested. An + authorized `workflow_dispatch` may use the local-QA path only with the explicitly + supplied full SHA that is still the exact `master` head. When a release is warranted, + both paths reuse the release preparation checks, publish through npm Trusted Publishing + (OIDC), and tag the published revision. There is no `NPM_TOKEN` in this repository, so a local publish + cannot authenticate anyway, and a hand-written version bump only fights the workflow. + Publishing is irreversible and a version can never be reused, so if a release looks + wrong, read the workflow run before touching anything. +- **After a merge, confirm the fix actually published.** The automatic release is gated + by successful master CI; the manual path is only for an explicitly authorized local-QA + release at the exact current `master` SHA. Either path fails closed when `master` + advances. Confirm the npm version and tag both point at the expected release revision: So check, every time: @@ -38,8 +39,9 @@ natively, and Claude Code loads it through the `@AGENTS.md` import in git tag --points-at HEAD # a tag here with no npm release is the hole ``` - If master is ahead of npm, inspect the CI and Release runs. Fix or re-run the failed - workflow rather than manufacturing another version bump. + If master is ahead of npm, inspect the CI and Release runs. Retry the automatic path + when master CI succeeds; use the manual path only after authorized local QA, supplying + the exact current `master` SHA. Never manufacture an extra version bump. - **One open PR per repository. Add to it.** If a PR is already open here, push your commits onto that branch instead of opening a second one. Two open PRs against the same library mean two releases, two version bumps, and a consumer that has to wait for diff --git a/README.md b/README.md index 15116c33..4a7bd42d 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ work against them directly. | family | components | |---|---| -| **Layout** | Flex, Grid, Join, Surface, Card, GlassPanel, Separator, ScrollShadow, Skeleton, EmptyState, Footer, Header, Navbar, Toolbar, FloatingDock | +| **Layout** | Flex, Grid, Join, Card, Separator, ScrollArea, ScrollHorizontal, Skeleton, Empty, Footer, Header, Navbar, Toolbar, Dock | | **Typography & misc** | Text, Link, Kbd, Badge, Chip, Tag, TagGroup, Avatar, Icon, Tooltip, Breadcrumbs, Pagination, Meter, ProgressBar, ProgressCircle, Spinner | | **Inputs** | Input, InputGroup, InputOTP, TextField, TextArea, NumberField, SearchField, PasswordField, ColorField, Checkbox, CheckboxGroup, Radio, RadioGroup, Toggle, Slider, Select, ComboBox, ListBox, SizePicker | | **Forms** | Form, Fieldset, Label, Description, ErrorMessage, FieldError, PasswordRequirements | @@ -175,6 +175,13 @@ import — the published size is the whole library, not what ships to your users | **[Contributing](https://github.com/pathscale/ui/blob/master/CONTRIBUTING.md)** | local setup, component checklist, proposal template | | **[Releasing](https://github.com/pathscale/ui/blob/master/docs/releasing.md)** | how a push to master becomes an npm version, and the gates it passes | +## Honey password validation + +`@pathscale/ui/passwordRules` exports `isPrintableAsciiPassword` and +`PASSWORD_CHARSET_MESSAGE` for inline signup and password-change validation. +Printable ASCII (U+0020–U+007E), including spaces, is accepted without normalization. +Do not apply this restriction to sign-in or reauthentication. + ## License MIT diff --git a/docs/api-contract.md b/docs/api-contract.md index ed5b43f9..de28649a 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -11,7 +11,7 @@ invisible for a day behind a doc that looked correct the whole time. When an API change is intentional, run `bun run check:api -- --write`, read the diff, and commit it. The diff is the review. -187 components. An empty list means the component adds nothing beyond +188 components. An empty list means the component adds nothing beyond HTML attributes and `UIBaseProps`; that is an assertion, not a gap. --- @@ -1506,6 +1506,15 @@ state?: State value?: number ``` +### QrCode + +```ts +level?: QrErrorCorrectionLevel +size?: number | string +title: string +value: string +``` + ### PWAInstallPrompt ```ts @@ -1594,6 +1603,16 @@ variant?: ScrollAreaVariant visibility?: ScrollAreaVisibility ``` +### ScrollHorizontal + +```ts +gap?: number +height?: number | string +itemWidth?: number +mobileGap?: number +mobileItemWidth?: number +``` + ### Select ```ts diff --git a/docs/ui-usage.md b/docs/ui-usage.md index e32f08c9..7a75e9e5 100644 --- a/docs/ui-usage.md +++ b/docs/ui-usage.md @@ -4,7 +4,7 @@ agents alike, and for every consuming application. Those apps link here rather than keeping their own copy — one library, one set of conventions, no drift. -SolidJS component library, HeroUI-parity API, daisyUI-style theming. 101 public +SolidJS component library, HeroUI-parity API, daisyUI-style theming. 103 public component families. This file is **how to USE the library** (as a consumer, or when writing demos and @@ -308,16 +308,67 @@ A trigger given plain text is unchanged and needs nothing. ## Component inventory (by family) -- **Layout/primitives**: Flex, Grid, Join, Card, Separator, ScrollArea, Skeleton, Empty, Footer, Header, Navbar, Toolbar, Dock +- **Layout/primitives**: Flex, Grid, Join, Card, Separator, ScrollArea, ScrollHorizontal, Skeleton, Empty, Footer, Header, Navbar, Toolbar, Dock - **Typography/misc**: Text, Link, Kbd, Badge, Chip, Tag/TagGroup, Avatar, Icon, Tooltip, Breadcrumb, Pagination, Meter, Progress, RadialProgress, Spinner (alias: Loading) - **Inputs**: Input, InputGroup, InputOTP, TextField, Textarea, NumberField, SearchField, PasswordField (+ password-requirements/rules, `passwordRules.ts`), ColorField, Checkbox(+Group), Radio(+Group), Switch, Slider, Select, ComboBox, ListBox, SizePicker, Form pieces (Label, Description, ErrorMessage, FieldError, Fieldset) + +For Honey signup and password changes, import `isPrintableAsciiPassword` and +`PASSWORD_CHARSET_MESSAGE` from `@pathscale/ui/passwordRules`. The validator allows +only U+0020 through U+007E, preserves spaces, and leaves length and confirmation to +the form's existing rules. Show the message inline when validation fails. Never use +this validator for sign-in or reauthentication: existing passwords remain accepted. - **Dates**: Calendar, RangeCalendar, DatePicker, DateRangePicker (internal date engine); DateField, TimeField (separate segmented editors) - **Color**: ColorPicker, ColorArea, ColorSlider, ColorSwatch(+Picker), ColorWheel, ComplexColorWheel, ColorWheelFlower, ThemeColorPicker - **Overlays**: Dialog, Drawer, Popover, Dropdown, Menu, Toast, Collapsible(+Group), Accordion - **Data**: DataGrid (assembled, `createDataGrid` model), FlexGrid (incremental reveal, `createFlexGrid` model), Table (headless compound, bring your own model), plus primitives `useStreamingBuffer`, `useStreamingSubscription` - **Auth kit**: AuthForm, AuthCard, AuthFieldGroup, AuthSubmitButton, AuthFooterLinks, AuthPoweredBy, AuthErrorMessage, AuthSuccessMessage — Layouts composing Button/Card/fields. Their spacing, alignment and tone are recipe parameters (`gap`, `align`, `variant`), so a consumer asks for the presentation it wants rather than restating utility classes. AuthCard exposes `header`, `headings`, `title`, `description`, `branding`, `body` and `footer` as `data-slot` targets. - **Connection settings**: ConnectionSettings (the panel) with `createConnectionSettings` (the store). See below. -- **Visual FX**: MetalBorder (WebGL liquid-metal border; presets `chromatic|silver|gold`, `kind="pill"|"circle"`, `glow`, `strength` 0-100, `theme="dark"|"light"|"auto"`), GlowCard (mouse-tracking glow), NoiseBackground (animated gradient blobs), ImmersiveLanding (full mini-app w/ PWA widgets), VideoPreview, LiveChat, ChatBubble, LanguageSwitcher +- **Visual FX**: MetalBorder (WebGL liquid-metal border; presets `chromatic|silver|gold`, `kind="pill"|"circle"`, `glow`, `strength` 0-100, `theme="dark"|"light"|"auto"`), GlowCard (mouse-tracking glow), NoiseBackground (animated gradient blobs), QrCode, ImmersiveLanding (full mini-app w/ PWA widgets), VideoPreview, LiveChat, ChatBubble, LanguageSwitcher + +## ScrollHorizontal + +Use `ScrollHorizontal` for a gallery whose cards move horizontally as the page +scrolls vertically. Intro and outro sections remain regular consumer content. +Children can be existing Layouts such as `Card`: + +```tsx +import { Card, ScrollHorizontal } from "@pathscale/ui"; + +
+ +

Introductory copy stays outside the gallery.

+
+ + + First story + Second story + Third story + + +
Outro content follows the gallery.
+``` + +`itemWidth` and `mobileItemWidth` set card widths; `gap` and `mobileGap` set +spacing. Defaults are 400px and 280px for widths, and 30px and 15px for gaps. +The default `height="auto"` measures the row and creates enough vertical travel +to reach the last card. Pass a number for a pixel height or a CSS length string +to choose a different section height. + +The gallery exposes a labelled `region` with a keyboard-focusable horizontal +viewport. Supply `aria-label` or `aria-labelledby` with a useful name. Focus +entering an offscreen card moves the page to reveal it without changing DOM or +focus order. Reduced motion disables sticky translation and leaves a normal +horizontal scroller. After hydration, supported browsers use a CSS view timeline; +other browsers use a passive scroll listener with frame-scheduled progress. +The component also accepts `class`, `style` and `dataTheme` props. `ScrollArea` +remains the component for an ordinary scrollable region. Renames from old versions: Loading→Spinner, DropdownSelect→Select, RangeSlider→Slider, Callout→Alert, EmptyState→Empty, Toggle→Switch, Modal→Dialog, TextArea→Textarea, Disclosure→Collapsible, FloatingDock→Dock, ProgressBar→Progress, ProgressCircle→RadialProgress, ScrollShadow→ScrollArea, Breadcrumbs→Breadcrumb. ~40 components removed outright (Carousel, Rating, Steps, Stats, FileInput, …). @@ -588,6 +639,48 @@ enablePopmotion((opts) => animate({ ...opts })); // ⚠️ WITHOUT this, all J - Solid components: `{(isExiting, onExitComplete) => …` — Presence force-unmounts after 800ms if `onExitComplete` never fires. `` for height collapse. - `resolvePreset(name, {reduceMotion})` returns the `noMotion` preset under prefers-reduced-motion. Note Dialog/Toast/Drawer animate via CSS, not this system. +The root barrel and `@pathscale/ui/motion` subpath also export small browser +motion helpers: + +```tsx +import { + animateElement, + createInView, + createScrollProgress, + springKeyframes, + stagger, +} from "@pathscale/ui/motion"; + +const visible = createInView(() => observedElement, { once: true }); +const progress = createScrollProgress(() => section, { + range: "start-start/end-end", +}); +const delay = stagger(index, 50); // milliseconds + +const samples = springKeyframes({ stiffness: 180, damping: 20, mass: 1 }); +const animation = animateElement(element, { opacity: samples }, { + duration: ((samples.length - 1) / 60) * 1000, +}); +``` + +`createInView` and `createScrollProgress` return Solid accessors and attach +browser listeners only after mount. Visibility starts as `true` if the observer +is unavailable. Scroll progress starts at zero, samples scroll updates at most +once per animation frame, and also writes `--scroll-progress` to its target for +CSS. Its supported range tracks the target from viewport top to its bottom at +viewport bottom; the target's previous inline custom property is restored on +cleanup. `supportsViewTimeline()` checks the CSS timeline and attachment range +used by `ScrollHorizontal`. + +`animateElement` uses WAAPI when available, defaults to the library's base +duration and `motionEasings.out`, and applies the final keyframe immediately when +WAAPI is unavailable. Its options follow WAAPI timing fields in milliseconds; +the returned `finished` promise resolves on completion or cancellation, and +`cancel()` stops the animation. Live reduced-motion changes finish an active +animation by default. `springKeyframes` returns normalized 60 Hz samples for a +WAAPI property; use `(samples.length - 1) / 60 * 1000` milliseconds as the +duration to preserve that sample rate. + ## Streaming ```ts @@ -639,6 +732,22 @@ token, with `@plugin "@iconify/tailwind4"` under Tailwind v4 or than ours. Both sources inherit colour through `currentColor`, so `flavor` works the same either way. +## QR codes + +`QrCode` encodes `value` into one inline SVG. Its required `title` is both the +SVG title and its accessible name. Encoding is synchronous, so a changed value +updates the matrix immediately. `level` accepts `L`, `M`, `Q` or `H` and defaults +to `M`; `size` accepts a number of CSS pixels or another CSS length. + +```tsx +import { QrCode } from "@pathscale/ui"; + + +``` + +For non-Solid use, `qrMatrix(value, level?)` returns the dark modules as a +`boolean[][]`. + ## Dates Calendar/DatePicker/RangeCalendar/DateRangePicker use the internal engine (native `Date`, a built-in name table, no `Intl` and no date lib). Values are `Date` objects; ranges are `{start: Date, end: Date}`. Controlled via `value/defaultValue/onChange`. `DateField`/`TimeField` are separate segmented text editors, not calendar-backed. diff --git a/layouts.library.json b/layouts.library.json index f70bdbad..e94cbb5e 100644 --- a/layouts.library.json +++ b/layouts.library.json @@ -153,11 +153,13 @@ "PasswordRequirements", "Popover", "Progress", + "QrCode", "RadialProgress", "Radio", "RadioGroup", "RangeCalendar", "ScrollArea", + "ScrollHorizontal", "Select", "Separator", "SizePicker", diff --git a/src/component-families.ts b/src/component-families.ts index ab42bfa1..24c11d28 100644 --- a/src/component-families.ts +++ b/src/component-families.ts @@ -250,6 +250,10 @@ export const componentFamilies = [ "id": "progress", "name": "Progress" }, + { + "id": "qr-code", + "name": "QrCode" + }, { "id": "radio", "name": "Radio" @@ -258,6 +262,10 @@ export const componentFamilies = [ "id": "scroll-area", "name": "ScrollArea" }, + { + "id": "scroll-horizontal", + "name": "ScrollHorizontal" + }, { "id": "select", "name": "Select" diff --git a/src/components/qr-code/QrCode.css b/src/components/qr-code/QrCode.css new file mode 100644 index 00000000..4c6c6a22 --- /dev/null +++ b/src/components/qr-code/QrCode.css @@ -0,0 +1,5 @@ +@layer components { + .qr-code { + display: block; + } +} diff --git a/src/components/qr-code/QrCode.layout.tsx b/src/components/qr-code/QrCode.layout.tsx new file mode 100644 index 00000000..600a0577 --- /dev/null +++ b/src/components/qr-code/QrCode.layout.tsx @@ -0,0 +1,87 @@ +import "./QrCode.css"; +import type { JSX } from "@solidjs/web"; +import { createMemo } from "solid-js"; +import type { Layout } from "../../lib/layouts"; +import type { QrErrorCorrectionLevel } from "../../lib/qr/qrMatrix"; +import { qrMatrix } from "../../lib/qr/qrMatrix"; +import type { UIBaseProps } from "../vocabulary"; +import { componentRecipe } from "./QrCode.recipe"; + +export type QrCodeProps = Omit< + JSX.SvgSVGAttributes, + | "aria-label" + | "aria-labelledby" + | "children" + | "height" + | "role" + | "title" + | "viewBox" + | "width" +> & + UIBaseProps & { + /** The text encoded into the QR matrix. */ + value: string; + /** Accessible name for the QR image. */ + title: string; + /** Reed-Solomon error correction level. Defaults to M. */ + level?: QrErrorCorrectionLevel; + /** Rendered square size in CSS pixels or another CSS length. */ + size?: number | string; + }; + +function matrixPath(matrix: boolean[][]): string { + const path: string[] = []; + + for (let row = 0; row < matrix.length; row++) { + let column = 0; + while (column < matrix[row].length) { + if (!matrix[row][column]) { + column++; + continue; + } + + const start = column; + while (column < matrix[row].length && matrix[row][column]) column++; + const x = start + 4; + const y = row + 4; + path.push(`M${x} ${y}h${column - start}v1h-${column - start}z`); + } + } + + return path.join(""); +} + +const QrCodeLayout: Layout = () => { + const matrix = createMemo(() => qrMatrix(local.value, local.level ?? "M")); + const path = createMemo(() => matrixPath(matrix())); + const viewBox = () => { + const size = matrix().length + 8; + return `0 0 ${size} ${size}`; + }; + + return ( + + {local.title} + + + ); +}; + +export default QrCodeLayout; +export { QrCodeLayout as QrCode }; diff --git a/src/components/qr-code/QrCode.recipe.ts b/src/components/qr-code/QrCode.recipe.ts new file mode 100644 index 00000000..24c750c6 --- /dev/null +++ b/src/components/qr-code/QrCode.recipe.ts @@ -0,0 +1,12 @@ +import { recipe } from "../../lib/layouts"; + +export const componentRecipe = recipe({ + component: "qr-code", + element: "svg", + slots: { + root: { base: "qr-code" }, + modules: { base: "qr-code__modules" }, + "qr-code": {}, + "qr-code-modules": {}, + }, +}); diff --git a/src/components/qr-code/index.ts b/src/components/qr-code/index.ts new file mode 100644 index 00000000..910b2734 --- /dev/null +++ b/src/components/qr-code/index.ts @@ -0,0 +1,9 @@ +export { + type QrErrorCorrectionLevel, + qrMatrix, +} from "../../lib/qr/qrMatrix"; +export { + default, + QrCode, + type QrCodeProps, +} from "./QrCode.generated"; diff --git a/src/components/scroll-horizontal/ScrollHorizontal.css b/src/components/scroll-horizontal/ScrollHorizontal.css new file mode 100644 index 00000000..8dfed34d --- /dev/null +++ b/src/components/scroll-horizontal/ScrollHorizontal.css @@ -0,0 +1,100 @@ +@layer components { + .scroll-horizontal { + display: block; + width: 100%; + } + + .scroll-horizontal[data-scroll-ready="true"] { + height: var(--scroll-horizontal-section-height, auto); + } + + .scroll-horizontal__viewport { + align-items: center; + display: flex; + max-width: 100%; + overflow-x: auto; + overflow-y: hidden; + } + + .scroll-horizontal__track { + align-items: stretch; + display: flex; + flex: 0 0 auto; + gap: var(--scroll-horizontal-mobile-gap, 15px); + min-width: 100%; + width: max-content; + } + + .scroll-horizontal__track > * { + box-sizing: border-box; + flex: 0 0 var(--scroll-horizontal-mobile-item-width, 280px); + min-width: 0; + width: var(--scroll-horizontal-mobile-item-width, 280px); + } + + .scroll-horizontal[data-scroll-ready="true"] .scroll-horizontal__viewport { + height: 100vh; + overflow: hidden; + position: sticky; + top: 0; + } + + @media (min-width: 768px) { + .scroll-horizontal__track { + gap: var(--scroll-horizontal-gap, 30px); + } + + .scroll-horizontal__track > * { + flex-basis: var(--scroll-horizontal-item-width, 400px); + width: var(--scroll-horizontal-item-width, 400px); + } + } + + @supports (view-timeline-name: --scroll-horizontal) and + (view-timeline-axis: block) and + (animation-timeline: --scroll-horizontal) and + (animation-range: contain 0% contain 100%) { + .scroll-horizontal[data-scroll-ready="true"][data-scroll-native="true"] { + view-timeline-axis: block; + view-timeline-name: --scroll-horizontal; + } + + .scroll-horizontal[data-scroll-ready="true"][data-scroll-native="true"] + .scroll-horizontal__track { + animation: scroll-horizontal-track linear both; + animation-timeline: --scroll-horizontal; + animation-range-start: contain 0%; + animation-range-end: contain 100%; + } + } + + @media (prefers-reduced-motion: reduce) { + .scroll-horizontal[data-scroll-ready="true"] { + height: auto; + } + + .scroll-horizontal[data-scroll-ready="true"] .scroll-horizontal__viewport { + height: auto; + min-height: 0; + overflow-x: auto; + overflow-y: hidden; + position: relative; + top: auto; + } + + .scroll-horizontal[data-scroll-ready="true"] .scroll-horizontal__track { + animation: none; + transform: none; + } + } + + @keyframes scroll-horizontal-track { + from { + transform: translateX(0); + } + + to { + transform: translateX(calc(0px - var(--scroll-horizontal-travel, 0px))); + } + } +} diff --git a/src/components/scroll-horizontal/ScrollHorizontal.layout.tsx b/src/components/scroll-horizontal/ScrollHorizontal.layout.tsx new file mode 100644 index 00000000..623a17d6 --- /dev/null +++ b/src/components/scroll-horizontal/ScrollHorizontal.layout.tsx @@ -0,0 +1,428 @@ +import "./ScrollHorizontal.css"; +import type { JSX } from "@solidjs/web"; +import { + type Component, + createMemo, + createSignal, + omit, + onCleanup, + onSettled, + Show, +} from "solid-js"; +import type { Layout } from "../../lib/layouts"; +import { + attachScrollProgress, + supportsViewTimeline, + type ScrollProgressBinding as ScrollProgressHandle, +} from "../../motion/scroll-progress"; +import type { UIBaseProps } from "../vocabulary"; +import { componentRecipe } from "./ScrollHorizontal.recipe"; + +export type ScrollHorizontalProps = UIBaseProps & + Omit, "class" | "style" | "height"> & { + itemWidth?: number; + mobileItemWidth?: number; + gap?: number; + mobileGap?: number; + height?: number | string; + }; + +const ScrollProgressBinding: Component<{ + target: () => HTMLElement | undefined; + onProgress: (progress: number) => void; + onDispose: () => void; +}> = (props) => { + let binding: ScrollProgressHandle | undefined; + + onSettled(() => { + binding?.cleanup(); + const section = props.target(); + binding = section + ? attachScrollProgress(section, { onProgress: props.onProgress }) + : undefined; + }); + + onCleanup(() => { + binding?.cleanup(); + binding = undefined; + props.onDispose(); + }); + + return null; +}; + +type ScrollLayoutResizeObserver = Pick; +type ScrollLayoutResizeObserverConstructor = new ( + callback: ResizeObserverCallback, +) => ScrollLayoutResizeObserver; + +const getScrollLayoutResizeObserver = + (): ScrollLayoutResizeObserverConstructor | undefined => { + const observerConstructor = ( + window as Window & { + ResizeObserver?: ScrollLayoutResizeObserverConstructor; + } + ).ResizeObserver; + return typeof observerConstructor === "function" + ? observerConstructor + : undefined; + }; + +const ScrollHorizontal: Layout< + typeof componentRecipe, + ScrollHorizontalProps +> = () => { + const others = omit( + local, + "children", + "class", + "dataTheme", + "style", + "itemWidth", + "mobileItemWidth", + "gap", + "mobileGap", + "height", + "ref", + "onFocusIn", + "tabIndex", + "aria-label", + "aria-labelledby", + "role", + ); + + let sectionRef: HTMLElement | undefined; + let viewportRef: HTMLElement | undefined; + let trackRef: HTMLDivElement | undefined; + let prefersReducedMotion = false; + + const [travel, setTravel] = createSignal(0); + const [measuredHeight, setMeasuredHeight] = createSignal("auto"); + const [ready, setReady] = createSignal(false); + const [nativeTimeline, setNativeTimeline] = createSignal(false); + let fallbackProgress = 0; + + const asPixels = (value: number): string => + `${Math.max(0, Number.isFinite(value) ? value : 0)}px`; + + const clearFallbackTrackTransform = () => { + if (!trackRef) return; + try { + trackRef.style.removeProperty("transform"); + } catch { + // The track may already be detached. + } + }; + + const writeFallbackTrackTransform = (progress?: number) => { + if (progress !== undefined) fallbackProgress = progress; + if (!trackRef) return; + if (prefersReducedMotion || nativeTimeline() || !ready()) { + clearFallbackTrackTransform(); + return; + } + + const distance = travel(); + const offset = + Number.isFinite(distance) && Number.isFinite(fallbackProgress) + ? -(distance * fallbackProgress) + : 0; + try { + trackRef.style.transform = `translateX(${offset}px)`; + } catch { + // Inline transform is the fallback paint path; keep scroll handling. + } + }; + + const asLength = (value: number | string): string => + typeof value === "number" ? asPixels(value) : value; + + const style = createMemo( + () => + ({ + ...(local.style ?? {}), + "--scroll-horizontal-item-width": asPixels(local.itemWidth ?? 400), + "--scroll-horizontal-mobile-item-width": asPixels( + local.mobileItemWidth ?? 280, + ), + "--scroll-horizontal-gap": asPixels(local.gap ?? 30), + "--scroll-horizontal-mobile-gap": asPixels(local.mobileGap ?? 15), + "--scroll-horizontal-travel": asPixels(travel()), + "--scroll-horizontal-section-height": + local.height === undefined || local.height === "auto" + ? measuredHeight() + : asLength(local.height), + }) as JSX.CSSProperties, + ); + + const measure = (): boolean => { + if (!sectionRef || !viewportRef || !trackRef) return false; + + const rowWidth = trackRef.scrollWidth; + const viewportWidth = viewportRef.clientWidth; + const viewportHeight = window.innerHeight; + if ( + !Number.isFinite(rowWidth) || + !Number.isFinite(viewportWidth) || + !Number.isFinite(viewportHeight) || + viewportWidth <= 0 || + viewportHeight <= 0 + ) { + return false; + } + + const nextTravel = Math.max(0, rowWidth - viewportWidth); + const nextHeight = + local.height === undefined || local.height === "auto" + ? `${viewportHeight + nextTravel}px` + : asLength(local.height); + + try { + sectionRef.style.setProperty( + "--scroll-horizontal-travel", + asPixels(nextTravel), + ); + sectionRef.style.setProperty( + "--scroll-horizontal-section-height", + nextHeight, + ); + } catch { + return false; + } + + setTravel((current) => (current === nextTravel ? current : nextTravel)); + + if (local.height === undefined || local.height === "auto") { + setMeasuredHeight((current) => + current === nextHeight ? current : nextHeight, + ); + } + + return true; + }; + + const handleFocusIn: JSX.EventHandlerUnion = ( + event, + ) => { + if ( + !prefersReducedMotion && + ready() && + sectionRef && + viewportRef && + trackRef && + event.target instanceof globalThis.HTMLElement && + trackRef.contains(event.target) + ) { + const focusTarget = event.target; + let item: HTMLElement = focusTarget; + + while (item.parentElement && item.parentElement !== trackRef) { + item = item.parentElement; + } + + if (item.parentElement === trackRef) { + const focusRect = focusTarget.getBoundingClientRect(); + const viewportRect = viewportRef.getBoundingClientRect(); + const visibleWidth = viewportRef.clientWidth; + const itemLeft = focusRect.left - viewportRect.left; + const itemRight = focusRect.right - viewportRect.left; + + const clipsLeft = itemLeft < 0; + const clipsRight = itemRight > visibleWidth; + + if (focusRect.width > 0 && (clipsLeft || clipsRight)) { + const sectionRect = sectionRef.getBoundingClientRect(); + const viewportHeight = window.innerHeight; + const sectionRange = Math.max(0, sectionRect.height - viewportHeight); + const horizontalTravel = travel(); + + if (sectionRange > 0 && horizontalTravel > 0) { + const currentProgress = Math.max( + 0, + Math.min(1, -sectionRect.top / sectionRange), + ); + const offsetAtStart = horizontalTravel * currentProgress; + const itemLeftAtStart = itemLeft + offsetAtStart; + const itemRightAtStart = itemRight + offsetAtStart; + const nextProgress = Math.max( + 0, + Math.min( + 1, + itemRight <= 0 + ? itemRightAtStart / horizontalTravel + : clipsLeft + ? itemLeftAtStart / horizontalTravel + : (itemRightAtStart - visibleWidth) / horizontalTravel, + ), + ); + const sectionTop = sectionRect.top + window.scrollY; + + window.scrollTo({ + top: sectionTop + nextProgress * sectionRange, + behavior: "auto", + }); + } + } + } + } + + if (typeof local.onFocusIn === "function") local.onFocusIn(event); + }; + + onSettled(() => { + setNativeTimeline(supportsViewTimeline()); + + const mediaQuery = + typeof window.matchMedia === "function" + ? window.matchMedia("(prefers-reduced-motion: reduce)") + : undefined; + const maxInitialRetries = 3; + let initialRetriesRemaining = maxInitialRetries; + let active = true; + let pendingFrame: number | undefined; + let retryPending = false; + let layoutObserver: ScrollLayoutResizeObserver | undefined; + + const cancelScheduledMeasure = () => { + if (pendingFrame !== undefined) { + window.cancelAnimationFrame(pendingFrame); + pendingFrame = undefined; + } + retryPending = false; + }; + + const scheduleMeasure = (retryIfUnavailable = false) => { + if (!active || prefersReducedMotion) return; + retryPending ||= retryIfUnavailable; + if (pendingFrame !== undefined) return; + + pendingFrame = window.requestAnimationFrame(() => { + pendingFrame = undefined; + const shouldRetry = retryPending; + retryPending = false; + if (!active || prefersReducedMotion) return; + + const measured = measure(); + setReady(measured); + writeFallbackTrackTransform(); + if (measured) { + initialRetriesRemaining = maxInitialRetries; + return; + } + + if (shouldRetry && initialRetriesRemaining > 0) { + initialRetriesRemaining -= 1; + scheduleMeasure(true); + } + }); + }; + + const applyMotionPreference = () => { + prefersReducedMotion = mediaQuery?.matches ?? false; + + if (prefersReducedMotion) { + cancelScheduledMeasure(); + setReady(false); + clearFallbackTrackTransform(); + return; + } + + initialRetriesRemaining = maxInitialRetries; + scheduleMeasure(true); + }; + + const handleResize = () => { + if (prefersReducedMotion) return; + scheduleMeasure(); + }; + + window.addEventListener("resize", handleResize, { passive: true }); + mediaQuery?.addEventListener?.("change", applyMotionPreference); + if (mediaQuery && !mediaQuery.addEventListener) { + mediaQuery.addListener(applyMotionPreference); + } + + const ResizeObserverConstructor = getScrollLayoutResizeObserver(); + if (ResizeObserverConstructor && viewportRef && trackRef) { + try { + layoutObserver = new ResizeObserverConstructor(handleResize); + layoutObserver.observe(viewportRef); + layoutObserver.observe(trackRef); + } catch { + layoutObserver?.disconnect(); + layoutObserver = undefined; + } + } + + // Bounded frame retries handle late initial layout when ResizeObserver is + // unavailable; observer notifications cover delayed and later resizes. + applyMotionPreference(); + + return () => { + active = false; + cancelScheduledMeasure(); + layoutObserver?.disconnect(); + window.removeEventListener("resize", handleResize); + mediaQuery?.removeEventListener?.("change", applyMotionPreference); + if (mediaQuery && !mediaQuery.removeEventListener) { + mediaQuery.removeListener(applyMotionPreference); + } + }; + }); + + return ( +
{ + sectionRef = el; + if (typeof local.ref === "function") local.ref(el); + }} + data-theme={local.dataTheme} + data-scroll-ready={ready() ? "true" : undefined} + data-scroll-native={nativeTimeline() ? "true" : undefined} + style={style()} + onFocusIn={handleFocusIn} + role={typeof local.role === "string" ? local.role : "group"} + aria-label={undefined} + aria-labelledby={undefined} + > + + sectionRef} + onProgress={writeFallbackTrackTransform} + onDispose={clearFallbackTrackTransform} + /> + +
{ + viewportRef = el; + }} + {...slot.viewport} + role="region" + aria-label={ + typeof local["aria-label"] === "string" + ? local["aria-label"] + : "Scrollable content" + } + aria-labelledby={ + typeof local["aria-labelledby"] === "string" + ? local["aria-labelledby"] + : undefined + } + tabindex={typeof local.tabIndex === "number" ? local.tabIndex : 0} + > +
{ + trackRef = el; + }} + {...slot.track} + > + {children} +
+
+
+ ); +}; + +export default ScrollHorizontal; diff --git a/src/components/scroll-horizontal/ScrollHorizontal.recipe.ts b/src/components/scroll-horizontal/ScrollHorizontal.recipe.ts new file mode 100644 index 00000000..e89cd0ea --- /dev/null +++ b/src/components/scroll-horizontal/ScrollHorizontal.recipe.ts @@ -0,0 +1,10 @@ +import { recipe } from "../../lib/layouts"; + +export const componentRecipe = recipe({ + component: "scroll-horizontal", + slots: { + root: { base: "scroll-horizontal" }, + viewport: { base: "scroll-horizontal__viewport" }, + track: { base: "scroll-horizontal__track" }, + }, +}); diff --git a/src/components/scroll-horizontal/index.ts b/src/components/scroll-horizontal/index.ts new file mode 100644 index 00000000..70e6ef99 --- /dev/null +++ b/src/components/scroll-horizontal/index.ts @@ -0,0 +1,4 @@ +export { + default, + type ScrollHorizontalProps, +} from "./ScrollHorizontal.generated"; diff --git a/src/index.ts b/src/index.ts index 2770998a..18109116 100644 --- a/src/index.ts +++ b/src/index.ts @@ -243,7 +243,11 @@ export { FieldsetLegend, } from "./components/fieldset"; export { default as Flex } from "./components/flex"; -export type { CreateFlexGridOptions, FlexGridModel, FlexGridProps } from "./components/flex-grid"; +export type { + CreateFlexGridOptions, + FlexGridModel, + FlexGridProps, +} from "./components/flex-grid"; export { createFlexGrid, default as FlexGrid } from "./components/flex-grid"; export type { FooterProps, FooterTitleProps } from "./components/footer"; export { default as Footer } from "./components/footer"; @@ -407,6 +411,8 @@ export type { ProgressSize, } from "./components/progress"; export { default as Progress } from "./components/progress"; +export type { QrCodeProps, QrErrorCorrectionLevel } from "./components/qr-code"; +export { default as QrCode, qrMatrix } from "./components/qr-code"; export { default as Radio } from "./components/radio"; export { RadioGroup, @@ -421,6 +427,8 @@ export type { ScrollAreaVisibility, } from "./components/scroll-area"; export { default as ScrollArea } from "./components/scroll-area"; +export type { ScrollHorizontalProps } from "./components/scroll-horizontal"; +export { default as ScrollHorizontal } from "./components/scroll-horizontal"; export { default as Select } from "./components/select"; export type { SeparatorOrientation, @@ -650,6 +658,8 @@ export { useAnchoredOverlayPosition } from "./hooks/table"; export * from "./motion"; export { evaluatePasswordRules, + isPrintableAsciiPassword, + PASSWORD_CHARSET_MESSAGE, matchPasswordConfirmation, type PasswordCustomRegexRule, type PasswordRuleConfig, diff --git a/src/lib/qr/qrMatrix.ts b/src/lib/qr/qrMatrix.ts new file mode 100644 index 00000000..56d52b85 --- /dev/null +++ b/src/lib/qr/qrMatrix.ts @@ -0,0 +1,888 @@ +/* + * QR Code encoder based on QRCode for JavaScript by davidshimjs and + * Kazuhiko Arase. + * + * Copyright (c) 2009 Kazuhiko Arase + * Copyright (c) davidshimjs + * + * Licensed under the MIT License. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +export type QrErrorCorrectionLevel = "L" | "M" | "Q" | "H"; + +const BYTE_MODE = 1 << 2; +const ERROR_CORRECTION_FORMAT_BITS: Record = { + L: 1, + M: 0, + Q: 3, + H: 2, +}; +const ERROR_CORRECTION_TABLE_INDEX: Record = { + L: 0, + M: 1, + Q: 2, + H: 3, +}; + +class QR8bitByte { + readonly mode = BYTE_MODE; + + readonly data: number[]; + + constructor(value: string) { + this.data = Array.from(new TextEncoder().encode(value)); + + // The source encoder prefixes UTF-8 data with a BOM so scanners can + // identify its byte encoding. Keep that behavior for non-ASCII strings. + if (this.data.length !== value.length) { + this.data.unshift(0xef, 0xbb, 0xbf); + } + } + + getLength(): number { + return this.data.length; + } + + write(buffer: QRBitBuffer): void { + for (const byte of this.data) buffer.put(byte, 8); + } +} + +class QRBitBuffer { + readonly buffer: number[] = []; + + length = 0; + + getLengthInBits(): number { + return this.length; + } + + put(value: number, length: number): void { + for (let index = 0; index < length; index++) { + this.putBit(((value >>> (length - index - 1)) & 1) === 1); + } + } + + putBit(bit: boolean): void { + const byteIndex = Math.floor(this.length / 8); + if (this.buffer.length <= byteIndex) this.buffer.push(0); + if (bit) this.buffer[byteIndex] |= 0x80 >>> (this.length % 8); + this.length++; + } +} + +const EXP_TABLE = new Array(256); +const LOG_TABLE = new Array(256); + +for (let index = 0; index < 8; index++) EXP_TABLE[index] = 1 << index; +for (let index = 8; index < 256; index++) { + EXP_TABLE[index] = + EXP_TABLE[index - 4] ^ + EXP_TABLE[index - 5] ^ + EXP_TABLE[index - 6] ^ + EXP_TABLE[index - 8]; +} +for (let index = 0; index < 255; index++) { + LOG_TABLE[EXP_TABLE[index]] = index; +} + +const QRMath = { + glog(value: number): number { + if (value < 1) throw new Error(`glog(${value})`); + return LOG_TABLE[value]; + }, + + gexp(value: number): number { + let exponent = value; + while (exponent < 0) exponent += 255; + while (exponent >= 256) exponent -= 255; + return EXP_TABLE[exponent]; + }, +}; + +class QRPolynomial { + readonly num: number[]; + + constructor(values: number[], shift: number) { + let offset = 0; + while (offset < values.length && values[offset] === 0) offset++; + this.num = [...values.slice(offset), ...new Array(shift).fill(0)]; + } + + get(index: number): number { + return this.num[index]; + } + + getLength(): number { + return this.num.length; + } + + multiply(other: QRPolynomial): QRPolynomial { + const values = new Array( + this.getLength() + other.getLength() - 1, + ).fill(0); + for (let left = 0; left < this.getLength(); left++) { + for (let right = 0; right < other.getLength(); right++) { + values[left + right] ^= QRMath.gexp( + QRMath.glog(this.get(left)) + QRMath.glog(other.get(right)), + ); + } + } + return new QRPolynomial(values, 0); + } + + mod(other: QRPolynomial): QRPolynomial { + if (this.getLength() < other.getLength()) return this; + + const ratio = QRMath.glog(this.get(0)) - QRMath.glog(other.get(0)); + const values = this.num.slice(); + for (let index = 0; index < other.getLength(); index++) { + values[index] ^= QRMath.gexp(QRMath.glog(other.get(index)) + ratio); + } + return new QRPolynomial(values, 0).mod(other); + } +} + +class QRRSBlock { + constructor( + readonly totalCount: number, + readonly dataCount: number, + ) {} + + static readonly RS_BLOCK_TABLE: readonly (readonly number[])[] = [ + [1, 26, 19], + [1, 26, 16], + [1, 26, 13], + [1, 26, 9], + [1, 44, 34], + [1, 44, 28], + [1, 44, 22], + [1, 44, 16], + [1, 70, 55], + [1, 70, 44], + [2, 35, 17], + [2, 35, 13], + [1, 100, 80], + [2, 50, 32], + [2, 50, 24], + [4, 25, 9], + [1, 134, 108], + [2, 67, 43], + [2, 33, 15, 2, 34, 16], + [2, 33, 11, 2, 34, 12], + [2, 86, 68], + [4, 43, 27], + [4, 43, 19], + [4, 43, 15], + [2, 98, 78], + [4, 49, 31], + [2, 32, 14, 4, 33, 15], + [4, 39, 13, 1, 40, 14], + [2, 121, 97], + [2, 60, 38, 2, 61, 39], + [4, 40, 18, 2, 41, 19], + [4, 40, 14, 2, 41, 15], + [2, 146, 116], + [3, 58, 36, 2, 59, 37], + [4, 36, 16, 4, 37, 17], + [4, 36, 12, 4, 37, 13], + [2, 86, 68, 2, 87, 69], + [4, 69, 43, 1, 70, 44], + [6, 43, 19, 2, 44, 20], + [6, 43, 15, 2, 44, 16], + [4, 101, 81], + [1, 80, 50, 4, 81, 51], + [4, 50, 22, 4, 51, 23], + [3, 36, 12, 8, 37, 13], + [2, 116, 92, 2, 117, 93], + [6, 58, 36, 2, 59, 37], + [4, 46, 20, 6, 47, 21], + [7, 42, 14, 4, 43, 15], + [4, 133, 107], + [8, 59, 37, 1, 60, 38], + [8, 44, 20, 4, 45, 21], + [12, 33, 11, 4, 34, 12], + [3, 145, 115, 1, 146, 116], + [4, 64, 40, 5, 65, 41], + [11, 36, 16, 5, 37, 17], + [11, 36, 12, 5, 37, 13], + [5, 109, 87, 1, 110, 88], + [5, 65, 41, 5, 66, 42], + [5, 54, 24, 7, 55, 25], + [11, 36, 12], + [5, 122, 98, 1, 123, 99], + [7, 73, 45, 3, 74, 46], + [15, 43, 19, 2, 44, 20], + [3, 45, 15, 13, 46, 16], + [1, 135, 107, 5, 136, 108], + [10, 74, 46, 1, 75, 47], + [1, 50, 22, 15, 51, 23], + [2, 42, 14, 17, 43, 15], + [5, 150, 120, 1, 151, 121], + [9, 69, 43, 4, 70, 44], + [17, 50, 22, 1, 51, 23], + [2, 42, 14, 19, 43, 15], + [3, 141, 113, 4, 142, 114], + [3, 70, 44, 11, 71, 45], + [17, 47, 21, 4, 48, 22], + [9, 39, 13, 16, 40, 14], + [3, 135, 107, 5, 136, 108], + [3, 67, 41, 13, 68, 42], + [15, 54, 24, 5, 55, 25], + [15, 43, 15, 10, 44, 16], + [4, 144, 116, 4, 145, 117], + [17, 68, 42], + [17, 50, 22, 6, 51, 23], + [19, 46, 16, 6, 47, 17], + [2, 139, 111, 7, 140, 112], + [17, 74, 46], + [7, 54, 24, 16, 55, 25], + [34, 37, 13], + [4, 151, 121, 5, 152, 122], + [4, 75, 47, 14, 76, 48], + [11, 54, 24, 14, 55, 25], + [16, 45, 15, 14, 46, 16], + [6, 147, 117, 4, 148, 118], + [6, 73, 45, 14, 74, 46], + [11, 54, 24, 16, 55, 25], + [30, 46, 16, 2, 47, 17], + [8, 132, 106, 4, 133, 107], + [8, 75, 47, 13, 76, 48], + [7, 54, 24, 22, 55, 25], + [22, 45, 15, 13, 46, 16], + [10, 142, 114, 2, 143, 115], + [19, 74, 46, 4, 75, 47], + [28, 50, 22, 6, 51, 23], + [33, 46, 16, 4, 47, 17], + [8, 152, 122, 4, 153, 123], + [22, 73, 45, 3, 74, 46], + [8, 53, 23, 26, 54, 24], + [12, 45, 15, 28, 46, 16], + [3, 147, 117, 10, 148, 118], + [3, 73, 45, 23, 74, 46], + [4, 54, 24, 31, 55, 25], + [11, 45, 15, 31, 46, 16], + [7, 146, 116, 7, 147, 117], + [21, 73, 45, 7, 74, 46], + [1, 53, 23, 37, 54, 24], + [19, 45, 15, 26, 46, 16], + [5, 145, 115, 10, 146, 116], + [19, 75, 47, 10, 76, 48], + [15, 54, 24, 25, 55, 25], + [23, 45, 15, 25, 46, 16], + [13, 145, 115, 3, 146, 116], + [2, 74, 46, 29, 75, 47], + [42, 54, 24, 1, 55, 25], + [23, 45, 15, 28, 46, 16], + [17, 145, 115], + [10, 74, 46, 23, 75, 47], + [10, 54, 24, 35, 55, 25], + [19, 45, 15, 35, 46, 16], + [17, 145, 115, 1, 146, 116], + [14, 74, 46, 21, 75, 47], + [29, 54, 24, 19, 55, 25], + [11, 45, 15, 46, 46, 16], + [13, 145, 115, 6, 146, 116], + [14, 74, 46, 23, 75, 47], + [44, 54, 24, 7, 55, 25], + [59, 46, 16, 1, 47, 17], + [12, 151, 121, 7, 152, 122], + [12, 75, 47, 26, 76, 48], + [39, 54, 24, 14, 55, 25], + [22, 45, 15, 41, 46, 16], + [6, 151, 121, 14, 152, 122], + [6, 75, 47, 34, 76, 48], + [46, 54, 24, 10, 55, 25], + [2, 45, 15, 64, 46, 16], + [17, 152, 122, 4, 153, 123], + [29, 74, 46, 14, 75, 47], + [49, 54, 24, 10, 55, 25], + [24, 45, 15, 46, 46, 16], + [4, 152, 122, 18, 153, 123], + [13, 74, 46, 32, 75, 47], + [48, 54, 24, 14, 55, 25], + [42, 45, 15, 32, 46, 16], + [20, 147, 117, 4, 148, 118], + [40, 75, 47, 7, 76, 48], + [43, 54, 24, 22, 55, 25], + [10, 45, 15, 67, 46, 16], + [19, 148, 118, 6, 149, 119], + [18, 75, 47, 31, 76, 48], + [34, 54, 24, 34, 55, 25], + [20, 45, 15, 61, 46, 16], + ]; + + static getRSBlocks( + typeNumber: number, + level: QrErrorCorrectionLevel, + ): QRRSBlock[] { + const table = + QRRSBlock.RS_BLOCK_TABLE[ + (typeNumber - 1) * 4 + ERROR_CORRECTION_TABLE_INDEX[level] + ]; + if (!table) throw new Error(`bad RS block for type ${typeNumber}`); + + const blocks: QRRSBlock[] = []; + for (let index = 0; index < table.length; index += 3) { + const count = table[index]; + const totalCount = table[index + 1]; + const dataCount = table[index + 2]; + for (let block = 0; block < count; block++) { + blocks.push(new QRRSBlock(totalCount, dataCount)); + } + } + return blocks; + } +} + +const PATTERN_POSITION_TABLE: readonly (readonly number[])[] = [ + [], + [6, 18], + [6, 22], + [6, 26], + [6, 30], + [6, 34], + [6, 22, 38], + [6, 24, 42], + [6, 26, 46], + [6, 28, 50], + [6, 30, 54], + [6, 32, 58], + [6, 34, 62], + [6, 26, 46, 66], + [6, 26, 48, 70], + [6, 26, 50, 74], + [6, 30, 54, 78], + [6, 30, 56, 82], + [6, 30, 58, 86], + [6, 34, 62, 90], + [6, 28, 50, 72, 94], + [6, 26, 50, 74, 98], + [6, 30, 54, 78, 102], + [6, 28, 54, 80, 106], + [6, 32, 58, 84, 110], + [6, 30, 58, 86, 114], + [6, 34, 62, 90, 118], + [6, 26, 50, 74, 98, 122], + [6, 30, 54, 78, 102, 126], + [6, 26, 52, 78, 104, 130], + [6, 30, 56, 82, 108, 134], + [6, 34, 60, 86, 112, 138], + [6, 30, 58, 86, 114, 142], + [6, 34, 62, 90, 118, 146], + [6, 30, 54, 78, 102, 126, 150], + [6, 24, 50, 76, 102, 128, 154], + [6, 28, 54, 80, 106, 132, 158], + [6, 32, 58, 84, 110, 136, 162], + [6, 26, 54, 82, 110, 138, 166], + [6, 30, 58, 86, 114, 142, 170], +]; + +const QRUtil: { + G15: number; + G18: number; + G15_MASK: number; + getBCHTypeInfo(data: number): number; + getBCHTypeNumber(data: number): number; + getBCHDigit(value: number): number; + getPatternPosition(typeNumber: number): readonly number[]; + getMask(maskPattern: number, row: number, column: number): boolean; + getErrorCorrectPolynomial(errorCorrectLength: number): QRPolynomial; + getLengthInBits(typeNumber: number): number; + getLostPoint(modules: readonly (readonly boolean[])[]): number; +} = { + G15: (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | 1, + + G18: + (1 << 12) | + (1 << 11) | + (1 << 10) | + (1 << 9) | + (1 << 8) | + (1 << 5) | + (1 << 2) | + 1, + + G15_MASK: (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1), + + getBCHTypeInfo(data: number): number { + let remainder = data << 10; + while ( + QRUtil.getBCHDigit(remainder) - QRUtil.getBCHDigit(QRUtil.G15) >= + 0 + ) { + remainder ^= + QRUtil.G15 << + (QRUtil.getBCHDigit(remainder) - QRUtil.getBCHDigit(QRUtil.G15)); + } + return ((data << 10) | remainder) ^ QRUtil.G15_MASK; + }, + + getBCHTypeNumber(data: number): number { + let remainder = data << 12; + while ( + QRUtil.getBCHDigit(remainder) - QRUtil.getBCHDigit(QRUtil.G18) >= + 0 + ) { + remainder ^= + QRUtil.G18 << + (QRUtil.getBCHDigit(remainder) - QRUtil.getBCHDigit(QRUtil.G18)); + } + return (data << 12) | remainder; + }, + + getBCHDigit(value: number): number { + let digit = 0; + let remaining = value; + while (remaining !== 0) { + digit++; + remaining >>>= 1; + } + return digit; + }, + + getPatternPosition(typeNumber: number): readonly number[] { + return PATTERN_POSITION_TABLE[typeNumber - 1]; + }, + + getMask(maskPattern: number, row: number, column: number): boolean { + switch (maskPattern) { + case 0: + return (row + column) % 2 === 0; + case 1: + return row % 2 === 0; + case 2: + return column % 3 === 0; + case 3: + return (row + column) % 3 === 0; + case 4: + return (Math.floor(row / 2) + Math.floor(column / 3)) % 2 === 0; + case 5: + return ((row * column) % 2) + ((row * column) % 3) === 0; + case 6: + return (((row * column) % 2) + ((row * column) % 3)) % 2 === 0; + case 7: + return (((row * column) % 3) + ((row + column) % 2)) % 2 === 0; + default: + throw new Error(`bad mask pattern: ${maskPattern}`); + } + }, + + getErrorCorrectPolynomial(errorCorrectLength: number): QRPolynomial { + let polynomial = new QRPolynomial([1], 0); + for (let index = 0; index < errorCorrectLength; index++) { + polynomial = polynomial.multiply( + new QRPolynomial([1, QRMath.gexp(index)], 0), + ); + } + return polynomial; + }, + + getLengthInBits(typeNumber: number): number { + if (typeNumber < 1 || typeNumber >= 41) { + throw new Error(`type: ${typeNumber}`); + } + return typeNumber < 10 ? 8 : 16; + }, + + getLostPoint(modules: readonly (readonly boolean[])[]): number { + const size = modules.length; + let lostPoint = 0; + + for (let row = 0; row < size; row++) { + for (let column = 0; column < size; column++) { + let sameCount = 0; + const dark = modules[row][column]; + for (let rowOffset = -1; rowOffset <= 1; rowOffset++) { + const neighborRow = row + rowOffset; + if (neighborRow < 0 || neighborRow >= size) continue; + for (let columnOffset = -1; columnOffset <= 1; columnOffset++) { + const neighborColumn = column + columnOffset; + if ( + (rowOffset === 0 && columnOffset === 0) || + neighborColumn < 0 || + neighborColumn >= size + ) { + continue; + } + if (dark === modules[neighborRow][neighborColumn]) sameCount++; + } + } + if (sameCount > 5) lostPoint += 3 + sameCount - 5; + } + } + + for (let row = 0; row < size - 1; row++) { + for (let column = 0; column < size - 1; column++) { + const darkCount = + Number(modules[row][column]) + + Number(modules[row + 1][column]) + + Number(modules[row][column + 1]) + + Number(modules[row + 1][column + 1]); + if (darkCount === 0 || darkCount === 4) lostPoint += 3; + } + } + + for (let row = 0; row < size; row++) { + for (let column = 0; column < size - 6; column++) { + if ( + modules[row][column] && + !modules[row][column + 1] && + modules[row][column + 2] && + modules[row][column + 3] && + modules[row][column + 4] && + !modules[row][column + 5] && + modules[row][column + 6] + ) { + lostPoint += 40; + } + } + } + for (let column = 0; column < size; column++) { + for (let row = 0; row < size - 6; row++) { + if ( + modules[row][column] && + !modules[row + 1][column] && + modules[row + 2][column] && + modules[row + 3][column] && + modules[row + 4][column] && + !modules[row + 5][column] && + modules[row + 6][column] + ) { + lostPoint += 40; + } + } + } + + let darkCount = 0; + for (const row of modules) { + for (const dark of row) if (dark) darkCount++; + } + const ratio = Math.abs((100 * darkCount) / (size * size) - 50) / 5; + return lostPoint + ratio * 10; + }, +}; + +class QRCodeModel { + private modules: (boolean | null)[][] = []; + + private readonly moduleCount: number; + + private readonly dataList: QR8bitByte[] = []; + + constructor( + private readonly typeNumber: number, + private readonly errorCorrectLevel: QrErrorCorrectionLevel, + ) { + this.moduleCount = typeNumber * 4 + 17; + this.dataList.push(new QR8bitByte("")); + } + + addData(data: QR8bitByte): void { + this.dataList[0] = data; + } + + make(): boolean[][] { + const data = QRCodeModel.createData( + this.typeNumber, + this.errorCorrectLevel, + this.dataList, + ); + const maskPattern = this.getBestMaskPattern(data); + this.makeImpl(false, maskPattern, data); + return this.modules.map((row) => row.map((module) => module === true)); + } + + private makeImpl( + test: boolean, + maskPattern: number, + data: readonly number[], + ): void { + this.modules = Array.from({ length: this.moduleCount }, () => + new Array(this.moduleCount).fill(null), + ); + this.setupPositionProbePattern(0, 0); + this.setupPositionProbePattern(this.moduleCount - 7, 0); + this.setupPositionProbePattern(0, this.moduleCount - 7); + this.setupPositionAdjustPattern(); + this.setupTimingPattern(); + this.setupTypeInfo(test, maskPattern); + if (this.typeNumber >= 7) this.setupTypeNumber(test); + this.mapData(data, maskPattern); + } + + private setupPositionProbePattern(row: number, column: number): void { + for (let rowOffset = -1; rowOffset <= 7; rowOffset++) { + const targetRow = row + rowOffset; + if (targetRow < 0 || targetRow >= this.moduleCount) continue; + for (let columnOffset = -1; columnOffset <= 7; columnOffset++) { + const targetColumn = column + columnOffset; + if (targetColumn < 0 || targetColumn >= this.moduleCount) continue; + this.modules[targetRow][targetColumn] = + (rowOffset >= 0 && + rowOffset <= 6 && + (columnOffset === 0 || columnOffset === 6)) || + (columnOffset >= 0 && + columnOffset <= 6 && + (rowOffset === 0 || rowOffset === 6)) || + (rowOffset >= 2 && + rowOffset <= 4 && + columnOffset >= 2 && + columnOffset <= 4); + } + } + } + + private setupPositionAdjustPattern(): void { + for (const row of QRUtil.getPatternPosition(this.typeNumber)) { + for (const column of QRUtil.getPatternPosition(this.typeNumber)) { + if (this.modules[row][column] !== null) continue; + for (let rowOffset = -2; rowOffset <= 2; rowOffset++) { + for (let columnOffset = -2; columnOffset <= 2; columnOffset++) { + this.modules[row + rowOffset][column + columnOffset] = + rowOffset === -2 || + rowOffset === 2 || + columnOffset === -2 || + columnOffset === 2 || + (rowOffset === 0 && columnOffset === 0); + } + } + } + } + } + + private setupTimingPattern(): void { + for (let row = 8; row < this.moduleCount - 8; row++) { + if (this.modules[row][6] !== null) continue; + this.modules[row][6] = row % 2 === 0; + } + for (let column = 8; column < this.moduleCount - 8; column++) { + if (this.modules[6][column] !== null) continue; + this.modules[6][column] = column % 2 === 0; + } + } + + private setupTypeNumber(test: boolean): void { + const bits = QRUtil.getBCHTypeNumber(this.typeNumber); + for (let index = 0; index < 18; index++) { + const dark = !test && ((bits >>> index) & 1) === 1; + this.modules[Math.floor(index / 3)][(index % 3) + this.moduleCount - 11] = + dark; + this.modules[(index % 3) + this.moduleCount - 11][Math.floor(index / 3)] = + dark; + } + } + + private setupTypeInfo(test: boolean, maskPattern: number): void { + const data = + (ERROR_CORRECTION_FORMAT_BITS[this.errorCorrectLevel] << 3) | maskPattern; + const bits = QRUtil.getBCHTypeInfo(data); + for (let index = 0; index < 15; index++) { + const dark = !test && ((bits >>> index) & 1) === 1; + if (index < 6) { + this.modules[index][8] = dark; + } else if (index < 8) { + this.modules[index + 1][8] = dark; + } else { + this.modules[this.moduleCount - 15 + index][8] = dark; + } + } + for (let index = 0; index < 15; index++) { + const dark = !test && ((bits >>> index) & 1) === 1; + if (index < 8) { + this.modules[8][this.moduleCount - index - 1] = dark; + } else if (index < 9) { + this.modules[8][15 - index] = dark; + } else { + this.modules[8][15 - index - 1] = dark; + } + } + this.modules[this.moduleCount - 8][8] = !test; + } + + private mapData(data: readonly number[], maskPattern: number): void { + let direction = -1; + let row = this.moduleCount - 1; + let bitIndex = 7; + let byteIndex = 0; + + for (let column = this.moduleCount - 1; column > 0; ) { + if (column === 6) column--; + const rightColumn = column; + while (true) { + for (let offset = 0; offset < 2; offset++) { + const targetColumn = rightColumn - offset; + if (this.modules[row][targetColumn] !== null) continue; + let dark = + byteIndex < data.length && + ((data[byteIndex] >>> bitIndex) & 1) === 1; + if (QRUtil.getMask(maskPattern, row, targetColumn)) dark = !dark; + this.modules[row][targetColumn] = dark; + bitIndex--; + if (bitIndex === -1) { + byteIndex++; + bitIndex = 7; + } + } + + row += direction; + if (row < 0 || row >= this.moduleCount) { + row -= direction; + direction = -direction; + break; + } + } + column -= 2; + } + } + + private getBestMaskPattern(data: readonly number[]): number { + let lowestPenalty = 0; + let bestPattern = 0; + for (let pattern = 0; pattern < 8; pattern++) { + this.makeImpl(true, pattern, data); + const penalty = QRUtil.getLostPoint( + this.modules.map((row) => row.map((module) => module === true)), + ); + if (pattern === 0 || lowestPenalty > penalty) { + lowestPenalty = penalty; + bestPattern = pattern; + } + } + return bestPattern; + } + + private static createData( + typeNumber: number, + errorCorrectLevel: QrErrorCorrectionLevel, + dataList: readonly QR8bitByte[], + ): number[] { + const rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel); + const buffer = new QRBitBuffer(); + for (const data of dataList) { + buffer.put(data.mode, 4); + buffer.put(data.getLength(), QRUtil.getLengthInBits(typeNumber)); + data.write(buffer); + } + + const totalDataCount = rsBlocks.reduce( + (total, block) => total + block.dataCount, + 0, + ); + const totalDataBits = totalDataCount * 8; + if (buffer.getLengthInBits() > totalDataBits) { + throw new Error( + `code length overflow (${buffer.getLengthInBits()}>${totalDataBits})`, + ); + } + if (buffer.getLengthInBits() + 4 <= totalDataBits) buffer.put(0, 4); + while (buffer.getLengthInBits() % 8 !== 0) buffer.putBit(false); + + while (buffer.getLengthInBits() < totalDataBits) { + buffer.put(0xec, 8); + if (buffer.getLengthInBits() < totalDataBits) buffer.put(0x11, 8); + } + return QRCodeModel.createBytes(buffer, rsBlocks); + } + + private static createBytes( + buffer: QRBitBuffer, + rsBlocks: readonly QRRSBlock[], + ): number[] { + let offset = 0; + let maxDataCount = 0; + let maxErrorCount = 0; + const dataBlocks: number[][] = []; + const errorBlocks: number[][] = []; + + for (let blockIndex = 0; blockIndex < rsBlocks.length; blockIndex++) { + const block = rsBlocks[blockIndex]; + const errorCount = block.totalCount - block.dataCount; + maxDataCount = Math.max(maxDataCount, block.dataCount); + maxErrorCount = Math.max(maxErrorCount, errorCount); + const data = buffer.buffer.slice(offset, offset + block.dataCount); + offset += block.dataCount; + dataBlocks.push(data); + + const errorPolynomial = QRUtil.getErrorCorrectPolynomial(errorCount); + const rawPolynomial = new QRPolynomial( + data, + errorPolynomial.getLength() - 1, + ); + const modPolynomial = rawPolynomial.mod(errorPolynomial); + const errorData = new Array(errorPolynomial.getLength() - 1); + for (let index = 0; index < errorData.length; index++) { + const modIndex = index + modPolynomial.getLength() - errorData.length; + errorData[index] = modIndex >= 0 ? modPolynomial.get(modIndex) : 0; + } + errorBlocks.push(errorData); + } + + const totalCodeCount = rsBlocks.reduce( + (total, block) => total + block.totalCount, + 0, + ); + const result: number[] = []; + for (let index = 0; index < maxDataCount; index++) { + for (const block of dataBlocks) { + if (index < block.length) result.push(block[index]); + } + } + for (let index = 0; index < maxErrorCount; index++) { + for (const block of errorBlocks) { + if (index < block.length) result.push(block[index]); + } + } + return result.slice(0, totalCodeCount); + } +} + +function getTypeNumber( + dataLength: number, + level: QrErrorCorrectionLevel, +): number { + for (let typeNumber = 1; typeNumber <= 40; typeNumber++) { + const lengthBits = QRUtil.getLengthInBits(typeNumber); + const headerBits = 4 + lengthBits; + if (dataLength >= 2 ** lengthBits) continue; + const totalDataCount = QRRSBlock.getRSBlocks(typeNumber, level).reduce( + (total, block) => total + block.dataCount, + 0, + ); + if (headerBits + dataLength * 8 <= totalDataCount * 8) return typeNumber; + } + throw new Error("Too long data"); +} + +/** Encode text into a QR matrix without touching the DOM. */ +export function qrMatrix( + text: string, + level: QrErrorCorrectionLevel = "M", +): boolean[][] { + if (!Object.hasOwn(ERROR_CORRECTION_FORMAT_BITS, level)) { + throw new RangeError(`Unsupported QR error correction level: ${level}`); + } + + const data = new QR8bitByte(text); + const typeNumber = getTypeNumber(data.getLength(), level); + const model = new QRCodeModel(typeNumber, level); + model.addData(data); + return model.make(); +} diff --git a/src/motion/WIRING.md b/src/motion/WIRING.md new file mode 100644 index 00000000..cbf8621e --- /dev/null +++ b/src/motion/WIRING.md @@ -0,0 +1,48 @@ +# Motion primitive exports + +These helpers are already exported from `src/motion/index.ts` and the +`@pathscale/ui/motion` package subpath. + +```ts +export { + createScrollProgress, + supportsViewTimeline, + type ScrollProgress, + type ScrollProgressOptions, + type ScrollProgressRange, +} from "./scroll-progress"; +export { + animateElement, + type AnimateElementOptions, + type ElementAnimation, +} from "./animate-element"; +export { createInView, type InViewOptions } from "./in-view"; +export { stagger } from "./stagger"; +export { springKeyframes, type SpringKeyframeOptions } from "./spring-keyframes"; +``` + +## Contracts + +- `createScrollProgress(() => section, { range: "start-start/end-end" })` returns a + Solid accessor, so read `progress()` for the current value. The helper writes + `--scroll-progress` on the section and restores its prior inline value on cleanup. + It installs browser listeners only after mount, measures section and viewport + heights on mount and resize, and samples section position at most once per animation + frame. The supported range maps the section top at viewport top to its bottom at + viewport bottom. `supportsViewTimeline()` checks named view timeline, block axis, + animation timeline, and the `contain 0%` through `contain 100%` attachment range used + by the CSS path. +- `animateElement(element, keyframes, options)` uses WAAPI when available and applies + the final keyframe immediately when it is unavailable. `duration` and `delay` follow + WAAPI milliseconds; the default duration comes from `motionDurations.base` and the + default easing comes from `motionEasings.out`. Its `finished` promise resolves on + completion or cancellation. Live reduced-motion changes finish the active animation. +- `createInView(() => element, options)` returns a Solid accessor. It starts visible, + remains visible when `IntersectionObserver` is unavailable, and disconnects after + the first intersection when `once` is true. +- `stagger(index, interval)` returns a nonnegative delay in milliseconds; the default + interval is 50 ms. +- `springKeyframes({ stiffness, damping, mass })` returns normalized numeric values + sampled at 60 Hz. Use the values for one property in `PropertyIndexedKeyframes` and + set the animation duration to `(values.length - 1) / 60 * 1000` ms to preserve the + sample rate. diff --git a/src/motion/animate-element.ts b/src/motion/animate-element.ts new file mode 100644 index 00000000..4b458cb9 --- /dev/null +++ b/src/motion/animate-element.ts @@ -0,0 +1,175 @@ +import { prefersReducedMotion } from "./reduced-motion"; +import { motionDurations, motionEasings } from "./tokens"; +import type { MotionEasing } from "./types"; + +export type AnimateElementOptions = Omit & { + /** CSS timing keywords; function easings are provided by the JS motion driver. */ + easing?: Exclude number>; + /** Finish at the final keyframe when the live reduced-motion setting turns on. */ + respectReducedMotion?: boolean; +}; + +export type ElementAnimation = { + cancel: () => void; + /** Resolves when the animation ends or is cancelled. */ + finished: Promise; +}; + +const isKeyframeMetadata = (property: string) => + property === "offset" || + property === "easing" || + property === "composite" || + property === "computedOffset"; + +const finalValue = (value: unknown) => { + if (Array.isArray(value)) { + for (let index = value.length - 1; index >= 0; index -= 1) { + if (value[index] !== null && value[index] !== undefined) + return value[index]; + } + return undefined; + } + return value; +}; + +const applyFinalKeyframe = ( + element: Element, + keyframes: Keyframe[] | PropertyIndexedKeyframes, +) => { + const style = (element as Element & { style?: CSSStyleDeclaration }).style; + if (!style) return; + + const finalValues = new Map(); + if (Array.isArray(keyframes)) { + for (let index = keyframes.length - 1; index >= 0; index -= 1) { + const frame = keyframes[index] as Keyframe & Record; + for (const [property, value] of Object.entries(frame)) { + if ( + !isKeyframeMetadata(property) && + !finalValues.has(property) && + value !== null && + value !== undefined + ) { + finalValues.set(property, value); + } + } + } + } else { + for (const [property, value] of Object.entries(keyframes)) { + if (!isKeyframeMetadata(property)) { + finalValues.set(property, finalValue(value)); + } + } + } + + for (const [property, value] of finalValues) { + if (value === null || value === undefined) continue; + const text = String(value); + if (property.startsWith("--") || property.includes("-")) { + style.setProperty(property, text); + } else { + (style as unknown as Record)[property] = text; + } + } +}; + +const createCompletedAnimation = (): ElementAnimation => ({ + cancel: () => {}, + finished: Promise.resolve(), +}); + +/** Animate an element with WAAPI, using the library's base timing tokens by default. */ +export const animateElement = ( + element: Element, + keyframes: Keyframe[] | PropertyIndexedKeyframes, + options: AnimateElementOptions = {}, +): ElementAnimation => { + const { + respectReducedMotion = true, + duration = motionDurations.base * 1000, + easing = motionEasings.out as Exclude number>, + ...timing + } = options; + + const animate = (element as Element & { animate?: Element["animate"] }) + .animate; + if ( + typeof animate !== "function" || + (respectReducedMotion && prefersReducedMotion()) + ) { + applyFinalKeyframe(element, keyframes); + return createCompletedAnimation(); + } + + let animation: Animation; + try { + animation = animate.call(element, keyframes, { + ...timing, + duration, + easing, + }); + } catch { + applyFinalKeyframe(element, keyframes); + return createCompletedAnimation(); + } + + let settled = false; + let resolveFinished: () => void = () => {}; + let removeMotionListener = () => {}; + const finished = new Promise((resolve) => { + resolveFinished = resolve; + }); + const settle = () => { + if (settled) return; + settled = true; + removeMotionListener(); + resolveFinished(); + }; + + let media: MediaQueryList | undefined; + if (respectReducedMotion && typeof globalThis.matchMedia === "function") { + try { + media = globalThis.matchMedia("(prefers-reduced-motion: reduce)"); + } catch { + media = undefined; + } + } + const handleMotionChange = (event: MediaQueryListEvent | MediaQueryList) => { + if (!event.matches || settled) return; + applyFinalKeyframe(element, keyframes); + animation.cancel(); + settle(); + }; + removeMotionListener = () => { + if (!media) return; + if (typeof media.removeEventListener === "function") { + media.removeEventListener("change", handleMotionChange); + } else { + media.removeListener?.(handleMotionChange); + } + }; + + if (media?.matches) { + handleMotionChange(media); + } else if (media && typeof media.addEventListener === "function") { + media.addEventListener("change", handleMotionChange); + } else if (media && typeof media.addListener === "function") { + media.addListener(handleMotionChange); + } + + const animationFinished = animation.finished; + if (animationFinished && typeof animationFinished.then === "function") { + void animationFinished.then(settle, settle); + } else { + settle(); + } + + const cancel = () => { + if (settled) return; + animation.cancel(); + removeMotionListener(); + settle(); + }; + + return { cancel, finished }; +}; diff --git a/src/motion/in-view.ts b/src/motion/in-view.ts new file mode 100644 index 00000000..c65c10f4 --- /dev/null +++ b/src/motion/in-view.ts @@ -0,0 +1,77 @@ +import { type Accessor, createSignal, onCleanup, onSettled } from "solid-js"; + +export type InViewOptions = { + once?: boolean; + root?: Element | Document | null; + rootMargin?: string; + threshold?: number | number[]; +}; + +/** Attach an observer without depending on a Solid owner. */ +export const attachInView = ( + element: Element, + options: InViewOptions, + onChange: (visible: boolean) => void, +): (() => void) => { + const view = element.ownerDocument?.defaultView; + const Observer = + view?.IntersectionObserver ?? globalThis.IntersectionObserver; + if (typeof Observer !== "function") { + onChange(true); + return () => {}; + } + + let observer: IntersectionObserver | undefined; + let disconnected = false; + const disconnect = () => { + if (disconnected) return; + disconnected = true; + observer?.disconnect(); + }; + + const once = options.once ?? false; + try { + observer = new Observer( + (entries) => { + if (disconnected) return; + for (const entry of entries) { + if (entry.target !== element) continue; + const isVisible = entry.isIntersecting || entry.intersectionRatio > 0; + onChange(isVisible); + if (once && isVisible) disconnect(); + } + }, + { + root: options.root ?? null, + rootMargin: options.rootMargin, + threshold: options.threshold, + }, + ); + observer.observe(element); + } catch { + disconnect(); + onChange(true); + return () => {}; + } + + return disconnect; +}; + +/** Observe an element's visibility. The static and unsupported default is visible. */ +export const createInView = ( + target: () => Element | null | undefined, + options: InViewOptions = {}, +): Accessor => { + const [visible, setVisible] = createSignal(true); + let cleanup: (() => void) | undefined; + + onSettled(() => { + cleanup?.(); + const element = target(); + cleanup = element ? attachInView(element, options, setVisible) : undefined; + }); + + onCleanup(() => cleanup?.()); + + return visible; +}; diff --git a/src/motion/index.ts b/src/motion/index.ts index 1a423933..89756a55 100644 --- a/src/motion/index.ts +++ b/src/motion/index.ts @@ -1,6 +1,12 @@ +export { + type AnimateElementOptions, + animateElement, + type ElementAnimation, +} from "./animate-element"; export { getMotionDriver, immediateDriver, setMotionDriver } from "./driver"; export { resolveEase } from "./easing"; export { runMotion } from "./engine"; +export { createInView, type InViewOptions } from "./in-view"; export { createPopmotionDriver, enablePopmotion, @@ -22,6 +28,13 @@ export { type RouteTransitionRule, type RouteTransitionRuleResult, } from "./route"; +export { + createScrollProgress, + type ScrollProgress, + type ScrollProgressOptions, + type ScrollProgressRange, + supportsViewTimeline, +} from "./scroll-progress"; export { AnimatedCollapse, type AnimatedCollapseProps, @@ -34,6 +47,11 @@ export { type PresenceProps, type PresenceRenderProp, } from "./solid"; +export { + type SpringKeyframeOptions, + springKeyframes, +} from "./spring-keyframes"; +export { stagger } from "./stagger"; export { createMotionSystem, type MotionSystemConfig } from "./system"; export { defaultMotionTokens, diff --git a/src/motion/scroll-progress.ts b/src/motion/scroll-progress.ts new file mode 100644 index 00000000..cfdf248a --- /dev/null +++ b/src/motion/scroll-progress.ts @@ -0,0 +1,226 @@ +import { type Accessor, createSignal, onCleanup, onSettled } from "solid-js"; + +export type ScrollProgressRange = "start-start/end-end"; + +export type ScrollProgressOptions = { + /** Start when the section top reaches the viewport top and end at its bottom. */ + range?: ScrollProgressRange; +}; + +export type ScrollProgressCallbacks = { + onProgress: (progress: number) => void; +}; + +export type ScrollProgressBinding = { + measure: () => void; + cleanup: () => void; +}; + +/** A reactive value from 0 at the range start to 1 at the range end. */ +export type ScrollProgress = Accessor; + +const clamp = (value: number, min: number, max: number) => + Math.min(max, Math.max(min, value)); + +/** + * Check the named view timeline and the exact contain attachment range used by + * ScrollHorizontal. Returns false in server and partial CSS API environments. + */ +export const supportsViewTimeline = () => { + const css = globalThis.CSS; + if (typeof css?.supports !== "function") return false; + + try { + return ( + css.supports("view-timeline-name", "--motion-progress") && + css.supports("view-timeline-axis", "block") && + css.supports("animation-timeline", "--motion-progress") && + css.supports("animation-range", "contain 0% contain 100%") + ); + } catch { + return false; + } +}; + +/** + * Attach scroll progress without depending on a Solid owner. Geometry is read + * on attach and resize; scroll events only schedule a viewport-top read. + */ +export const attachScrollProgress = ( + section: Element, + callbacks: ScrollProgressCallbacks, +): ScrollProgressBinding => { + const view = + section.ownerDocument?.defaultView ?? + (typeof window === "undefined" ? undefined : window); + if (!view?.addEventListener || !view.removeEventListener) { + return { measure: () => {}, cleanup: () => {} }; + } + + const sectionStyle = (section as Element & { style?: CSSStyleDeclaration }) + .style; + let priorProgress = ""; + let priorPriority = ""; + let ownsStyle = false; + if (sectionStyle) { + try { + priorProgress = sectionStyle.getPropertyValue("--scroll-progress"); + const getPropertyPriority = ( + sectionStyle as unknown as { + getPropertyPriority?: (property: string) => string; + } + ).getPropertyPriority; + priorPriority = + typeof getPropertyPriority === "function" + ? getPropertyPriority.call(sectionStyle, "--scroll-progress") + : ""; + sectionStyle.setProperty("--scroll-progress", "0"); + ownsStyle = true; + } catch { + // The CSS variable is optional when inline styles are unavailable. + } + } + + let sectionHeight = 0; + let viewportHeight = 0; + let frameId: number | undefined; + let active = true; + + const writeProgress = (value: number) => { + if (!active) return; + const next = clamp(value, 0, 1); + try { + callbacks.onProgress(next); + } catch { + // Keep scroll handling alive if a consumer callback fails. + } + if (ownsStyle) { + try { + sectionStyle?.setProperty("--scroll-progress", String(next)); + } catch { + // The CSS variable is optional when inline styles are unavailable. + } + } + }; + + const update = () => { + if (!active) return; + if (sectionHeight <= viewportHeight || viewportHeight <= 0) { + writeProgress(0); + return; + } + + try { + const sectionTop = section.getBoundingClientRect().top; + if (!Number.isFinite(sectionTop)) return; + writeProgress((0 - sectionTop) / (sectionHeight - viewportHeight)); + } catch { + // Keep the last usable value when a host cannot measure this element. + } + }; + + const cancelScheduledUpdate = () => { + if (frameId === undefined) return; + view.cancelAnimationFrame?.(frameId); + frameId = undefined; + }; + + const scheduleUpdate = () => { + if (frameId !== undefined) return; + if (typeof view.requestAnimationFrame !== "function") { + update(); + return; + } + + frameId = view.requestAnimationFrame(() => { + frameId = undefined; + update(); + }); + }; + + const measure = () => { + if (!active) return; + try { + const rect = section.getBoundingClientRect(); + const measuredHeight = rect.height; + const elementHeight = + Number.isFinite(measuredHeight) && measuredHeight > 0 + ? measuredHeight + : (section as HTMLElement).offsetHeight; + const measuredViewportHeight = view.innerHeight; + + if ( + !Number.isFinite(elementHeight) || + !Number.isFinite(measuredViewportHeight) + ) { + return; + } + + sectionHeight = Math.max(0, elementHeight); + viewportHeight = Math.max(0, measuredViewportHeight); + cancelScheduledUpdate(); + update(); + } catch { + // Missing layout metrics leave the static zero-progress state in place. + } + }; + + const handleScroll = () => scheduleUpdate(); + const handleResize = () => measure(); + + view.addEventListener("scroll", handleScroll, { passive: true }); + view.addEventListener("resize", handleResize); + measure(); + + const cleanup = () => { + if (!active) return; + active = false; + view.removeEventListener("scroll", handleScroll); + view.removeEventListener("resize", handleResize); + cancelScheduledUpdate(); + if (sectionStyle && ownsStyle) { + try { + if (priorProgress || priorPriority) { + sectionStyle.setProperty( + "--scroll-progress", + priorProgress, + priorPriority, + ); + } else { + sectionStyle.removeProperty("--scroll-progress"); + } + } catch { + // The section may already be detached or owned by a host shim. + } + } + }; + + return { measure, cleanup }; +}; + +/** + * Track section progress using one passive scroll listener and at most one + * pending animation frame. Browser work is installed only after mount. + */ +export const createScrollProgress = ( + target: () => Element | null | undefined, + _options: ScrollProgressOptions = {}, +): ScrollProgress => { + const [progress, setProgress] = createSignal(0); + let binding: ScrollProgressBinding | undefined; + + onSettled(() => { + binding?.cleanup(); + const section = target(); + binding = section + ? attachScrollProgress(section, { onProgress: setProgress }) + : undefined; + }); + + onCleanup(() => { + binding?.cleanup(); + binding = undefined; + }); + + return progress; +}; diff --git a/src/motion/spring-keyframes.ts b/src/motion/spring-keyframes.ts new file mode 100644 index 00000000..30707a13 --- /dev/null +++ b/src/motion/spring-keyframes.ts @@ -0,0 +1,94 @@ +export type SpringKeyframeOptions = { + stiffness: number; + damping: number; + mass: number; +}; + +const frameRate = 60; +const maximumDuration = 5; +const precision = 0.001; + +/** + * Sample a unit spring response at 60 Hz. The returned numbers run from 0 to + * 1 and can be passed as the values for one property in PropertyIndexedKeyframes. + */ +export const springKeyframes = ({ + stiffness, + damping, + mass, +}: SpringKeyframeOptions): number[] => { + if ( + !Number.isFinite(stiffness) || + !Number.isFinite(damping) || + !Number.isFinite(mass) || + stiffness <= 0 || + damping < 0 || + mass <= 0 + ) { + return [0, 1]; + } + + const naturalFrequency = Math.sqrt(stiffness / mass); + const decay = damping / (2 * mass); + const discriminant = naturalFrequency ** 2 - decay ** 2; + if ( + !Number.isFinite(naturalFrequency) || + !Number.isFinite(decay) || + !Number.isFinite(discriminant) + ) { + return [0, 1]; + } + const maximumFrames = Math.ceil(frameRate * maximumDuration); + + let positionAt: (time: number) => number; + let velocityAt: (time: number) => number; + + if (discriminant > 1e-8) { + const frequency = Math.sqrt(discriminant); + positionAt = (time) => { + const envelope = Math.exp(-decay * time); + return ( + 1 - + envelope * + (Math.cos(frequency * time) + + (decay / frequency) * Math.sin(frequency * time)) + ); + }; + velocityAt = (time) => + Math.exp(-decay * time) * + ((naturalFrequency ** 2 / frequency) * Math.sin(frequency * time)); + } else if (discriminant >= -1e-8) { + positionAt = (time) => + 1 - Math.exp(-naturalFrequency * time) * (1 + naturalFrequency * time); + velocityAt = (time) => + naturalFrequency ** 2 * time * Math.exp(-naturalFrequency * time); + } else { + const split = Math.sqrt(-discriminant); + const slowRoot = -decay + split; + const fastRoot = -decay - split; + positionAt = (time) => + 1 + + (fastRoot / (2 * split)) * Math.exp(slowRoot * time) - + (slowRoot / (2 * split)) * Math.exp(fastRoot * time); + velocityAt = (time) => + ((fastRoot * slowRoot) / (2 * split)) * + (Math.exp(slowRoot * time) - Math.exp(fastRoot * time)); + } + + const frames = [0]; + for (let index = 1; index <= maximumFrames; index += 1) { + const time = index / frameRate; + const position = positionAt(time); + frames.push(position); + if ( + Math.abs(1 - position) <= precision && + Math.abs(velocityAt(time)) <= precision + ) { + frames.push(1); + return frames; + } + } + + frames.push(1); + return frames; +}; diff --git a/src/motion/stagger.ts b/src/motion/stagger.ts new file mode 100644 index 00000000..f574fd1d --- /dev/null +++ b/src/motion/stagger.ts @@ -0,0 +1,6 @@ +/** Return a nonnegative WAAPI delay in milliseconds for an item's position. */ +export const stagger = (index: number, interval = 50) => { + const safeIndex = Number.isFinite(index) ? Math.max(0, index) : 0; + const safeInterval = Number.isFinite(interval) ? Math.max(0, interval) : 0; + return safeIndex * safeInterval; +}; diff --git a/src/passwordRules.ts b/src/passwordRules.ts index ab17c201..0b421b90 100644 --- a/src/passwordRules.ts +++ b/src/passwordRules.ts @@ -1,3 +1,10 @@ +export const PASSWORD_CHARSET_MESSAGE = + "Use only printable ASCII characters (spaces, letters, numbers, and symbols)."; + +/** For signup and password changes only; never restrict existing sign-in passwords. */ +export const isPrintableAsciiPassword = (password: string): boolean => + !/[^\x20-\x7E]/.test(password); + export type PasswordCustomRegexRule = { key: string; regex: RegExp; diff --git a/tests/components/qr-code/QrCode.test.ts b/tests/components/qr-code/QrCode.test.ts new file mode 100644 index 00000000..7d9f200b --- /dev/null +++ b/tests/components/qr-code/QrCode.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { qrMatrix } from "../../../src/lib/qr/qrMatrix"; + +const QR_CODE_LAYOUT = readFileSync( + join(import.meta.dir, "../../../src/components/qr-code/QrCode.layout.tsx"), + "utf8", +); + +const FINDER_PATTERN = [ + "1111111", + "1000001", + "1011101", + "1011101", + "1011101", + "1000001", + "1111111", +]; + +function expectFinderPattern( + matrix: boolean[][], + top: number, + left: number, +): void { + for (let row = 0; row < FINDER_PATTERN.length; row++) { + for (let column = 0; column < FINDER_PATTERN[row].length; column++) { + expect(matrix[top + row][left + column]).toBe( + FINDER_PATTERN[row][column] === "1", + ); + } + } +} + +describe("qrMatrix", () => { + it("encodes HELLO WORLD at level M as a version-one matrix", () => { + const matrix = qrMatrix("HELLO WORLD", "M"); + + expect(matrix).toHaveLength(21); + expect(matrix.every((row) => row.length === 21)).toBe(true); + }); + + it("returns the same matrix for the same input", () => { + expect(qrMatrix("HELLO WORLD", "M")).toEqual(qrMatrix("HELLO WORLD", "M")); + }); + + it("encodes an otpauth URI with a 32-character secret", () => { + const secret = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + const matrix = qrMatrix( + `otpauth://totp/alice@example.com?secret=${secret}&issuer=Example`, + ); + + expect(matrix.length).toBeGreaterThan(21); + expect(matrix.every((row) => row.length === matrix.length)).toBe(true); + }); + + it("places finder patterns at all three corners", () => { + const matrix = qrMatrix("HELLO WORLD", "M"); + const last = matrix.length - 7; + + expectFinderPattern(matrix, 0, 0); + expectFinderPattern(matrix, 0, last); + expectFinderPattern(matrix, last, 0); + }); +}); + +describe("QrCode", () => { + it("renders one named SVG with the title as its accessible name", () => { + expect(QR_CODE_LAYOUT.match(/{local.title}"); + expect(QR_CODE_LAYOUT.match(/ { + const printable = Array.from({ length: 95 }, (_, i) => + String.fromCharCode(i + 0x20), + ).join(""); + expect(isPrintableAsciiPassword(printable)).toBe(true); + expect(isPrintableAsciiPassword(' Password1!," ')).toBe(true); + expect(isPrintableAsciiPassword("")).toBe(true); +}); + +test("rejects controls, DEL, Unicode, and lone surrogates", () => { + for (let code = 0; code < 0x20; code++) { + expect( + isPrintableAsciiPassword(`Password1${String.fromCharCode(code)}`), + ).toBe(false); + } + for (const value of ["\x7f", "é", "漢", "😀", "\uD800", "\u00A0"]) { + expect(isPrintableAsciiPassword(`Password1${value}`)).toBe(false); + } +}); diff --git a/tests/motion/animate-element.test.ts b/tests/motion/animate-element.test.ts new file mode 100644 index 00000000..c89233f0 --- /dev/null +++ b/tests/motion/animate-element.test.ts @@ -0,0 +1,175 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { animateElement } from "../../src/motion/animate-element"; + +let matchMediaDescriptor: PropertyDescriptor | undefined; +let matchMediaInstalled = false; + +const restoreMatchMedia = () => { + if (!matchMediaInstalled) return; + if (matchMediaDescriptor) { + Object.defineProperty(globalThis, "matchMedia", matchMediaDescriptor); + } else { + Reflect.deleteProperty(globalThis, "matchMedia"); + } + matchMediaDescriptor = undefined; + matchMediaInstalled = false; +}; + +const installMatchMedia = (query: MediaQueryList) => { + matchMediaDescriptor = Object.getOwnPropertyDescriptor( + globalThis, + "matchMedia", + ); + matchMediaInstalled = true; + Object.defineProperty(globalThis, "matchMedia", { + configurable: true, + value: () => query, + }); +}; + +afterEach(restoreMatchMedia); + +describe("animateElement", () => { + it("applies the final keyframe and resolves when WAAPI is unavailable", async () => { + const properties = new Map(); + const style = { + opacity: "0", + setProperty: (property: string, value: string) => + properties.set(property, value), + }; + const element = { style } as unknown as Element; + + const animation = animateElement(element, [ + { opacity: 0, "--progress": "0" }, + { opacity: 1, "--progress": "1" }, + ]); + + await animation.finished; + animation.cancel(); + expect(style.opacity).toBe("1"); + expect(properties.get("--progress")).toBe("1"); + }); + + it("passes timing options to WAAPI and resolves on cancellation", async () => { + let receivedDuration: number | undefined; + let receivedDelay: number | undefined; + let receivedEasing: string | undefined; + let cancelCount = 0; + const neverFinishes = new Promise(() => {}); + const element = { + animate: ( + _keyframes: Keyframe[] | PropertyIndexedKeyframes, + options?: KeyframeAnimationOptions, + ) => { + receivedDuration = options?.duration as number; + receivedDelay = options?.delay as number; + receivedEasing = options?.easing; + return { + cancel: () => { + cancelCount += 1; + }, + finished: neverFinishes, + } as unknown as Animation; + }, + } as unknown as Element; + + const animation = animateElement( + element, + [{ opacity: 0 }, { opacity: 1 }], + { + duration: 180, + delay: 40, + easing: "linear", + }, + ); + animation.cancel(); + await animation.finished; + + expect(receivedDuration).toBe(180); + expect(receivedDelay).toBe(40); + expect(receivedEasing).toBe("linear"); + expect(cancelCount).toBe(1); + }); + + it("resolves when the WAAPI finished promise resolves", async () => { + let finish: (() => void) | undefined; + const finished = new Promise((resolve) => { + finish = resolve; + }); + const element = { + animate: () => + ({ + cancel: () => {}, + finished, + }) as unknown as Animation, + } as unknown as Element; + + const animation = animateElement( + element, + [{ opacity: 0 }, { opacity: 1 }], + { + respectReducedMotion: false, + }, + ); + finish?.(); + await animation.finished; + + expect(finish).toBeDefined(); + }); + + it("finishes an active animation when reduced motion turns on", async () => { + let change: EventListenerOrEventListenerObject | undefined; + let removedChange: EventListenerOrEventListenerObject | undefined; + let cancelCount = 0; + let prefersReducedMotion = false; + const properties = new Map(); + const media = { + get matches() { + return prefersReducedMotion; + }, + addEventListener: ( + _type: string, + listener: EventListenerOrEventListenerObject, + ) => { + change = listener; + }, + removeEventListener: ( + _type: string, + listener: EventListenerOrEventListenerObject, + ) => { + removedChange = listener; + }, + } as unknown as MediaQueryList; + installMatchMedia(media); + + const element = { + style: { + opacity: "0", + setProperty: (property: string, value: string) => + properties.set(property, value), + }, + animate: () => + ({ + cancel: () => { + cancelCount += 1; + }, + finished: new Promise(() => {}), + }) as unknown as Animation, + } as unknown as Element; + + const animation = animateElement(element, [{ opacity: 0 }, { opacity: 1 }]); + prefersReducedMotion = true; + if (typeof change === "function") { + change({ matches: true } as MediaQueryListEvent); + } else { + change?.handleEvent({ matches: true } as MediaQueryListEvent); + } + await animation.finished; + + expect( + (element as Element & { style: CSSStyleDeclaration }).style.opacity, + ).toBe("1"); + expect(cancelCount).toBe(1); + expect(removedChange).toBe(change); + }); +}); diff --git a/tests/motion/in-view.test.ts b/tests/motion/in-view.test.ts new file mode 100644 index 00000000..e3da0d56 --- /dev/null +++ b/tests/motion/in-view.test.ts @@ -0,0 +1,107 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { attachInView } from "../../src/motion/in-view"; + +let intersectionObserverDescriptor: PropertyDescriptor | undefined; + +const setGlobalIntersectionObserver = (value: unknown) => { + intersectionObserverDescriptor = Object.getOwnPropertyDescriptor( + globalThis, + "IntersectionObserver", + ); + Object.defineProperty(globalThis, "IntersectionObserver", { + configurable: true, + value, + }); +}; + +const restoreIntersectionObserver = () => { + if (intersectionObserverDescriptor) { + Object.defineProperty( + globalThis, + "IntersectionObserver", + intersectionObserverDescriptor, + ); + } else { + Reflect.deleteProperty(globalThis, "IntersectionObserver"); + } + intersectionObserverDescriptor = undefined; +}; + +afterEach(restoreIntersectionObserver); + +describe("attachInView", () => { + it("starts visible and stays visible when IntersectionObserver is unavailable", () => { + setGlobalIntersectionObserver(undefined); + const element = { + ownerDocument: { defaultView: {} }, + } as unknown as Element; + let visible: boolean | undefined; + + const cleanup = attachInView(element, {}, (value) => { + visible = value; + }); + + expect(visible).toBe(true); + cleanup(); + }); + + it("updates visibility and disconnects after the first intersection when once is true", () => { + let report: IntersectionObserverCallback | undefined; + let observed: Element | undefined; + let disconnectCount = 0; + class Observer { + constructor(callback: IntersectionObserverCallback) { + report = callback; + } + + observe(element: Element) { + observed = element; + } + + disconnect() { + disconnectCount += 1; + } + } + const element = { + ownerDocument: { defaultView: { IntersectionObserver: Observer } }, + } as unknown as Element; + let visible = true; + + const cleanup = attachInView( + element, + { once: true, threshold: 0.25 }, + (value) => { + visible = value; + }, + ); + + expect(visible).toBe(true); + expect(observed).toBe(element); + report?.( + [ + { + target: element, + isIntersecting: false, + intersectionRatio: 0, + } as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ); + expect(visible).toBe(false); + + report?.( + [ + { + target: element, + isIntersecting: true, + intersectionRatio: 0.25, + } as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ); + expect(visible).toBe(true); + expect(disconnectCount).toBe(1); + cleanup(); + expect(disconnectCount).toBe(1); + }); +}); diff --git a/tests/motion/scroll-progress.supports-view-timeline.test.ts b/tests/motion/scroll-progress.supports-view-timeline.test.ts new file mode 100644 index 00000000..a080fd11 --- /dev/null +++ b/tests/motion/scroll-progress.supports-view-timeline.test.ts @@ -0,0 +1,54 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { supportsViewTimeline } from "../../src/motion/scroll-progress"; + +let cssDescriptor: PropertyDescriptor | undefined; + +const installCssSupports = ( + supports: (property: string, value: string) => boolean, +) => { + cssDescriptor = Object.getOwnPropertyDescriptor(globalThis, "CSS"); + Object.defineProperty(globalThis, "CSS", { + configurable: true, + value: { supports }, + }); +}; + +const restoreCss = () => { + if (cssDescriptor) { + Object.defineProperty(globalThis, "CSS", cssDescriptor); + } else { + Reflect.deleteProperty(globalThis, "CSS"); + } + cssDescriptor = undefined; +}; + +afterEach(restoreCss); + +describe("supportsViewTimeline", () => { + it("requires the named timeline and contain range declarations", () => { + const checked: string[] = []; + installCssSupports((property, value) => { + checked.push(`${property}: ${value}`); + return true; + }); + + expect(supportsViewTimeline()).toBe(true); + expect(checked).toEqual([ + "view-timeline-name: --motion-progress", + "view-timeline-axis: block", + "animation-timeline: --motion-progress", + "animation-range: contain 0% contain 100%", + ]); + }); + + it("rejects partial support and a throwing CSS.supports implementation", () => { + installCssSupports((property) => property !== "animation-range"); + expect(supportsViewTimeline()).toBe(false); + + restoreCss(); + installCssSupports(() => { + throw new Error("CSS.supports unavailable"); + }); + expect(supportsViewTimeline()).toBe(false); + }); +}); diff --git a/tests/motion/scroll-progress.test.ts b/tests/motion/scroll-progress.test.ts new file mode 100644 index 00000000..739b9977 --- /dev/null +++ b/tests/motion/scroll-progress.test.ts @@ -0,0 +1,178 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { attachScrollProgress } from "../../src/motion/scroll-progress"; + +type FrameCallback = (time: number) => void; + +const createFixture = () => { + let top = 0; + let height = 1000; + let viewportHeight = 400; + let nextFrameId = 1; + const frameCallbacks = new Map(); + const listeners = new Map>(); + + const view = { + get innerHeight() { + return viewportHeight; + }, + addEventListener: ( + type: string, + listener: EventListenerOrEventListenerObject, + ) => { + const entries = listeners.get(type) ?? new Set(); + entries.add(listener); + listeners.set(type, entries); + }, + removeEventListener: ( + type: string, + listener: EventListenerOrEventListenerObject, + ) => { + listeners.get(type)?.delete(listener); + }, + requestAnimationFrame: (callback: FrameRequestCallback) => { + const id = nextFrameId; + nextFrameId += 1; + frameCallbacks.set(id, callback); + return id; + }, + cancelAnimationFrame: (id: number) => frameCallbacks.delete(id), + } as unknown as Window; + + const styleValues = new Map(); + const stylePriorities = new Map(); + const sectionStyle = { + setProperty(property: string, value: string, priority = "") { + styleValues.set(property, value); + stylePriorities.set(property, priority); + }, + getPropertyValue: (property: string) => styleValues.get(property) ?? "", + getPropertyPriority: (property: string) => + stylePriorities.get(property) ?? "", + removeProperty: (property: string) => { + const value = styleValues.get(property) ?? ""; + styleValues.delete(property); + stylePriorities.delete(property); + return value; + }, + } as unknown as CSSStyleDeclaration; + + const section = { + ownerDocument: { defaultView: view }, + style: sectionStyle, + getBoundingClientRect: () => ({ + top, + height, + bottom: top + height, + left: 0, + right: 100, + width: 100, + x: 0, + y: top, + toJSON: () => ({}), + }), + } as unknown as Element; + + const fire = (type: string) => { + const event = new Event(type); + for (const listener of listeners.get(type) ?? []) { + if (typeof listener === "function") listener.call(view, event); + else listener.handleEvent(event); + } + }; + + const runNextFrame = () => { + const entry = frameCallbacks.entries().next().value; + if (!entry) return; + const [id, callback] = entry; + frameCallbacks.delete(id); + callback(0); + }; + + let progress = 0; + const binding = attachScrollProgress(section, { + onProgress: (value) => { + progress = value; + }, + }); + + return { + get progress() { + return progress; + }, + fire, + frameCount: () => frameCallbacks.size, + listenerCount: (type: string) => listeners.get(type)?.size ?? 0, + styleValues, + runNextFrame, + setTop: (value: number) => { + top = value; + }, + setViewportHeight: (value: number) => { + viewportHeight = value; + }, + setSectionHeight: (value: number) => { + height = value; + }, + dispose: binding.cleanup, + }; +}; + +let fixtures: ReturnType[] = []; + +afterEach(() => { + for (const fixture of fixtures) fixture.dispose(); + fixtures = []; +}); + +describe("attachScrollProgress", () => { + it("tracks and clamps section progress while updating its CSS variable", () => { + const fixture = createFixture(); + fixtures.push(fixture); + + expect(fixture.progress).toBe(0); + expect(fixture.styleValues.get("--scroll-progress")).toBe("0"); + expect(fixture.listenerCount("scroll")).toBe(1); + + fixture.setTop(-300); + fixture.fire("scroll"); + fixture.fire("scroll"); + expect(fixture.frameCount()).toBe(1); + expect(fixture.progress).toBe(0); + + fixture.runNextFrame(); + expect(fixture.progress).toBe(0.5); + expect(fixture.styleValues.get("--scroll-progress")).toBe("0.5"); + + fixture.setTop(-900); + fixture.fire("scroll"); + fixture.runNextFrame(); + expect(fixture.progress).toBe(1); + + fixture.dispose(); + expect(fixture.styleValues.has("--scroll-progress")).toBe(false); + }); + + it("remeasures its range on resize and removes listeners on cleanup", () => { + const fixture = createFixture(); + fixtures.push(fixture); + + fixture.setViewportHeight(500); + fixture.setTop(-250); + fixture.fire("resize"); + expect(fixture.progress).toBe(0.5); + + fixture.dispose(); + expect(fixture.listenerCount("scroll")).toBe(0); + expect(fixture.listenerCount("resize")).toBe(0); + expect(fixture.styleValues.has("--scroll-progress")).toBe(false); + }); + + it("keeps zero progress when the section has no vertical travel", () => { + const fixture = createFixture(); + fixtures.push(fixture); + fixture.setSectionHeight(400); + fixture.fire("resize"); + + expect(fixture.progress).toBe(0); + }); +}); diff --git a/tests/motion/spring-keyframes.test.ts b/tests/motion/spring-keyframes.test.ts new file mode 100644 index 00000000..5762b228 --- /dev/null +++ b/tests/motion/spring-keyframes.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "bun:test"; +import { springKeyframes } from "../../src/motion/spring-keyframes"; + +describe("springKeyframes", () => { + it("samples a finite response at 60 Hz and settles at unit endpoints", () => { + const values = springKeyframes({ stiffness: 200, damping: 24, mass: 1 }); + + expect(values.length).toBeGreaterThan(2); + expect(values[0]).toBe(0); + expect(values[values.length - 1]).toBe(1); + expect(values.every(Number.isFinite)).toBe(true); + expect(values.length).toBeLessThanOrEqual(302); + }); + + it("returns an immediate unit transition for invalid spring parameters", () => { + expect(springKeyframes({ stiffness: 0, damping: 12, mass: 1 })).toEqual([ + 0, 1, + ]); + expect(springKeyframes({ stiffness: 100, damping: -1, mass: 1 })).toEqual([ + 0, 1, + ]); + }); + + it("preserves overshoot for an underdamped spring", () => { + const values = springKeyframes({ stiffness: 200, damping: 8, mass: 1 }); + + expect(values.some((value) => value > 1)).toBe(true); + expect(values[values.length - 1]).toBe(1); + }); +}); diff --git a/tests/motion/stagger.test.ts b/tests/motion/stagger.test.ts new file mode 100644 index 00000000..21fca86d --- /dev/null +++ b/tests/motion/stagger.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "bun:test"; +import { stagger } from "../../src/motion/stagger"; + +describe("stagger", () => { + it("returns an index-based delay in milliseconds", () => { + expect(stagger(0)).toBe(0); + expect(stagger(3)).toBe(150); + expect(stagger(3, 20)).toBe(60); + }); + + it("keeps negative and non-finite inputs from creating invalid delays", () => { + expect(stagger(-2, 50)).toBe(0); + expect(stagger(2, -10)).toBe(0); + expect(stagger(Number.NaN, 20)).toBe(0); + expect(stagger(3, Number.POSITIVE_INFINITY)).toBe(0); + }); +}); diff --git a/tests/ps-qa-headless/qr-code.ron b/tests/ps-qa-headless/qr-code.ron new file mode 100644 index 00000000..2a2292cf --- /dev/null +++ b/tests/ps-qa-headless/qr-code.ron @@ -0,0 +1,37 @@ +// Generated from tests/qa-harness/components.ts by tests/qa-harness/generate-checks.ts. Do not edit. +// +// QrCode, mounted alone on its own harness page. Outcomes for +// this component share one native host; idempotent preparation keeps each +// outcome reproducible by id against a fresh host as well. +[ + ( + id: "qr-code-page-paints", + group: "qr-code", + what: "the QrCode page builds and paints", + open: None, + hover: None, + click: None, + subject: "heading:QrCode", + expect: Present, + ), + ( + id: "qr-code-renders", + group: "qr-code", + what: "QrCode renders a node of its own", + open: None, + hover: None, + click: None, + subject: "fixture", + expect: Paints, + ), + ( + id: "qr-code-paints", + group: "qr-code", + what: "the QrCode reaches the renderer with a box", + open: None, + hover: None, + click: None, + subject: "QrCode", + expect: Present, + ), +] diff --git a/tests/ps-qa-headless/scroll-horizontal.ron b/tests/ps-qa-headless/scroll-horizontal.ron new file mode 100644 index 00000000..85faac4e --- /dev/null +++ b/tests/ps-qa-headless/scroll-horizontal.ron @@ -0,0 +1,187 @@ +// Generated from tests/qa-harness/components.ts by tests/qa-harness/generate-checks.ts. Do not edit. +// +// ScrollHorizontal, mounted alone on its own harness page. Outcomes for +// this component share one native host; idempotent preparation keeps each +// outcome reproducible by id against a fresh host as well. +[ + ( + id: "scroll-horizontal-page-paints", + group: "scroll-horizontal", + what: "the ScrollHorizontal page builds and paints", + open: None, + hover: None, + click: None, + subject: "heading:ScrollHorizontal", + expect: Present, + ), + ( + id: "scroll-horizontal-renders", + group: "scroll-horizontal", + what: "ScrollHorizontal renders a node of its own", + open: None, + hover: None, + click: None, + subject: "fixture", + expect: Paints, + ), + ( + id: "scroll-horizontal-renders-final-card", + group: "scroll-horizontal", + what: "the gallery keeps its final card in the rendered tree", + open: None, + hover: None, + click: None, + subject: "button:Card four action", + expect: Present, + ), + ( + id: "scroll-horizontal-uses-scroll-fallback-middle", + group: "scroll-horizontal", + what: "page scrolling moves the gallery to its middle cards without a scroll timeline", + open: None, + hover: None, + click: Some("button:Go to gallery middle"), + subject: "region:Scroll gallery", + expect: PixelsChange, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-resizes-viewport", + group: "scroll-horizontal", + what: "the gallery recalculates its travel when its visible area resizes", + open: None, + hover: None, + click: Some("button:Resize gallery viewport"), + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Go to gallery middle"), + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-uses-scroll-fallback-end", + group: "scroll-horizontal", + what: "page scrolling moves the gallery to its final card without a scroll timeline", + open: None, + hover: None, + click: Some("button:Go to gallery end"), + subject: "region:Scroll gallery", + expect: PixelsChange, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-uses-scroll-fallback-start", + group: "scroll-horizontal", + what: "page scrolling returns the gallery to its first card without a scroll timeline", + open: None, + hover: None, + click: Some("button:Go to gallery start"), + subject: "region:Scroll gallery", + expect: PixelsChange, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-reports-viewport-scroll", + group: "scroll-horizontal", + what: "the native viewport readback changes after the gallery returns to its end", + open: None, + hover: None, + click: Some("button:Go to gallery end"), + subject: "heading:Viewport scroll:", + expect: NameChanges, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-reports-scroll-progress", + group: "scroll-horizontal", + what: "the component progress readback changes with native page position", + open: None, + hover: None, + click: Some("button:Go to gallery start"), + subject: "heading:Scroll progress:", + expect: NameChanges, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-focuses-first-card-action", + group: "scroll-horizontal", + what: "Tab moves focus from the gallery region to the first card action", + open: None, + hover: None, + click: None, + subject: "button:Card one action", + expect: FocusMoves, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("region:Scroll gallery"), + ), + ( + id: "scroll-horizontal-focuses-second-card-action", + group: "scroll-horizontal", + what: "Tab moves focus from the first card action to the second card action", + open: None, + hover: None, + click: None, + subject: "button:Card two action", + expect: FocusMoves, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("button:Card one action"), + ), + ( + id: "scroll-horizontal-keeps-keyboard-order", + group: "scroll-horizontal", + what: "keyboard navigation reaches the next card action", + open: None, + hover: None, + click: None, + subject: "button:Card four action", + expect: FocusMoves, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("button:Card three action"), + ), + ( + id: "scroll-horizontal-reveals-offscreen-card-on-focus", + group: "scroll-horizontal", + what: "keyboard focus brings an offscreen card action into the viewport", + open: None, + hover: None, + click: None, + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("button:Card three action"), + ), + ( + id: "scroll-horizontal-respects-reduced-motion", + group: "scroll-horizontal", + what: "a live reduced-motion change updates the gallery", + open: None, + hover: None, + click: Some("button:Toggle reduced motion"), + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-reduced-motion-keyboard-scrolls", + group: "scroll-horizontal", + what: "the horizontal row remains keyboard scrollable under reduced motion", + open: None, + hover: None, + click: None, + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Toggle reduced motion"), + prepare_unless: Some("heading:Reduced motion: enabled"), + settle_after_ms: 150, + key: Some("ArrowRight"), + key_on: Some("region:Scroll gallery"), + ), +] diff --git a/tests/ps-qa/qr-code.ron b/tests/ps-qa/qr-code.ron new file mode 100644 index 00000000..14f824cc --- /dev/null +++ b/tests/ps-qa/qr-code.ron @@ -0,0 +1,37 @@ +// Generated from tests/qa-harness/components.ts by tests/qa-harness/generate-checks.ts. Do not edit. +// +// QrCode, mounted alone on its own harness page. Outcomes for +// this component share one native host; idempotent preparation keeps each +// outcome reproducible by id against a fresh host as well. +[ + ( + id: "qr-code-page-paints", + group: "qr-code", + what: "the QrCode page builds and paints", + open: None, + hover: None, + click: None, + subject: "heading:QrCode", + expect: PaintsNamed, + ), + ( + id: "qr-code-renders", + group: "qr-code", + what: "QrCode renders a node of its own", + open: None, + hover: None, + click: None, + subject: "fixture", + expect: Paints, + ), + ( + id: "qr-code-paints", + group: "qr-code", + what: "the QrCode reaches the renderer with a box", + open: None, + hover: None, + click: None, + subject: "QrCode", + expect: Paints, + ), +] diff --git a/tests/ps-qa/scroll-horizontal.ron b/tests/ps-qa/scroll-horizontal.ron new file mode 100644 index 00000000..2bd04e0c --- /dev/null +++ b/tests/ps-qa/scroll-horizontal.ron @@ -0,0 +1,187 @@ +// Generated from tests/qa-harness/components.ts by tests/qa-harness/generate-checks.ts. Do not edit. +// +// ScrollHorizontal, mounted alone on its own harness page. Outcomes for +// this component share one native host; idempotent preparation keeps each +// outcome reproducible by id against a fresh host as well. +[ + ( + id: "scroll-horizontal-page-paints", + group: "scroll-horizontal", + what: "the ScrollHorizontal page builds and paints", + open: None, + hover: None, + click: None, + subject: "heading:ScrollHorizontal", + expect: PaintsNamed, + ), + ( + id: "scroll-horizontal-renders", + group: "scroll-horizontal", + what: "ScrollHorizontal renders a node of its own", + open: None, + hover: None, + click: None, + subject: "fixture", + expect: Paints, + ), + ( + id: "scroll-horizontal-renders-final-card", + group: "scroll-horizontal", + what: "the gallery keeps its final card in the rendered tree", + open: None, + hover: None, + click: None, + subject: "button:Card four action", + expect: Present, + ), + ( + id: "scroll-horizontal-uses-scroll-fallback-middle", + group: "scroll-horizontal", + what: "page scrolling moves the gallery to its middle cards without a scroll timeline", + open: None, + hover: None, + click: Some("button:Go to gallery middle"), + subject: "region:Scroll gallery", + expect: PixelsChange, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-resizes-viewport", + group: "scroll-horizontal", + what: "the gallery recalculates its travel when its visible area resizes", + open: None, + hover: None, + click: Some("button:Resize gallery viewport"), + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Go to gallery middle"), + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-uses-scroll-fallback-end", + group: "scroll-horizontal", + what: "page scrolling moves the gallery to its final card without a scroll timeline", + open: None, + hover: None, + click: Some("button:Go to gallery end"), + subject: "region:Scroll gallery", + expect: PixelsChange, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-uses-scroll-fallback-start", + group: "scroll-horizontal", + what: "page scrolling returns the gallery to its first card without a scroll timeline", + open: None, + hover: None, + click: Some("button:Go to gallery start"), + subject: "region:Scroll gallery", + expect: PixelsChange, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-reports-viewport-scroll", + group: "scroll-horizontal", + what: "the native viewport readback changes after the gallery returns to its end", + open: None, + hover: None, + click: Some("button:Go to gallery end"), + subject: "heading:Viewport scroll:", + expect: NameChanges, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-reports-scroll-progress", + group: "scroll-horizontal", + what: "the component progress readback changes with native page position", + open: None, + hover: None, + click: Some("button:Go to gallery start"), + subject: "heading:Scroll progress:", + expect: NameChanges, + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-focuses-first-card-action", + group: "scroll-horizontal", + what: "Tab moves focus from the gallery region to the first card action", + open: None, + hover: None, + click: None, + subject: "button:Card one action", + expect: FocusMoves, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("region:Scroll gallery"), + ), + ( + id: "scroll-horizontal-focuses-second-card-action", + group: "scroll-horizontal", + what: "Tab moves focus from the first card action to the second card action", + open: None, + hover: None, + click: None, + subject: "button:Card two action", + expect: FocusMoves, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("button:Card one action"), + ), + ( + id: "scroll-horizontal-keeps-keyboard-order", + group: "scroll-horizontal", + what: "keyboard navigation reaches the next card action", + open: None, + hover: None, + click: None, + subject: "button:Card four action", + expect: FocusMoves, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("button:Card three action"), + ), + ( + id: "scroll-horizontal-reveals-offscreen-card-on-focus", + group: "scroll-horizontal", + what: "keyboard focus brings an offscreen card action into the viewport", + open: None, + hover: None, + click: None, + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 150, + key: Some("Tab"), + key_on: Some("button:Card three action"), + ), + ( + id: "scroll-horizontal-respects-reduced-motion", + group: "scroll-horizontal", + what: "a live reduced-motion change updates the gallery", + open: None, + hover: None, + click: Some("button:Toggle reduced motion"), + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Go to gallery start"), + settle_after_ms: 250, + ), + ( + id: "scroll-horizontal-reduced-motion-keyboard-scrolls", + group: "scroll-horizontal", + what: "the horizontal row remains keyboard scrollable under reduced motion", + open: None, + hover: None, + click: None, + subject: "region:Scroll gallery", + expect: PixelsChange, + prepare: Some("button:Toggle reduced motion"), + prepare_unless: Some("heading:Reduced motion: enabled"), + settle_after_ms: 150, + key: Some("ArrowRight"), + key_on: Some("region:Scroll gallery"), + ), +] diff --git a/tests/qa-harness/components.ts b/tests/qa-harness/components.ts index be35e99b..352a969c 100644 --- a/tests/qa-harness/components.ts +++ b/tests/qa-harness/components.ts @@ -648,6 +648,26 @@ export const COMPONENTS: ComponentSpec[] = [ subjectRole: "radio", }, { id: "scroll-area", component: "ScrollArea", kind: "display" }, + { + id: "scroll-horizontal", + component: "ScrollHorizontal", + kind: "custom", + outcomes: [ + { suffix: "renders-final-card", what: "the gallery keeps its final card in the rendered tree", subject: "button:Card four action", expect: "Present" }, + { suffix: "uses-scroll-fallback-middle", what: "page scrolling moves the gallery to its middle cards without a scroll timeline", click: "button:Go to gallery middle", subject: "region:Scroll gallery", expect: "PixelsChange", settleAfterMs: 250 }, + { suffix: "resizes-viewport", what: "the gallery recalculates its travel when its visible area resizes", prepare: "button:Go to gallery middle", click: "button:Resize gallery viewport", subject: "region:Scroll gallery", expect: "PixelsChange", settleAfterMs: 250 }, + { suffix: "uses-scroll-fallback-end", what: "page scrolling moves the gallery to its final card without a scroll timeline", click: "button:Go to gallery end", subject: "region:Scroll gallery", expect: "PixelsChange", settleAfterMs: 250 }, + { suffix: "uses-scroll-fallback-start", what: "page scrolling returns the gallery to its first card without a scroll timeline", click: "button:Go to gallery start", subject: "region:Scroll gallery", expect: "PixelsChange", settleAfterMs: 250 }, + { suffix: "reports-viewport-scroll", what: "the native viewport readback changes after the gallery returns to its end", click: "button:Go to gallery end", subject: "heading:Viewport scroll:", expect: "NameChanges", settleAfterMs: 250 }, + { suffix: "reports-scroll-progress", what: "the component progress readback changes with native page position", click: "button:Go to gallery start", subject: "heading:Scroll progress:", expect: "NameChanges", settleAfterMs: 250 }, + { suffix: "focuses-first-card-action", what: "Tab moves focus from the gallery region to the first card action", prepare: "button:Go to gallery start", key: "Tab", keyOn: "region:Scroll gallery", subject: "button:Card one action", expect: "FocusMoves", settleAfterMs: 150 }, + { suffix: "focuses-second-card-action", what: "Tab moves focus from the first card action to the second card action", prepare: "button:Go to gallery start", key: "Tab", keyOn: "button:Card one action", subject: "button:Card two action", expect: "FocusMoves", settleAfterMs: 150 }, + { suffix: "keeps-keyboard-order", what: "keyboard navigation reaches the next card action", prepare: "button:Go to gallery start", key: "Tab", keyOn: "button:Card three action", subject: "button:Card four action", expect: "FocusMoves", settleAfterMs: 150 }, + { suffix: "reveals-offscreen-card-on-focus", what: "keyboard focus brings an offscreen card action into the viewport", prepare: "button:Go to gallery start", key: "Tab", keyOn: "button:Card three action", subject: "region:Scroll gallery", expect: "PixelsChange", settleAfterMs: 150 }, + { suffix: "respects-reduced-motion", what: "a live reduced-motion change updates the gallery", prepare: "button:Go to gallery start", click: "button:Toggle reduced motion", subject: "region:Scroll gallery", expect: "PixelsChange", settleAfterMs: 250 }, + { suffix: "reduced-motion-keyboard-scrolls", what: "the horizontal row remains keyboard scrollable under reduced motion", prepare: "button:Toggle reduced motion", prepareUnless: "heading:Reduced motion: enabled", key: "ArrowRight", keyOn: "region:Scroll gallery", subject: "region:Scroll gallery", expect: "PixelsChange", settleAfterMs: 150 }, + ], + }, { id: "select", component: "Select", @@ -881,6 +901,12 @@ export const COMPONENTS: ComponentSpec[] = [ }, { id: "meter", component: "Meter", kind: "display" }, { id: "noise-background", component: "NoiseBackground", kind: "display" }, + { + id: "qr-code", + component: "QrCode", + kind: "display", + props: { value: "https://pathscale.com", title: "PathScale QR code" }, + }, { id: "radial-progress", component: "RadialProgress", kind: "display" }, { id: "radio-group", diff --git a/tests/qa-harness/generate-entries.ts b/tests/qa-harness/generate-entries.ts index a5de5e29..678d98a3 100644 --- a/tests/qa-harness/generate-entries.ts +++ b/tests/qa-harness/generate-entries.ts @@ -183,11 +183,13 @@ const IMPORT_FORM: Record = { "PasswordRequirements": "named", "Popover": "default", "Progress": "default", + "QrCode": "default", "RadialProgress": "default", "Radio": "default", "RangeCalendar": "default", "RadioGroup": "named", "ScrollArea": "default", + "ScrollHorizontal": "default", "Select": "default", "Separator": "default", "SizePicker": "named", @@ -248,6 +250,8 @@ const IMPORT_FORM: Record = { "useDesktop": "named", "useAnchoredOverlayPosition": "named", "evaluatePasswordRules": "named", + "isPrintableAsciiPassword": "named", + "PASSWORD_CHARSET_MESSAGE": "named", "matchPasswordConfirmation": "named", "useStreamingBuffer": "named", "useStreamingSubscription": "named", @@ -338,11 +342,13 @@ const MODULE_PATHS: Record = { "password-requirements": "components/password-requirements", "popover": "components/popover", "progress": "components/progress", + "qr-code": "components/qr-code", "radial-progress": "components/radial-progress", "radio": "components/radio", "radio-group": "components/radio-group", "range-calendar": "components/range-calendar", "scroll-area": "components/scroll-area", + "scroll-horizontal": "components/scroll-horizontal", "select": "components/select", "separator": "components/separator", "size-picker": "components/size-picker", diff --git a/tests/qa-harness/mount.tsx b/tests/qa-harness/mount.tsx index afcaec3f..236c7940 100644 --- a/tests/qa-harness/mount.tsx +++ b/tests/qa-harness/mount.tsx @@ -21,6 +21,7 @@ * undefined. Dropdown, Select, Dialog, Popover and Tabs do attach their parts * to the root export, so their fixtures use that public compound API. */ +import { supportsViewTimeline } from "@pathscale/ui/motion"; import Collapsible, { CollapsibleContent, CollapsibleTrigger, @@ -1583,6 +1584,231 @@ function VideoPreviewFixture() { return ; } +function ScrollHorizontalFixture(props: { spec: ComponentSpec; under?: unknown }) { + const Component = props.under as + | ((props: Record) => JSX.Element) + | undefined; + const [reducedMotion, setReducedMotion] = createSignal(false); + let reducedMotionMatches = false; + const [viewportScrollY, setViewportScrollY] = createSignal( + Math.round(window.scrollY || 0), + ); + const [scrollProgress, setScrollProgress] = createSignal("pending"); + const [scrollSetup, setScrollSetup] = createSignal("pending"); + const [viewportDom, setViewportDom] = createSignal("pending"); + const [readyState, setReadyState] = createSignal("pending"); + const [travelVar, setTravelVar] = createSignal("pending"); + const [trackTransform, setTrackTransform] = createSignal("pending"); + const [trackBox, setTrackBox] = createSignal("pending"); + const [viewLeft, setViewLeft] = createSignal("pending"); + const sampleGalleryReadbacks = () => { + const gallery = document.querySelector(".qa-scroll-horizontal"); + const viewport = gallery?.querySelector(".scroll-horizontal__viewport"); + const track = gallery?.querySelector(".scroll-horizontal__track"); + setScrollProgress( + gallery?.style.getPropertyValue("--scroll-progress") || "unset", + ); + setTravelVar( + gallery?.style.getPropertyValue("--scroll-horizontal-travel") || "unset", + ); + setReadyState(gallery?.getAttribute("data-scroll-ready") ?? "false"); + setViewLeft( + viewport && Number.isFinite(viewport.scrollLeft) + ? String(viewport.scrollLeft) + : "unset", + ); + let transform = "unset"; + try { + if (track && typeof getComputedStyle === "function") { + transform = getComputedStyle(track).transform || "none"; + } + } catch { + transform = "error"; + } + setTrackTransform(transform); + if (track) { + const rect = track.getBoundingClientRect(); + setTrackBox( + `${Math.round(rect.left)},${Math.round(rect.top)} ${Math.round(rect.width)}x${Math.round(rect.height)}`, + ); + } else { + setTrackBox("missing"); + } + setScrollSetup( + `root=${gallery?.localName ?? "missing"};label=${gallery?.getAttribute("aria-label") ?? "missing"};ready=${gallery?.getAttribute("data-scroll-ready") ?? "missing"};view-timeline-support=${supportsViewTimeline() ? "yes" : "no"};progress=${gallery?.style.getPropertyValue("--scroll-progress") || "unset"};track=${track?.scrollWidth ?? "missing"};viewport=${viewport?.clientWidth ?? "missing"};height=${Math.round(window.innerHeight)}`, + ); + }; + const updateScrollReadbacks = () => { + setViewportScrollY(Math.round(window.scrollY || 0)); + window.requestAnimationFrame(() => + window.requestAnimationFrame(() => { + sampleGalleryReadbacks(); + }), + ); + }; + window.addEventListener("scroll", updateScrollReadbacks, { passive: true }); + onCleanup(() => window.removeEventListener("scroll", updateScrollReadbacks)); + window.requestAnimationFrame(() => sampleGalleryReadbacks()); + let isNarrow = false; + const reducedMotionListeners = new Set<(event: MediaQueryListEvent) => void>(); + const reducedMotionQuery = { + media: "(prefers-reduced-motion: reduce)", + get matches() { + return reducedMotionMatches; + }, + onchange: null, + addEventListener: (_type: string, listener: EventListenerOrEventListenerObject) => { + if (typeof listener === "function") { + reducedMotionListeners.add(listener as (event: MediaQueryListEvent) => void); + } + }, + removeEventListener: (_type: string, listener: EventListenerOrEventListenerObject) => { + if (typeof listener === "function") { + reducedMotionListeners.delete(listener as (event: MediaQueryListEvent) => void); + } + }, + addListener: (listener: (event: MediaQueryListEvent) => void) => reducedMotionListeners.add(listener), + removeListener: (listener: (event: MediaQueryListEvent) => void) => reducedMotionListeners.delete(listener), + dispatchEvent: (event: Event) => { + for (const listener of reducedMotionListeners) listener(event as MediaQueryListEvent); + if (typeof reducedMotionQuery.onchange === "function") { + reducedMotionQuery.onchange.call(reducedMotionQuery, event as MediaQueryListEvent); + } + return true; + }, + } as MediaQueryList; + const matchMediaDescriptor = Object.getOwnPropertyDescriptor(window, "matchMedia"); + const originalMatchMedia = + typeof window.matchMedia === "function" ? window.matchMedia.bind(window) : undefined; + + try { + Object.defineProperty(window, "matchMedia", { + configurable: true, + value: (query: string) => + query === reducedMotionQuery.media + ? reducedMotionQuery + : originalMatchMedia?.(query) ?? { + media: query, + matches: false, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => true, + }, + }); + } catch { + // A host that locks matchMedia keeps its native preference handling. + } + onCleanup(() => { + if (matchMediaDescriptor) { + Object.defineProperty(window, "matchMedia", matchMediaDescriptor); + } else { + Reflect.deleteProperty(window, "matchMedia"); + } + }); + + const goTo = (fraction: number) => { + const gallery = document.querySelector(".qa-scroll-horizontal"); + if (!gallery) return; + + const scroller = document.scrollingElement ?? document.documentElement; + const sectionTop = gallery.getBoundingClientRect().top + (window.scrollY || scroller.scrollTop || 0); + const travel = Math.max(0, gallery.getBoundingClientRect().height - window.innerHeight); + const top = sectionTop + travel * fraction; + if (typeof window.scrollTo === "function") { + window.scrollTo({ top, behavior: "auto" }); + } else { + scroller.scrollTop = top; + window.dispatchEvent(new Event("scroll")); + } + }; + + const resizeGallery = () => { + const gallery = document.querySelector(".qa-scroll-horizontal"); + if (!gallery) return; + isNarrow = !isNarrow; + gallery.style.width = isNarrow ? `${Math.max(320, Math.round(window.innerWidth * 0.9))}px` : "100%"; + window.dispatchEvent(new Event("resize")); + window.requestAnimationFrame(() => sampleGalleryReadbacks()); + }; + + const captureScrollSetup = () => { + sampleGalleryReadbacks(); + }; + + const toggleReducedMotion = () => { + // Capture the mounted component state before the preference change intentionally + // clears data-scroll-ready and removes the motion binding. + captureScrollSetup(); + // MediaQueryList reflects the new preference before notifying listeners; + // the rendered signal may commit after this event handler completes. + reducedMotionMatches = !reducedMotionMatches; + setReducedMotion(reducedMotionMatches); + reducedMotionQuery.dispatchEvent(new Event("change")); + window.requestAnimationFrame(() => { + const viewport = document.querySelector(".qa-scroll-horizontal .scroll-horizontal__viewport"); + setViewportDom(viewport + ? `${viewport.localName}; role-attr=${viewport.getAttribute("role") ?? "implicit"}; aria-label=${viewport.getAttribute("aria-label") ?? "missing"}; tabindex=${viewport.getAttribute("tabindex") ?? "missing"}` + : "missing"); + }); + }; + + if (!Component) return ScrollHorizontal is not exported; + + return ( + <> + + +
+

Card one

+ +
+
+

Card two

+ +
+
+

Card three

+ +
+
+

Card four

+ +
+
+

Viewport scroll: {viewportScrollY()}

+

Scroll progress: {scrollProgress()}

+

Ready: {readyState()}

+

Travel: {travelVar()}

+

Transform: {trackTransform()}

+

Track box: {trackBox()}

+

View left: {viewLeft()}

+

Scroll setup: {scrollSetup()}

+

Viewport DOM: {viewportDom()}

+

Reduced motion: {reducedMotion() ? "enabled" : "disabled"}

+ + ); +} + /** Ids with a hand-written fixture; everything else mounts generically. */ const FIXTURES: Record< string, @@ -1655,6 +1881,7 @@ const FIXTURES: Record< radio: ToggleFixtureWithReport, "radio-group": RadioGroupFixture, "range-calendar": RangeCalendarFixture, + "scroll-horizontal": ScrollHorizontalFixture, select: SelectFixture, "size-picker": SizePickerFixture, slider: SliderFixture,