sinwan-ui-core 1.5.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +29 -1
- package/agents/internal/llms.controlled.txt +39 -0
- package/agents/internal/llms.form.txt +43 -0
- package/agents/internal/llms.ids.txt +46 -0
- package/agents/internal/llms.modal.txt +51 -0
- package/agents/llms.controls.txt +82 -0
- package/agents/llms.core.txt +73 -0
- package/agents/llms.direction.txt +51 -0
- package/agents/llms.dismiss.txt +79 -0
- package/agents/llms.floating.txt +47 -0
- package/agents/llms.index.txt +46 -0
- package/agents/llms.menu-sub.txt +66 -0
- package/agents/llms.menu.txt +94 -0
- package/agents/llms.overlay.txt +122 -0
- package/agents/llms.sinwan-preload.txt +33 -0
- package/agents/llms.slot.txt +51 -0
- package/agents/llms.theme.txt +59 -0
- package/agents/llms.txt +45 -0
- package/agents/llms.types.txt +39 -0
- package/dist/chunks/chunk-7c8ct63g.js +126 -0
- package/dist/chunks/{chunk-16d43dkc.js → chunk-assqp8wg.js} +86 -13
- package/dist/chunks/{chunk-saen52f0.js → chunk-eczk2z48.js} +26 -14
- package/dist/chunks/{chunk-f6hw8ash.js → chunk-fe933s8d.js} +2 -2
- package/dist/chunks/chunk-rxbeqj7g.js +65 -0
- package/dist/chunks/{chunk-0dsacv44.js → chunk-s84my297.js} +124 -27
- package/dist/chunks/{chunk-6bm550r5.js → chunk-w6wwgdg6.js} +205 -46
- package/dist/chunks/{chunk-bw9vp0y9.js → chunk-wjzadrvr.js} +54 -0
- package/dist/chunks/{chunk-zmvg5gy1.js → chunk-y1ag4hk4.js} +57 -9
- package/dist/controls.d.ts +4 -0
- package/dist/controls.js +4 -4
- package/dist/core.d.ts +8 -0
- package/dist/core.js +4 -2
- package/dist/direction.d.ts +7 -1
- package/dist/direction.js +1 -1
- package/dist/dismiss.d.ts +18 -0
- package/dist/dismiss.js +9 -3
- package/dist/floating.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +54 -26
- package/dist/internal/controlled.d.ts +1 -0
- package/dist/internal/form.d.ts +6 -0
- package/dist/internal/ids.d.ts +8 -0
- package/dist/internal/modal.d.ts +8 -0
- package/dist/menu-sub.d.ts +10 -2
- package/dist/menu-sub.js +3 -2
- package/dist/menu.d.ts +66 -0
- package/dist/menu.js +16 -0
- package/dist/overlay.d.ts +27 -2
- package/dist/overlay.js +6 -4
- package/dist/slot.d.ts +1 -0
- package/dist/slot.js +1 -1
- package/dist/theme.d.ts +30 -2
- package/dist/theme.js +5 -1
- package/dist/types.d.ts +1 -0
- package/package.json +16 -7
- package/dist/chunks/chunk-9whagkb6.js +0 -31
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,58 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this package are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this package uses [Semantic Versioning](https://semver.org/).
|
|
4
4
|
|
|
5
|
+
## [2.0.0] — Layer Stack, Modal Dialogs, Form Controls, Accessible Tooltips, Agent Docs
|
|
6
|
+
|
|
7
|
+
sinwan-ui-core 2.0.0 needs **sinwan >= 2.6.1** (part ids from the component tree).
|
|
8
|
+
|
|
9
|
+
### Breaking
|
|
10
|
+
|
|
11
|
+
- **`useDirection()` returns a `Computed<Direction>`**: read `.value` (it returned the direction at mount, so a mounted component kept the first value).
|
|
12
|
+
- **Modal dialogs lock page scroll and hide the page from screen readers** while open (`DialogRoot` `modal`, default `true`; `modal={false}` keeps the old behaviour).
|
|
13
|
+
- **`DialogKey` is `InjectionKey<DialogApi>`** (`OpenApi & { modal }`) and **`TooltipKey` is `InjectionKey<TooltipApi>`** (`scheduleOpen`, `cancelOpen`, `contentId`).
|
|
14
|
+
- **Peer `sinwan` is `>=2.6.1 <3.0.0`.**
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- **Dismiss layer stack** (`sinwan-ui-core/dismiss`): `useDismissLayer(open)` (`layer.isTop()`), `pushDismissLayer`, `isTopDismissLayer`. Dialog, Popover and Tooltip use it; sinwan-ui's menus, Select and Navigation Menu join it.
|
|
19
|
+
- **`TooltipProviderKey`**, `TooltipRoot` `delayDuration`; `SwitchRoot` `name`/`value`.
|
|
20
|
+
- **Agent docs** (`agents/`, shipped in the package): one `agents/llms.<name>.txt` per source file (`agents/internal/…` for `src/internal`) and a root `agents/llms.txt` with the rules for building components on the primitives. Every `dist/**/*.d.ts` starts with a pointer to its doc.
|
|
21
|
+
- **`check:agents`** script (in CI and the new `prepublishOnly`: typecheck, export map, agent docs, tests, build).
|
|
22
|
+
- **Menu keyboard** (`sinwan-ui-core/menu`, agents/llms.menu.txt): `useMenuFocus` (focus into a menu when it opens — the first item after a keyboard opening, the menu itself after a click — and back to the trigger when it closes; Tab closes), `handleMenuKeyDown` (ArrowDown / ArrowUp wrapping, Home / End, typeahead), `getMenuItems`, `focusMenuItem`, `isKeyboardClick`, `MENU_ITEM_SELECTOR`. sinwan-ui's dropdown menu, context menu and menubar use them.
|
|
23
|
+
- **`usePartId(prefix)`** (`sinwan-ui-core/core`): ids for `aria-controls` / `aria-activedescendant` targets, equal on the server and after hydration.
|
|
24
|
+
- **`MenuSubApi.openedByKeyboard`**; `MenuSubTriggerHandlers.onClick(event?)` takes the click event.
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
- **A controlled value arrived one poll late**: `useControllableState` polled it every 16 ms (a timer per controlled instance until unmount). It now follows the value with an effect.
|
|
29
|
+
- **`asChild` lost the child's `ref` and `style`**: `Slot` composes refs (both called) and merges styles (objects per property, strings joined, the slot wins).
|
|
30
|
+
- **One Escape closed every open layer** (a popover in a dialog closed both): only the topmost layer handles Escape.
|
|
31
|
+
- **A closing popover reported `onOpenChange(false)` again** on Escape during its exit animation.
|
|
32
|
+
- **Server-rendered ids did not match after hydration**: dialog and tab ids came from page counters that grow per server request; they now come from the component's position in the tree.
|
|
33
|
+
- **Checkbox, Switch and RadioGroup were not part of forms**: with a `name`, a hidden input submits their value, and form reset restores their default.
|
|
34
|
+
- **`ToggleGroupItem` had no pressed state for screen readers**: `aria-pressed` (multiple) or `role="radio"` + `aria-checked` (single).
|
|
35
|
+
- **Tooltips**: `delayDuration` is honoured, the trigger has `aria-describedby` while open, Escape closes, and moving onto the tooltip keeps it open (100 ms close delay; no reopen lock).
|
|
36
|
+
- **Submenus opened with ArrowRight in right-to-left layouts**: ArrowLeft there.
|
|
37
|
+
- **Submenus had no keyboard inside**: `MenuSubContentLayer` is `role="menu"`; a sub opened with a key (or Enter / Space on its trigger) focuses its first item, Arrow keys move between its items, and ArrowLeft (ArrowRight in right to left) or Escape closes it and refocuses its trigger without closing the parent menu.
|
|
38
|
+
- **`asChild` triggers lost their ARIA**: `CollapsibleTrigger`, `PopoverTrigger` and `DialogTrigger` with `asChild` now set `aria-expanded` (the child keeps its own `data-slot`); `DialogTrigger` and `PopoverTrigger` also set `aria-haspopup="dialog"`.
|
|
39
|
+
|
|
40
|
+
## [1.6.0]
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- **Custom palettes, discovered from your stylesheet.** Write a palette in the same structure as the built-in ones (`html[data-palette="ocean"]` for light, `html[data-palette="ocean"].dark` for dark, and `html[data-palette="ocean"]:not(.light)` inside `@media (prefers-color-scheme: dark)`) in your `global.css`, then use it like a built-in: `<ThemeProvider defaultPalette="ocean">`, `forcedPalette="ocean"` or `setPalette("ocean")`. When `palettes` is omitted, `ThemeProvider` scans the page's stylesheets (inside `@media`, `@supports`, `@layer` and `@import` too, quoted or minified selectors) and lists every palette they define in `useTheme().palettes`, `carzow` first. It scans again on mount, when `setPalette` gets an unknown name, and on `refreshPalettes()`, so CSS that loads late still counts and a saved custom palette is restored. A palette under `:not(...)` is not counted. Cross-origin stylesheets cannot be read: pass `palettes` explicitly for those. When no stylesheet defines a palette (no DOM, tests), the list is the four built-ins, as before.
|
|
45
|
+
- `discoverPalettes(document?)`, `BUILT_IN_PALETTES`, the `BuiltInPalette` type and `ThemeApi.refreshPalettes()`.
|
|
46
|
+
|
|
47
|
+
### Changed
|
|
48
|
+
|
|
49
|
+
- `Palette` is now `BuiltInPalette | string`: any palette name type-checks, and the built-in names still autocomplete. `setPalette` still ignores a name that is not in the allowed list.
|
|
50
|
+
- **Breaking:** `ThemeApi.palettes` is a `Signal<Palette[]>` (like `palette` and `theme`), so a palette picker updates when new palettes are found. Read `palettes.value` instead of `palettes`. No alias is kept because sinwan-ui has no consumers outside the registry yet.
|
|
51
|
+
- An explicit `palettes` list is used as given and skips discovery, as before. `palettes={[]}` now means "discover", which falls back to the built-ins as before when nothing is found.
|
|
52
|
+
|
|
53
|
+
### Fixed
|
|
54
|
+
|
|
55
|
+
- The source of `src/internal/controlled.ts` (SW202 guard, 1.5.1) typechecks without Node or Bun types: it declares the `process.env.NODE_ENV` it reads. Builds are unchanged.
|
|
56
|
+
|
|
5
57
|
## [1.5.1]
|
|
6
58
|
|
|
7
59
|
### Fixed
|
package/README.md
CHANGED
|
@@ -30,9 +30,37 @@ Import from the root barrel or from a subpath (subpaths keep bundles small):
|
|
|
30
30
|
| `sinwan-ui-core/menu-sub` | `createMenuSubApi` (closes with its `parentOpen`), `createMenuSubTriggerHandlers`, `isInsideMenuSubContent`, `MenuSubContentLayer` for nested menus |
|
|
31
31
|
| `sinwan-ui-core/slot` | `Slot` (the `asChild` prop merge) |
|
|
32
32
|
| `sinwan-ui-core/types` | Intrinsic prop aliases, `isSinwanElement`, `flattenChildren` |
|
|
33
|
-
| `sinwan-ui-core/theme` | `ThemeProvider`, `useTheme`, `ThemeToggle` (unstyled), `ThemeKey` |
|
|
33
|
+
| `sinwan-ui-core/theme` | `ThemeProvider`, `useTheme`, `ThemeToggle` (unstyled), `ThemeKey`, `discoverPalettes`, `BUILT_IN_PALETTES` (see [Palettes](#palettes)) |
|
|
34
34
|
| `sinwan-ui-core/direction` | `DirectionProvider`, `useDirection`, `DirectionKey` |
|
|
35
35
|
|
|
36
|
+
## Palettes
|
|
37
|
+
|
|
38
|
+
`ThemeProvider` writes the light/dark mode as a class (`.light`/`.dark`) and the palette as `html[data-palette]`. The registry stylesheet ships `carzow` (the `:root` default), `jomlaty`, `cazview` and `voltzig`.
|
|
39
|
+
|
|
40
|
+
To add your own, write it in your stylesheet in the same structure as the built-in ones:
|
|
41
|
+
|
|
42
|
+
```css
|
|
43
|
+
html[data-palette="ocean"] { --background: …; --primary: …; /* every token */ }
|
|
44
|
+
html[data-palette="ocean"].dark { --background: …; --primary: …; }
|
|
45
|
+
@media (prefers-color-scheme: dark) {
|
|
46
|
+
html[data-palette="ocean"]:not(.light) { /* the .dark tokens again */ }
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Then use it by name. Nothing to register: without a `palettes` prop, `ThemeProvider` reads the page's stylesheets and allows every palette they define.
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
<ThemeProvider defaultPalette="ocean">…</ThemeProvider>
|
|
54
|
+
|
|
55
|
+
const { palette, palettes, setPalette } = useTheme();
|
|
56
|
+
palettes.value; // ["carzow", "jomlaty", "cazview", "voltzig", "ocean"]
|
|
57
|
+
setPalette("ocean");
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
- A token the palette leaves out keeps its `carzow` value, so define every color token in both modes.
|
|
61
|
+
- Pass `palettes={[…]}` to allow a fixed list instead (needed for cross-origin stylesheets, whose rules the page cannot read).
|
|
62
|
+
- For CSS loaded after the provider mounts, `setPalette(name)` scans again for an unknown name, and `refreshPalettes()` rescans on demand.
|
|
63
|
+
|
|
36
64
|
## Styling contract
|
|
37
65
|
|
|
38
66
|
Every primitive renders a `data-slot` and, where relevant, `data-state` (`open`/`closed`, `checked`/`unchecked`, `on`/`off`, `active`/`inactive`) and `data-side`. Style those attributes from your component layer. `Presence` keeps closing content mounted for `exitMs` (200 ms by default), so exit animations must hold their last keyframe (`animation-fill-mode: forwards`) and finish within that time.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# sinwan-ui-core — internal/controlled
|
|
2
|
+
|
|
3
|
+
> Source: src/internal/controlled.ts · Import: internal (used by every controllable root) · Types: dist/internal/controlled.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
One rule for "controlled": a root is controlled through a prop when the prop is present, even if its value is `undefined`. In development, a present `undefined` value warns SW202, because the control would ignore input.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `isControlledProp(props, key, component): boolean` — `key in props`; in development (`process.env.NODE_ENV !== "production"`), warns `SW202` when the current value (a getter is called) is `undefined`: `<TabsRoot> value is undefined: the control is controlled with no value and ignores input. Omit value, or pass null or "" for an empty controlled value.`
|
|
12
|
+
|
|
13
|
+
## How it works
|
|
14
|
+
|
|
15
|
+
The check is guarded by `process.env.NODE_ENV`, left as is in `dist/`: the app's bundler replaces it, so production builds drop the warning and its text. The warning goes through `devWarn` from `sinwan/dev`, which prints only with Sinwan's development build (the plugins pick it outside production).
|
|
16
|
+
|
|
17
|
+
## Examples
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
// browser (happy-dom), compiled by sinwan-compiler, development
|
|
21
|
+
import { TabsRoot } from "sinwan-ui-core/controls";
|
|
22
|
+
import { mount } from "sinwan/renderer";
|
|
23
|
+
|
|
24
|
+
const warnings: string[] = [];
|
|
25
|
+
console.warn = (...args: unknown[]) => void warnings.push(String(args[0]));
|
|
26
|
+
let selected: string | undefined;
|
|
27
|
+
mount(() => <TabsRoot value={selected} />, document.createElement("div"));
|
|
28
|
+
console.log(warnings.some((w) => w.includes("SW202"))); // true
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Pitfalls
|
|
32
|
+
|
|
33
|
+
- `value={state.value}` with a state that starts `undefined` makes the control controlled and frozen: start with `""` or `null`, or omit the prop until you have a value.
|
|
34
|
+
- `ToggleRoot` uses its own `"pressed" in props` check and does not warn.
|
|
35
|
+
|
|
36
|
+
## Related
|
|
37
|
+
|
|
38
|
+
- llms.core.txt — `useControllableState`
|
|
39
|
+
- ../llms.controls.txt, ../llms.overlay.txt — the roots
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# sinwan-ui-core — internal/form
|
|
2
|
+
|
|
3
|
+
> Source: src/internal/form.ts · Import: internal (Checkbox, Switch, RadioGroup) · Types: dist/internal/form.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Form reset for controls that keep their own state: when the `<form>` of a control's hidden input is reset, the control returns to its default.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `useFormReset(input: () => HTMLInputElement | null, reset: () => void): void` — call in a component body; on mount, listens to the input's form `reset` event and runs `reset` after the browser reset the fields. Nothing happens without an input or a form.
|
|
12
|
+
|
|
13
|
+
## How it works
|
|
14
|
+
|
|
15
|
+
`input()?.form` on mount; the listener is removed on unmount.
|
|
16
|
+
|
|
17
|
+
## Examples
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
// browser (happy-dom), compiled by sinwan-compiler: through a checkbox in a form
|
|
21
|
+
import { CheckboxRoot } from "sinwan-ui-core/controls";
|
|
22
|
+
import { mount } from "sinwan/renderer";
|
|
23
|
+
import { nextTick } from "sinwan/reactivity";
|
|
24
|
+
|
|
25
|
+
const root = document.createElement("div");
|
|
26
|
+
document.body.appendChild(root);
|
|
27
|
+
mount(() => <form><CheckboxRoot name="terms" defaultChecked={false} /></form>, root);
|
|
28
|
+
root.querySelector<HTMLElement>("[role=checkbox]")!.click();
|
|
29
|
+
await nextTick();
|
|
30
|
+
console.log(root.querySelector("[role=checkbox]")!.getAttribute("aria-checked")); // true
|
|
31
|
+
root.querySelector("form")!.reset();
|
|
32
|
+
await nextTick();
|
|
33
|
+
await nextTick();
|
|
34
|
+
console.log(root.querySelector("[role=checkbox]")!.getAttribute("aria-checked")); // false
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Pitfalls
|
|
38
|
+
|
|
39
|
+
- The control needs a `name` (no hidden input, no reset).
|
|
40
|
+
|
|
41
|
+
## Related
|
|
42
|
+
|
|
43
|
+
- ../llms.controls.txt — the controls
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# sinwan-ui-core — internal/ids
|
|
2
|
+
|
|
3
|
+
> Source: src/internal/ids.ts · Import: internal (Dialog, Tooltip, Tabs) · Types: dist/internal/ids.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Ids that link parts (`aria-labelledby`, `aria-controls`, `aria-describedby`) and survive server rendering: the same in the server HTML and after `hydrate`.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `treeId(prefix): string` — call in a component body. With a tree position (server renders and `hydrate`, sinwan 2.6.1+): `sinwan-ui-<prefix>-t<path>` (`sinwan-ui-tabs-t0_1_2`). Without one (`mount`): `sinwan-ui-<prefix>-<n>`, unique in the page.
|
|
12
|
+
|
|
13
|
+
## How it works
|
|
14
|
+
|
|
15
|
+
Reads `getCurrentInstance().idPath`, the component's position in the tree, which Sinwan assigns identically on the server and while hydrating.
|
|
16
|
+
|
|
17
|
+
## Examples
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
// browser (happy-dom), compiled by sinwan-compiler: ids through Tabs
|
|
21
|
+
import { TabsList, TabsRoot, TabsTrigger } from "sinwan-ui-core/controls";
|
|
22
|
+
import { mount } from "sinwan/renderer";
|
|
23
|
+
|
|
24
|
+
export function Tabs() {
|
|
25
|
+
return (
|
|
26
|
+
<TabsRoot defaultValue="a">
|
|
27
|
+
<TabsList>
|
|
28
|
+
<TabsTrigger value="a">A</TabsTrigger>
|
|
29
|
+
</TabsList>
|
|
30
|
+
</TabsRoot>
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const first = document.createElement("div");
|
|
34
|
+
const second = document.createElement("div");
|
|
35
|
+
mount(Tabs, first);
|
|
36
|
+
mount(Tabs, second);
|
|
37
|
+
console.log(first.querySelector("[role=tab]")!.id !== second.querySelector("[role=tab]")!.id); // true
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Pitfalls
|
|
41
|
+
|
|
42
|
+
- Call during setup (it reads the current component).
|
|
43
|
+
|
|
44
|
+
## Related
|
|
45
|
+
|
|
46
|
+
- ../llms.controls.txt, ../llms.overlay.txt — the parts that use it
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# sinwan-ui-core — internal/modal
|
|
2
|
+
|
|
3
|
+
> Source: src/internal/modal.ts · Import: internal (modal `DialogContent`) · Types: dist/internal/modal.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
What a modal layer does to the rest of the page while open: no page scroll, and screen readers stay in the layer.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `enterModal(layer: HTMLElement): () => void` — locks `body` scroll (`overflow: hidden`, the scrollbar width added as `padding-right`) and sets `aria-hidden="true"` on the other top-level children of `body` (not on live regions `[aria-live]`, overlays `[data-slot$='-overlay']`, `[data-sinwan-keep-visible]`, scripts and styles, nor on elements already hidden). Returns the release, which restores exactly what it changed. Locks nest: scroll comes back when the last one is released.
|
|
12
|
+
|
|
13
|
+
## How it works
|
|
14
|
+
|
|
15
|
+
A module counter for the scroll lock (the body's previous `overflow`/`padding-right` saved by the first lock); each call records the elements it hid.
|
|
16
|
+
|
|
17
|
+
## Examples
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
// browser (happy-dom), compiled by sinwan-compiler: through a modal dialog
|
|
21
|
+
import { DialogContent, DialogRoot, DialogTitle } from "sinwan-ui-core/overlay";
|
|
22
|
+
import { mount } from "sinwan/renderer";
|
|
23
|
+
import { nextTick, signal } from "sinwan/reactivity";
|
|
24
|
+
|
|
25
|
+
const toasts = document.createElement("section");
|
|
26
|
+
toasts.setAttribute("aria-live", "polite");
|
|
27
|
+
document.body.appendChild(toasts);
|
|
28
|
+
const open = signal(true);
|
|
29
|
+
const app = document.createElement("main");
|
|
30
|
+
document.body.appendChild(app);
|
|
31
|
+
mount(() => (
|
|
32
|
+
<DialogRoot open={open.value} onOpenChange={(v: boolean) => (open.value = v)}>
|
|
33
|
+
<DialogContent>
|
|
34
|
+
<DialogTitle>T</DialogTitle>
|
|
35
|
+
</DialogContent>
|
|
36
|
+
</DialogRoot>
|
|
37
|
+
), app);
|
|
38
|
+
await nextTick();
|
|
39
|
+
console.log(document.body.style.overflow, app.getAttribute("aria-hidden"), toasts.hasAttribute("aria-hidden")); // hidden true false
|
|
40
|
+
open.value = false;
|
|
41
|
+
await nextTick();
|
|
42
|
+
console.log(document.body.style.overflow === "", app.hasAttribute("aria-hidden")); // true false
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Pitfalls
|
|
46
|
+
|
|
47
|
+
- Mark app-level layers that must stay reachable while a dialog is open (a toaster without `aria-live`) with `data-sinwan-keep-visible`.
|
|
48
|
+
|
|
49
|
+
## Related
|
|
50
|
+
|
|
51
|
+
- ../llms.overlay.txt — `DialogRoot`'s `modal`
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# sinwan-ui-core — controls
|
|
2
|
+
|
|
3
|
+
> Source: src/controls.tsx · Import: sinwan-ui-core/controls (also sinwan-ui-core) · Types: dist/controls.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Headless value controls: Tabs and RadioGroup (WAI-ARIA keyboard, one tab stop), Accordion, Checkbox, Switch, Toggle and ToggleGroup. Each root holds its value (controlled or not), provides it to its parts through an injection key, and renders the ARIA roles and `data-state` attributes the styled sinwan-ui components target.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
Controlled/uncontrolled: every root takes `value`/`defaultValue`/`onValueChange` (or `checked`/`defaultChecked`/`onCheckedChange`, `pressed`/`defaultPressed`/`onPressedChange`). Passing the value prop makes it controlled (SW202 when `undefined`; Toggle does not warn).
|
|
12
|
+
|
|
13
|
+
- **Tabs** — `TabsRoot({ value?, defaultValue?, onValueChange?, orientation?, class? })` (`TabsKey`), `TabsList({ class?, data-variant?, aria-* })` (`role="tablist"`), `TabsTrigger({ value, disabled?, class? })` (`role="tab"`, `aria-selected`, `aria-controls`, one tab stop; Arrow keys (Left/Right horizontal, Up/Down vertical, swapped in RTL), Home and End move focus and select), `TabsContent({ value, class? })` (`role="tabpanel"`, mounted only while active).
|
|
14
|
+
- **RadioGroup** — `RadioGroupRoot({ value?, defaultValue?, onValueChange?, name?, class?, aria-* })` (`role="radiogroup"`, `RadioGroupKey`; with a `name`, a hidden input submits the selected value, nothing when none), `RadioGroupItem({ value, disabled?, id?, class? })` (`role="radio"`, `aria-checked`, one tab stop, arrows move focus and selection, wrapping, RTL-aware).
|
|
15
|
+
- **Accordion** — `AccordionRoot({ type? = "single" | "multiple", value?, defaultValue?, onValueChange?, collapsible? = true, class? })` (`AccordionKey`; `onValueChange` gets a string for `single`, an array for `multiple`), `AccordionItem({ value })` (`AccordionItemKey`), `AccordionTrigger` (`aria-expanded`), `AccordionContent` (`Presence`, `--radix-accordion-content-height`).
|
|
16
|
+
- **Checkbox** — `CheckboxRoot({ checked?, defaultChecked?, indeterminate?, onCheckedChange?, disabled?, id?, name?, value?, aria-label?, class? })` (`role="checkbox"`, `aria-checked` true/false/`"mixed"`; a click on an indeterminate box checks it). With a `name`, a hidden input takes part in its `<form>`: submitted as `name=value` (default `"on"`) only when checked and enabled.
|
|
17
|
+
- **Switch** — `SwitchRoot({ checked?, defaultChecked?, onCheckedChange?, disabled?, id?, name?, value?, data-size?, aria-* })` (`role="switch"`; with a `name`, submitted like a checkbox).
|
|
18
|
+
- **Toggle** — `ToggleRoot({ pressed?, defaultPressed?, onPressedChange?, disabled? })` (`aria-pressed`).
|
|
19
|
+
- **ToggleGroup** — `ToggleGroupRoot({ type?, value?, defaultValue?, onValueChange?, style?, data-*, aria-* })` (`role="group"`, `ToggleGroupKey`), `ToggleGroupItem({ value, disabled?, data-* })` (`data-state="on"|"off"`; `type="single"`: `role="radio"` + `aria-checked`, `"multiple"`: `aria-pressed`).
|
|
20
|
+
- **Form reset**: Checkbox, Switch and RadioGroup with a `name` return to their default when their form is reset (uncontrolled: their own state; controlled: through the change callback).
|
|
21
|
+
- Types: `AriaProps`, `RadioGroupEntry`, `RovingMove`. Re-exports `For`, `Show`, `Slot`.
|
|
22
|
+
|
|
23
|
+
## How it works
|
|
24
|
+
|
|
25
|
+
Roots create a local signal (or a `computed` of the controlled prop) and a setter that writes the local signal only when uncontrolled, then calls the change callback. Tabs and RadioGroup register their items in a roving-focus list (from each item's `ref`) and sort it in document order on keydown. Ids for `aria-controls`/`aria-labelledby` come from the component's position in the tree (`sinwan-ui-tabs-t0_1_2-…`), the same in server HTML and after hydration; under `mount` they are unique in the page (internal/llms.ids.txt).
|
|
26
|
+
|
|
27
|
+
## Examples
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
// browser (happy-dom), compiled by sinwan-compiler
|
|
31
|
+
import { CheckboxRoot, RadioGroupItem, RadioGroupRoot, TabsContent, TabsList, TabsRoot, TabsTrigger } from "sinwan-ui-core/controls";
|
|
32
|
+
import { mount } from "sinwan/renderer";
|
|
33
|
+
import { nextTick, signal } from "sinwan/reactivity";
|
|
34
|
+
|
|
35
|
+
const size = signal("m");
|
|
36
|
+
export function Form() {
|
|
37
|
+
return (
|
|
38
|
+
<main>
|
|
39
|
+
<RadioGroupRoot aria-label="Size" value={size.value} onValueChange={(v: string) => (size.value = v)}>
|
|
40
|
+
<RadioGroupItem value="s">S</RadioGroupItem>
|
|
41
|
+
<RadioGroupItem value="m">M</RadioGroupItem>
|
|
42
|
+
<RadioGroupItem value="l">L</RadioGroupItem>
|
|
43
|
+
</RadioGroupRoot>
|
|
44
|
+
<CheckboxRoot defaultChecked name="gift" aria-label="Gift wrap" />
|
|
45
|
+
<TabsRoot defaultValue="details">
|
|
46
|
+
<TabsList aria-label="Product">
|
|
47
|
+
<TabsTrigger value="details">Details</TabsTrigger>
|
|
48
|
+
<TabsTrigger value="reviews">Reviews</TabsTrigger>
|
|
49
|
+
</TabsList>
|
|
50
|
+
<TabsContent value="details">Cotton</TabsContent>
|
|
51
|
+
<TabsContent value="reviews">5 stars</TabsContent>
|
|
52
|
+
</TabsRoot>
|
|
53
|
+
</main>
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const root = document.createElement("div");
|
|
58
|
+
document.body.appendChild(root);
|
|
59
|
+
mount(Form, root);
|
|
60
|
+
const medium = root.querySelector<HTMLElement>("[role=radio][aria-checked=true]")!;
|
|
61
|
+
medium.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
|
|
62
|
+
await nextTick();
|
|
63
|
+
console.log(size.value, [...root.querySelectorAll("[role=radio]")].map((r) => r.getAttribute("tabindex")).join(",")); // l -1,-1,0
|
|
64
|
+
root.querySelector<HTMLElement>("[role=checkbox]")!.click();
|
|
65
|
+
root.querySelectorAll<HTMLElement>("[role=tab]")[1]!.click();
|
|
66
|
+
await nextTick();
|
|
67
|
+
console.log(root.querySelector("[role=checkbox]")!.getAttribute("aria-checked"), root.querySelector("[role=tabpanel]")!.textContent); // false 5 stars
|
|
68
|
+
console.log(root.querySelector<HTMLInputElement>("input[name=gift]")!.disabled); // true
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Pitfalls
|
|
72
|
+
|
|
73
|
+
- Pass `name` for the control to be submitted with its form (no `name`: no hidden input).
|
|
74
|
+
- `TabsContent` unmounts inactive panels: state inside a panel is lost when switching tabs.
|
|
75
|
+
- `AccordionRoot` `collapsible` defaults to `true` (Radix's default is `false`).
|
|
76
|
+
- Before 2.0.0: Checkbox, Switch and RadioGroup were not part of forms; `ToggleGroupItem` had no `aria-pressed`/`aria-checked`; tab ids came from a page counter (server and hydration ids differed).
|
|
77
|
+
|
|
78
|
+
## Related
|
|
79
|
+
|
|
80
|
+
- llms.overlay.txt — Collapsible (one item), Dialog, Popover
|
|
81
|
+
- llms.direction.txt — RTL arrow keys
|
|
82
|
+
- internal/llms.controlled.txt — SW202
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# sinwan-ui-core — core
|
|
2
|
+
|
|
3
|
+
> Source: src/core.tsx · Import: sinwan-ui-core/core (also sinwan-ui-core) · Types: dist/core.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
The building blocks the other primitives share: `Presence` keeps content mounted while a CSS exit animation plays, `UiPortal` renders into `document.body` (or a container), `useControllableState` is the controlled/uncontrolled value pattern, and `getFocusableElements`/`trapFocus` keep Tab inside a layer. It also re-exports the positioning helpers of llms.floating.txt.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `Presence(props: PresenceProps)` — `{ present?: boolean; exitMs?: number = 200; children? }`. Mounts children when `present` turns true; when it turns false they stay `exitMs` milliseconds (for a `data-state="closed"` CSS animation), then unmount. `exitMs <= 0` unmounts at once.
|
|
12
|
+
- `UiPortal(props: UiPortalProps)` — `{ children?; container?: HTMLElement | null | (() => HTMLElement | null) }` (default `document.body`), on `Portal` from `sinwan/control-flow`.
|
|
13
|
+
- `useControllableState<T>({ value?, defaultValue, onChange? }): [Signal<T>, setState]` — controlled when the options object has a `value` key (a value or a getter `() => T`): `setState` only calls `onChange`, and the signal follows `value`. Otherwise the signal holds the state. `setState` takes a value or an updater. Call in a component body. A present but `undefined` `value` warns SW202 in development (llms.controlled.txt in internal/).
|
|
14
|
+
- `usePartId(prefix: string): string` — an id for a part's element (`sinwan-ui-<prefix>-<n>`), equal on the server and after hydration (llms.ids.txt in internal/); use it for `aria-controls` / `aria-activedescendant` targets. Call in a component body, once per prefix in that component.
|
|
15
|
+
- `getFocusableElements(root): HTMLElement[]` — links, enabled buttons/inputs/selects/textareas, and `[tabindex]` other than `-1`.
|
|
16
|
+
- `trapFocus(event: KeyboardEvent, root)` — on Tab/Shift+Tab at the last/first focusable, wraps to the other end.
|
|
17
|
+
- Re-exports (llms.floating.txt): `basePlacement`, `computePosition`, `createPointReference`, `createRectReference`, `createSizeFloating`, `estimatePosition`, `readDocumentRtl`, `toFloatingPlacement`, `useAnchorPosition`, `usePointPosition`, types `Align`, `FloatingPosition`, `FloatingStyle`, `Placement`, `RectLike`, `UseAnchorPositionOptions`, `UsePointPositionOptions`; and `signal`, `Show`, `SinwanPortal` (Sinwan's `Portal`).
|
|
18
|
+
|
|
19
|
+
Types: `PresenceProps`, `UiPortalProps`.
|
|
20
|
+
|
|
21
|
+
## How it works
|
|
22
|
+
|
|
23
|
+
`Presence` keeps a `mounted` signal that follows `present` with a timer on the way out, and renders `<Show when={mounted}>`. `useControllableState` copies the controlled value into its signal with an effect over the `value` getter, so it follows in the same flush (no timer; the effect is disposed with the component).
|
|
24
|
+
|
|
25
|
+
## Examples
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
// browser (happy-dom), compiled by sinwan-compiler
|
|
29
|
+
import { Presence, useControllableState } from "sinwan-ui-core/core";
|
|
30
|
+
import { mount } from "sinwan/renderer";
|
|
31
|
+
import { nextTick, signal } from "sinwan/reactivity";
|
|
32
|
+
|
|
33
|
+
const open = signal(true);
|
|
34
|
+
export function Fade() {
|
|
35
|
+
return (
|
|
36
|
+
<Presence present={open.value} exitMs={50}>
|
|
37
|
+
<p data-state={open.value ? "open" : "closed"}>hello</p>
|
|
38
|
+
</Presence>
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Uncontrolled unless the caller passes `value`.
|
|
43
|
+
export function Counter(props: { value?: number; onChange?: (n: number) => void }) {
|
|
44
|
+
const [count, setCount] = useControllableState({ ...("value" in props ? { value: () => props.value ?? 0 } : {}), defaultValue: 0, onChange: props.onChange });
|
|
45
|
+
return <button onclick={() => setCount((n) => n + 1)}>{count.value}</button>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const root = document.createElement("div");
|
|
49
|
+
document.body.appendChild(root); // click handlers are delegated from the document
|
|
50
|
+
const app = mount(() => <main><Fade /><Counter /></main>, root);
|
|
51
|
+
open.value = false;
|
|
52
|
+
await nextTick();
|
|
53
|
+
console.log(root.querySelector("p")?.dataset.state); // closed
|
|
54
|
+
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
55
|
+
root.querySelector("button")!.click();
|
|
56
|
+
await nextTick();
|
|
57
|
+
console.log(root.textContent); // 1
|
|
58
|
+
app.unmount();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Pitfalls
|
|
62
|
+
|
|
63
|
+
- **Pass `value` only when controlling**: a present `value` key makes it controlled even when `undefined` (SW202). Spread it conditionally, as in the example.
|
|
64
|
+
- `trapFocus` only reacts to Tab inside the root; it does not make the rest of the page inert (llms.overlay.txt).
|
|
65
|
+
- `Presence` decides on `present` only: the exit animation must fit in `exitMs`.
|
|
66
|
+
- A controlled `value` that becomes `undefined` keeps the last value (SW202 reports it).
|
|
67
|
+
- Before 2.0.0: the controlled value was polled every 16 ms (one flush late, and a timer per controlled instance until unmount).
|
|
68
|
+
|
|
69
|
+
## Related
|
|
70
|
+
|
|
71
|
+
- llms.overlay.txt — dialogs, popovers and tooltips built on these
|
|
72
|
+
- llms.floating.txt — the positioning helpers re-exported here
|
|
73
|
+
- internal/llms.controlled.txt — `isControlledProp` and SW202
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# sinwan-ui-core — direction
|
|
2
|
+
|
|
3
|
+
> Source: src/direction.tsx · Import: sinwan-ui-core/direction (also sinwan-ui-core) · Types: dist/direction.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Text direction for a subtree: `DirectionProvider` renders a `dir` wrapper and provides the direction, so keyboard primitives (tabs, radio groups) swap Left/Right in right-to-left layouts.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `DirectionProvider({ dir?, children? })` — a `<div dir data-slot="direction-provider">`. With `dir` it follows the prop (live); without it, it starts `ltr` and `setDir` changes it.
|
|
12
|
+
- `DirectionKey: InjectionKey<DirectionApi>` — `DirectionApi`: `{ dir: { value: Direction }, setDir(dir) }` (`setDir` does nothing when `dir` is a prop). Components read `inject(DirectionKey)?.dir.value` where they need it (live).
|
|
13
|
+
- `useDirection(): Computed<Direction>` — the nearest provider's direction (`"ltr"` without one), live: read `dir.value` where it is used.
|
|
14
|
+
- Type `Direction` (`"ltr" | "rtl"`), `DirectionProviderProps`.
|
|
15
|
+
|
|
16
|
+
## How it works
|
|
17
|
+
|
|
18
|
+
`dir` is a signal (or a computed of the prop) behind `DirectionKey`; the wrapper's `dir` attribute and the controls' key handling read it.
|
|
19
|
+
|
|
20
|
+
## Examples
|
|
21
|
+
|
|
22
|
+
```tsx
|
|
23
|
+
// browser (happy-dom), compiled by sinwan-compiler
|
|
24
|
+
import { DirectionKey, DirectionProvider, useDirection } from "sinwan-ui-core/direction";
|
|
25
|
+
import { inject } from "sinwan/component";
|
|
26
|
+
import { mount } from "sinwan/renderer";
|
|
27
|
+
import { nextTick, signal } from "sinwan/reactivity";
|
|
28
|
+
|
|
29
|
+
const dir = signal<"ltr" | "rtl">("ltr");
|
|
30
|
+
export function Arrow() {
|
|
31
|
+
const dir = useDirection();
|
|
32
|
+
const api = inject(DirectionKey); // the same value, plus setDir
|
|
33
|
+
return <span title={api?.dir.value}>{dir.value === "rtl" ? "←" : "→"}</span>;
|
|
34
|
+
}
|
|
35
|
+
const root = document.createElement("div");
|
|
36
|
+
mount(() => <DirectionProvider dir={dir.value}><Arrow /></DirectionProvider>, root);
|
|
37
|
+
dir.value = "rtl";
|
|
38
|
+
await nextTick();
|
|
39
|
+
console.log(root.textContent, root.firstElementChild?.getAttribute("dir")); // ← rtl
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Pitfalls
|
|
43
|
+
|
|
44
|
+
- `const d = useDirection().value` in a body copies it once: keep the computed and read `.value` where it is used.
|
|
45
|
+
- Before 2.0.0: `useDirection()` returned the direction string at mount.
|
|
46
|
+
- The provider adds a `div`: for the whole page, set `<html dir>` instead (sinwan-i18n's `syncDocument`) and still wrap the app so the controls know the direction.
|
|
47
|
+
|
|
48
|
+
## Related
|
|
49
|
+
|
|
50
|
+
- llms.controls.txt — RTL arrow keys
|
|
51
|
+
- llms.menu-sub.txt — submenu keys
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# sinwan-ui-core — dismiss
|
|
2
|
+
|
|
3
|
+
> Source: src/dismiss.ts · Import: sinwan-ui-core/dismiss (also sinwan-ui-core) · Types: dist/dismiss.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Dismissal across stacked, portaled layers: one Escape closes only the topmost open layer (a popover inside a dialog closes alone), and a press in a portaled child layer (a Select list, a submenu, a dialog opened from a popover) is not "outside".
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `useDismissLayer(open: () => boolean): DismissLayer` — call in a component body: registers the layer on the stack while `open()` is true (removed when it turns false or the component unmounts). `DismissLayer.isTop()` is `true` for the most recently opened layer still open: check it in the layer's Escape handler. Dialog, Popover and Tooltip use it; so do sinwan-ui's menus and Select.
|
|
12
|
+
- `pushDismissLayer(token: object): () => void`, `isTopDismissLayer(token): boolean` — the same stack for code outside components.
|
|
13
|
+
- `isDismissExemptPointerTarget(target: EventTarget | null): boolean` — `true` when the target (or a text node's parent) is inside a layer: `[data-slot]` ending in `-menu-content` or `-sub-content`, `menubar-content`, `select-content`, `popover-content`, `dialog-content`, `alert-dialog-content`, `sheet-content`, `drawer-content`, any `*-overlay`, or a native `select`/`option`/`optgroup`.
|
|
14
|
+
|
|
15
|
+
## How it works
|
|
16
|
+
|
|
17
|
+
The stack is a module-level list of tokens (the newest last). Layers listen to `keydown` on `document`; each returns early unless `layer.isTop()`, so only the newest layer acts (layers removed when they close, so the next Escape reaches the one below). `isDismissExemptPointerTarget` is `closest()` with one selector list: a layer's document `pointerdown` handler returns early for exempt targets (and for its own trigger) and closes otherwise.
|
|
18
|
+
|
|
19
|
+
## Examples
|
|
20
|
+
|
|
21
|
+
```tsx
|
|
22
|
+
// browser (happy-dom), compiled by sinwan-compiler: a custom layer that joins the stack
|
|
23
|
+
import { useDismissLayer } from "sinwan-ui-core/dismiss";
|
|
24
|
+
import { DialogContent, DialogRoot, DialogTitle } from "sinwan-ui-core/overlay";
|
|
25
|
+
import { onMounted, onUnmounted } from "sinwan/component";
|
|
26
|
+
import { mount } from "sinwan/renderer";
|
|
27
|
+
import { nextTick, signal } from "sinwan/reactivity";
|
|
28
|
+
|
|
29
|
+
const panel = signal(true);
|
|
30
|
+
const dialog = signal(true);
|
|
31
|
+
export function Panel() {
|
|
32
|
+
const layer = useDismissLayer(() => panel.value);
|
|
33
|
+
onMounted(() => {
|
|
34
|
+
const onKey = (e: KeyboardEvent) => {
|
|
35
|
+
if (e.key === "Escape" && panel.value && layer.isTop()) panel.value = false;
|
|
36
|
+
};
|
|
37
|
+
document.addEventListener("keydown", onKey);
|
|
38
|
+
onUnmounted(() => document.removeEventListener("keydown", onKey));
|
|
39
|
+
});
|
|
40
|
+
return <div data-slot="panel-content">panel</div>;
|
|
41
|
+
}
|
|
42
|
+
mount(
|
|
43
|
+
() => (
|
|
44
|
+
<DialogRoot open={dialog.value} onOpenChange={(v: boolean) => (dialog.value = v)}>
|
|
45
|
+
<DialogContent>
|
|
46
|
+
<DialogTitle>Settings</DialogTitle>
|
|
47
|
+
<Panel />
|
|
48
|
+
</DialogContent>
|
|
49
|
+
</DialogRoot>
|
|
50
|
+
),
|
|
51
|
+
document.body,
|
|
52
|
+
);
|
|
53
|
+
await nextTick();
|
|
54
|
+
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
|
|
55
|
+
await nextTick();
|
|
56
|
+
console.log(panel.value, dialog.value); // false true
|
|
57
|
+
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
|
|
58
|
+
await nextTick();
|
|
59
|
+
console.log(dialog.value); // false
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
// browser (happy-dom)
|
|
64
|
+
import { isDismissExemptPointerTarget } from "sinwan-ui-core/dismiss";
|
|
65
|
+
|
|
66
|
+
document.body.innerHTML = `<div data-slot="select-content"><span id="opt">Paris</span></div><div data-slot="card-content"><b id="card">x</b></div>`;
|
|
67
|
+
console.log(isDismissExemptPointerTarget(document.getElementById("opt")), isDismissExemptPointerTarget(document.getElementById("card"))); // true false
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Pitfalls
|
|
71
|
+
|
|
72
|
+
- A press inside **any** popover or dialog content (also another unrelated one) does not close an open popover; layout slots such as `card-content` do close it.
|
|
73
|
+
- Your own layer components need one of these `data-slot` values to be treated as inside, and `useDismissLayer` to take part in Escape ordering.
|
|
74
|
+
- Before 2.0.0: there was no layer stack; one Escape closed every open dialog, popover, menu and select at once.
|
|
75
|
+
|
|
76
|
+
## Related
|
|
77
|
+
|
|
78
|
+
- llms.overlay.txt — Popover's outside press
|
|
79
|
+
- llms.menu-sub.txt — `isInsideMenuSubContent`
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# sinwan-ui-core — floating
|
|
2
|
+
|
|
3
|
+
> Source: src/floating.ts · Import: sinwan-ui-core/floating (also sinwan-ui-core, sinwan-ui-core/core) · Types: dist/floating.d.ts
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Positions a fixed layer (popover, tooltip, menu, submenu, context menu) next to a trigger or at a pointer, with `@floating-ui/dom` (offset, flip, shift) and its `autoUpdate` while open. Returns a style signal to bind on the layer.
|
|
8
|
+
|
|
9
|
+
## API
|
|
10
|
+
|
|
11
|
+
- `useAnchorPosition(options: UseAnchorPositionOptions): FloatingPosition` — call in a component body. Options: `open` and `trigger` (signals or computeds), `content?` (signal of the layer element, for its real size and `autoUpdate`), `placement?` (`"top" | "right" | "bottom" | "left"`, default bottom), `align?` (`"start" | "center" | "end"`), `gap?` (default 8), `fallbackSize?` (size before the layer is measured), `extra?(anchorRect)` (more style keys, e.g. `minWidth`).
|
|
12
|
+
- `usePointPosition(options: UsePointPositionOptions): FloatingPosition` — the same at `point` (a signal of `{ x, y }`), placement `bottom-start`.
|
|
13
|
+
- `FloatingPosition`: `style` (`Signal<FloatingStyle>`: `position: fixed`, `top`, `left`, `zIndex: 50`, plus `extra`), `ready`, `side` (the side after flipping, for `data-side`), `present` (a getter that places now and returns whether it is open).
|
|
14
|
+
- `computePosition(anchorRect, size, placement?, align?, gap?): Promise<{ top, left, placement }>` — one async Floating UI pass on a rect (falls back to `estimatePosition` on error). `estimatePosition(...)` — the synchronous first-paint position (offset and align, clamped 8 px inside the viewport, no flip).
|
|
15
|
+
- Helpers: `toFloatingPlacement(placement, align)` (`bottom-start`), `basePlacement("top-end")` (`top`), `createRectReference(rect)`, `createPointReference(x, y)`, `createSizeFloating(w, h)` (Floating UI virtual elements), `readDocumentRtl()`.
|
|
16
|
+
- Types: `Placement`, `Align`, `RectLike`, `VirtualClientRect`, `FloatingStyle`, `FloatingPosition`, `UseAnchorPositionOptions`, `UsePointPositionOptions`.
|
|
17
|
+
|
|
18
|
+
## How it works
|
|
19
|
+
|
|
20
|
+
On mount, an effect watches `open`, `trigger` and `content`: when open, it writes the estimated position at once, then refines asynchronously with Floating UI and keeps refining through `autoUpdate` (scroll, resize) until closed or unmounted. A generation counter drops results of stale passes.
|
|
21
|
+
|
|
22
|
+
## Examples
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// browser or any environment: one positioning pass without a component
|
|
26
|
+
import { computePosition, estimatePosition, toFloatingPlacement } from "sinwan-ui-core/floating";
|
|
27
|
+
import { Window } from "happy-dom";
|
|
28
|
+
|
|
29
|
+
const window = new Window({ width: 1024, height: 768 });
|
|
30
|
+
Object.assign(globalThis, { window, document: window.document });
|
|
31
|
+
const anchor = { top: 100, left: 200, bottom: 132, right: 300, width: 100, height: 32 };
|
|
32
|
+
console.log(JSON.stringify(estimatePosition(anchor, { width: 160, height: 80 }, "bottom", "start", 8)), toFloatingPlacement("top", "end")); // {"top":140,"left":200} top-end
|
|
33
|
+
const placed = await computePosition(anchor, { width: 160, height: 80 }, "bottom", "center", 8);
|
|
34
|
+
console.log(placed.top, placed.left, placed.placement); // 140 170 bottom
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Pitfalls
|
|
38
|
+
|
|
39
|
+
- **Options are read once**: `placement`, `align`, `gap` and `fallbackSize` are taken at setup; a prop that changes them later is ignored (remount the layer).
|
|
40
|
+
- Bind `content` to the layer's `ref` (`ref={(el) => (contentEl.value = el)}`): without it Floating UI uses `fallbackSize` and no `autoUpdate` runs.
|
|
41
|
+
- The layer is `position: fixed` with `z-index: 50`; a transformed ancestor breaks fixed positioning, so render layers in a portal (`UiPortal`).
|
|
42
|
+
- In tests (happy-dom) every rect is 0: positions are not meaningful there.
|
|
43
|
+
|
|
44
|
+
## Related
|
|
45
|
+
|
|
46
|
+
- llms.overlay.txt, llms.menu-sub.txt — the layers that use it
|
|
47
|
+
- llms.core.txt — re-exports these helpers
|