sinwan-ui-core 1.6.0 → 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.
Files changed (54) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/agents/internal/llms.controlled.txt +39 -0
  3. package/agents/internal/llms.form.txt +43 -0
  4. package/agents/internal/llms.ids.txt +46 -0
  5. package/agents/internal/llms.modal.txt +51 -0
  6. package/agents/llms.controls.txt +82 -0
  7. package/agents/llms.core.txt +73 -0
  8. package/agents/llms.direction.txt +51 -0
  9. package/agents/llms.dismiss.txt +79 -0
  10. package/agents/llms.floating.txt +47 -0
  11. package/agents/llms.index.txt +46 -0
  12. package/agents/llms.menu-sub.txt +66 -0
  13. package/agents/llms.menu.txt +94 -0
  14. package/agents/llms.overlay.txt +122 -0
  15. package/agents/llms.sinwan-preload.txt +33 -0
  16. package/agents/llms.slot.txt +51 -0
  17. package/agents/llms.theme.txt +59 -0
  18. package/agents/llms.txt +45 -0
  19. package/agents/llms.types.txt +39 -0
  20. package/dist/chunks/chunk-7c8ct63g.js +126 -0
  21. package/dist/chunks/{chunk-saen52f0.js → chunk-eczk2z48.js} +26 -14
  22. package/dist/chunks/{chunk-f6hw8ash.js → chunk-fe933s8d.js} +2 -2
  23. package/dist/chunks/chunk-rxbeqj7g.js +65 -0
  24. package/dist/chunks/{chunk-0dsacv44.js → chunk-s84my297.js} +124 -27
  25. package/dist/chunks/{chunk-6bm550r5.js → chunk-w6wwgdg6.js} +205 -46
  26. package/dist/chunks/{chunk-bw9vp0y9.js → chunk-wjzadrvr.js} +54 -0
  27. package/dist/chunks/{chunk-zmvg5gy1.js → chunk-y1ag4hk4.js} +57 -9
  28. package/dist/controls.d.ts +4 -0
  29. package/dist/controls.js +4 -4
  30. package/dist/core.d.ts +8 -0
  31. package/dist/core.js +4 -2
  32. package/dist/direction.d.ts +7 -1
  33. package/dist/direction.js +1 -1
  34. package/dist/dismiss.d.ts +18 -0
  35. package/dist/dismiss.js +9 -3
  36. package/dist/floating.d.ts +1 -0
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.js +49 -25
  39. package/dist/internal/controlled.d.ts +1 -0
  40. package/dist/internal/form.d.ts +6 -0
  41. package/dist/internal/ids.d.ts +8 -0
  42. package/dist/internal/modal.d.ts +8 -0
  43. package/dist/menu-sub.d.ts +10 -2
  44. package/dist/menu-sub.js +3 -2
  45. package/dist/menu.d.ts +66 -0
  46. package/dist/menu.js +16 -0
  47. package/dist/overlay.d.ts +27 -2
  48. package/dist/overlay.js +6 -4
  49. package/dist/slot.d.ts +1 -0
  50. package/dist/slot.js +1 -1
  51. package/dist/theme.d.ts +1 -0
  52. package/dist/types.d.ts +1 -0
  53. package/package.json +16 -7
  54. package/dist/chunks/chunk-9whagkb6.js +0 -31
@@ -0,0 +1,66 @@
1
+ # sinwan-ui-core — menu-sub
2
+
3
+ > Source: src/menu-sub.tsx · Import: sinwan-ui-core/menu-sub (also sinwan-ui-core) · Types: dist/menu-sub.d.ts
4
+
5
+ ## Purpose
6
+
7
+ The shared behaviour of nested menus (dropdown, context menu, menubar submenus): the submenu's open state, its trigger handlers (hover, click, arrow key, close delay), closing with its parent, and the positioned content layer with its keyboard (focus moves in when opened with a key; ArrowLeft / Escape go back to the trigger).
8
+
9
+ ## API
10
+
11
+ - `createMenuSubApi(options: MenuSubOptions): MenuSubApi` — call in a component body. Options: `controlled`, `defaultOpen?`, `readOpen()` (the controlled value), `onOpenChange?`, `parentOpen?()` (the sub closes when it turns false). `MenuSubApi`: `open`, `setOpen`, `triggerEl` (set it from the trigger's `ref`), `cancelClose()`, `requestClose(delayMs = 100)`, `openedByKeyboard` (set by the trigger handlers: the sub's first item takes focus when it opens).
12
+ - `createMenuSubTriggerHandlers(api): MenuSubTriggerHandlers` — `onMouseEnter` and `onClick(event?)` open (never toggle closed; pass the click event so Enter / Space, a click with `detail` 0, focuses the first item), `onMouseLeave` starts the close delay, `onKeyDown` opens on the arrow toward the sub and focuses its first item: ArrowRight, or ArrowLeft in right to left (the nearest `dir` attribute of the trigger, else the document's direction).
13
+ - `isInsideMenuSubContent(target)` — inside a `[data-slot$='-sub-content']` layer.
14
+ - `MenuSubContentLayer({ api, slot, class?, children? })` — the portaled, positioned content (`useAnchorPosition`, right/start, gap 4) with `role="menu"`, `tabIndex={-1}`, `data-slot={slot}`, `data-state`, `data-side`; hovering it cancels the close delay. Its keyboard: the arrow back toward the trigger (ArrowLeft, ArrowRight in right to left) or Escape closes the sub and refocuses its trigger (the keydown stops there, so the parent menu stays open); ArrowDown / ArrowUp / Home / End / letters / Tab as in llms.menu.txt.
15
+ - Types: `MenuSubApi`, `MenuSubOptions`, `MenuSubTriggerHandlers`, `MenuSubContentLayerProps`.
16
+
17
+ ## How it works
18
+
19
+ Like `createOpenState` (llms.overlay.txt) with a hover close timer; an effect closes the sub when `parentOpen()` turns false. The content layer calls `useMenuFocus` (llms.menu.txt) with `restoreFromBody: false`, so a hover close never moves focus.
20
+
21
+ ## Examples
22
+
23
+ ```tsx
24
+ // browser (happy-dom), compiled by sinwan-compiler
25
+ import { MenuSubContentLayer, createMenuSubApi, createMenuSubTriggerHandlers } from "sinwan-ui-core/menu-sub";
26
+ import { mount } from "sinwan/renderer";
27
+ import { nextTick, signal } from "sinwan/reactivity";
28
+
29
+ const menuOpen = signal(true);
30
+ export function ShareMenu() {
31
+ const api = createMenuSubApi({ controlled: false, readOpen: () => false, parentOpen: () => menuOpen.value });
32
+ const handlers = createMenuSubTriggerHandlers(api);
33
+ return (
34
+ <div>
35
+ <button ref={(el: HTMLElement | null) => (api.triggerEl.value = el)} onclick={handlers.onClick} onkeydown={handlers.onKeyDown}>Share</button>
36
+ <MenuSubContentLayer api={api} slot="dropdown-menu-sub-content">
37
+ <button>Email</button>
38
+ </MenuSubContentLayer>
39
+ </div>
40
+ );
41
+ }
42
+ const root = document.createElement("div");
43
+ document.body.appendChild(root);
44
+ mount(ShareMenu, root);
45
+ root.querySelector("button")!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
46
+ await nextTick();
47
+ console.log(document.querySelector("[data-slot=dropdown-menu-sub-content]")?.getAttribute("data-state")); // open
48
+ await Promise.resolve();
49
+ console.log(document.activeElement?.textContent); // Email
50
+ menuOpen.value = false; // the parent menu closes: the sub closes too
51
+ await nextTick();
52
+ console.log(document.querySelector("[data-slot=dropdown-menu-sub-content]")?.getAttribute("data-state")); // closed
53
+ ```
54
+
55
+ ## Pitfalls
56
+
57
+ - Put `dir="rtl"` on an ancestor (or `<html>`) for right-to-left keys; `DirectionProvider` does.
58
+ - Before 2.0.0: ArrowRight opened a sub also in right-to-left layouts, and ArrowLeft did nothing there.
59
+ - Before 2.0.0: the content had no `role="menu"`, a key-opened sub left focus on its trigger, and ArrowLeft / Escape inside it did nothing.
60
+ - Call `createMenuSubApi` during setup (it registers an unmount cleanup).
61
+
62
+ ## Related
63
+
64
+ - llms.menu.txt — the item keyboard and focus helpers the layer uses
65
+ - llms.floating.txt — the positioning
66
+ - llms.dismiss.txt — sub content is exempt from outside-press dismissal
@@ -0,0 +1,94 @@
1
+ # sinwan-ui-core — menu
2
+
3
+ > Source: src/menu.ts · Import: sinwan-ui-core/menu (also sinwan-ui-core) · Types: dist/menu.d.ts
4
+
5
+ ## Purpose
6
+
7
+ Keyboard behaviour shared by menus (dropdown, context menu, menubar and their submenus, llms.menu-sub.txt): focus moves into a menu when it opens and back to its trigger when it closes; ArrowDown / ArrowUp (wrapping), Home / End and a typed letter move between items; Tab closes the menu.
8
+
9
+ ## API
10
+
11
+ - `MENU_ITEM_SELECTOR` — `[role="menuitem"],[role="menuitemcheckbox"],[role="menuitemradio"]`.
12
+ - `getMenuItems(menu: HTMLElement): HTMLElement[]` — the menu's own enabled, visible items in DOM order. Items of a nested `role="menu"` belong to that menu; `disabled`, `aria-disabled="true"`, `data-disabled` (any value but `"false"`) and items inside `[hidden]` are skipped.
13
+ - `focusMenuItem(menu, which: "first" | "last"): boolean` — focuses that item; false when there is none.
14
+ - `isKeyboardClick(event: MouseEvent): boolean` — `event.detail === 0`: a click fired by Enter / Space on a button.
15
+ - `handleMenuKeyDown(event: KeyboardEvent, menu: HTMLElement, options?: MenuKeyDownOptions): boolean` — handles one keydown inside `menu`: ArrowDown / ArrowUp, Home, End, a printable character (the next item whose text starts with it), Tab (`options.onTab()`; the key is not prevented, so focus moves on). Returns true when it moved focus (the event is then `preventDefault`ed). Keys whose target belongs to a nested menu, and keys with Ctrl / ⌘ / Alt, are left alone.
16
+ - `MenuKeyDownOptions` — `{ onTab?: () => void }`.
17
+ - `useMenuFocus(options: MenuFocusOptions): MenuFocusReturn` — call in the menu content's component body. Options: `open()` (read in an effect), `content` and `trigger` (`{ value: HTMLElement | null }`, e.g. signals set from `ref`s), `close()` (used on Tab), `openedByKeyboard?()` (also focus the first item — a submenu opened with a key), `restoreFromBody?` (default true: also refocus the trigger when focus was lost to `<body>`). Returns `markOpenedByKeyboard(event)` (call from the trigger's click or opening key) and `onKeyDown(event)` (put on the content element).
18
+ - Types: `MenuKeyDownOptions`, `MenuFocusOptions`, `MenuFocusReturn`.
19
+
20
+ ## How it works
21
+
22
+ `useMenuFocus` runs one effect over `open()` and `content.value`. Once per opening, after the content is in the page, a microtask focuses the first item when the menu was opened from the keyboard (`markOpenedByKeyboard` saw a `KeyboardEvent` or a click with `detail` 0), else the content element itself (give it `tabIndex={-1}`), so Arrow keys work without highlighting an item after a mouse click. When `open()` turns false and focus was inside the content (or lost to `<body>`), the trigger is focused again.
23
+
24
+ ## Examples
25
+
26
+ ```tsx
27
+ // browser (happy-dom), compiled by sinwan-compiler
28
+ import { handleMenuKeyDown, focusMenuItem, getMenuItems, useMenuFocus } from "sinwan-ui-core/menu";
29
+ import { mount } from "sinwan/renderer";
30
+ import { nextTick, signal } from "sinwan/reactivity";
31
+
32
+ const open = signal(false);
33
+ const trigger = signal<HTMLElement | null>(null);
34
+ const content = signal<HTMLElement | null>(null);
35
+ function Menu() {
36
+ const focus = useMenuFocus({ open: () => open.value, content, trigger, close: () => (open.value = false) });
37
+ return (
38
+ <div>
39
+ <button
40
+ id="trigger"
41
+ ref={(el: HTMLElement | null) => (trigger.value = el)}
42
+ onclick={(event: MouseEvent) => {
43
+ focus.markOpenedByKeyboard(event);
44
+ open.value = !open.value;
45
+ }}
46
+ >
47
+ Actions
48
+ </button>
49
+ <div role="menu" tabIndex={-1} hidden={!open.value} ref={(el: HTMLElement | null) => (content.value = el)} onkeydown={focus.onKeyDown}>
50
+ <button role="menuitem">Copy</button>
51
+ <button role="menuitem" disabled>Cut</button>
52
+ <button role="menuitem">Paste</button>
53
+ <button role="menuitem">Print</button>
54
+ </div>
55
+ </div>
56
+ );
57
+ }
58
+ const root = document.createElement("div");
59
+ document.body.appendChild(root);
60
+ mount(Menu, root);
61
+ const menu = root.querySelector<HTMLElement>("[role=menu]")!;
62
+ const key = (name: string) =>
63
+ document.activeElement!.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true }));
64
+ const button = root.querySelector<HTMLElement>("#trigger")!;
65
+ button.focus();
66
+ button.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 0 })); // Enter on the button
67
+ await nextTick();
68
+ await Promise.resolve();
69
+ console.log(getMenuItems(menu).map((item) => item.textContent).join(",")); // Copy,Paste,Print
70
+ console.log(document.activeElement?.textContent); // Copy
71
+ key("ArrowDown");
72
+ key("p");
73
+ console.log(document.activeElement?.textContent); // Print
74
+ key("Tab"); // closes; focus goes back to the trigger
75
+ await nextTick();
76
+ console.log(open.value, document.activeElement?.id); // false trigger
77
+
78
+ console.log(focusMenuItem(document.createElement("div"), "first"), handleMenuKeyDown(new KeyboardEvent("keydown", { key: "ArrowDown" }), menu)); // false false
79
+ ```
80
+
81
+ ## Pitfalls
82
+
83
+ - Give the content `role="menu"` and `tabIndex={-1}`: a pointer opening focuses the content element itself.
84
+ - Call `markOpenedByKeyboard` before the open state changes (in the same click / keydown handler); the choice between "first item" and "content" is made when the content first appears.
85
+ - `getMenuItems` skips items inside `[hidden]`: a closed menu kept in the page with `hidden` has none.
86
+ - Typeahead matches the first letter of each item's text content, trimmed and lowercased.
87
+ - `handleMenuKeyDown` only moves focus between items; opening and closing a submenu (ArrowRight / ArrowLeft, Escape) is `MenuSubContentLayer`'s job (llms.menu-sub.txt).
88
+ - New in 2.0.0 (the sinwan-ui registry menus had no keyboard navigation before).
89
+
90
+ ## Related
91
+
92
+ - llms.menu-sub.txt — submenus use `useMenuFocus` and close on ArrowLeft / Escape
93
+ - llms.core.txt — `usePartId` for `aria-controls` ids
94
+ - llms.overlay.txt — dialogs and popovers manage focus themselves
@@ -0,0 +1,122 @@
1
+ # sinwan-ui-core — overlay
2
+
3
+ > Source: src/overlay.tsx · Import: sinwan-ui-core/overlay (also sinwan-ui-core) · Types: dist/overlay.d.ts
4
+
5
+ ## Purpose
6
+
7
+ Headless Dialog, Collapsible, Popover and Tooltip: open state (controlled or not), triggers, portaled content with `data-state="open"|"closed"` for CSS animations, Escape and outside-press dismissal, focus moved into a dialog and returned on close, accessible names. sinwan-ui's styled components wrap these with classes.
8
+
9
+ ## API
10
+
11
+ All parts read their root from context (`inject`), so they must be inside their root. Every root takes `open`/`defaultOpen`/`onOpenChange` (controlled when `open` is passed; SW202 when it is `undefined`).
12
+
13
+ **Dialog**
14
+ - `DialogRoot({ open?, defaultOpen?, onOpenChange?, modal? = true })` — provides `DialogKey` (`DialogApi` = `OpenApi & { modal }`) and `DialogLabelsKey` (`DialogLabels`: the title/description ids, from the component's tree position, so equal in server HTML and after hydration). While a **modal** dialog is open, the page does not scroll (the scrollbar width is kept as padding) and the rest of the page is `aria-hidden` (live regions and overlays stay visible); nested dialogs stack. `modal` is read at setup.
15
+ - `DialogTrigger({ class?, asChild? })` — a button (or, with `asChild`, its only child through `Slot`) that opens it; `aria-haspopup="dialog"` and `aria-expanded` either way.
16
+ - `DialogOverlay({ class? })` — the backdrop, portaled; a click closes.
17
+ - `DialogContent({ class?, role?: "dialog" | "alertdialog", onEscapeKeyDown?, data-*/aria-* })` — portaled, `aria-modal="true"`, named by `DialogTitle`/`DialogDescription` (`aria-labelledby`/`aria-describedby`). On open it focuses itself and remembers the focused element; Tab and Shift+Tab stay inside; Escape closes the topmost open layer only (unless `onEscapeKeyDown` calls `preventDefault()`); on close, focus returns to what opened it when focus was inside or lost.
18
+ - `DialogClose({ class?, asChild? })`, `DialogTitle` (an `h2`), `DialogDescription` (a `p`).
19
+
20
+ **Collapsible** — `CollapsibleRoot({ class? })` (provides `CollapsibleKey`), `CollapsibleTrigger` (`aria-expanded`, also with `asChild`), `CollapsibleContent` (sets `--radix-collapsible-content-height` for height animations).
21
+
22
+ **Popover** — `PopoverRoot({ placement?, align? })` (provides `PopoverKey`), `PopoverTrigger` (toggles; `aria-haspopup="dialog"` and `aria-expanded`, also with `asChild`), `PopoverContent({ side?, align?, sideOffset? = 8, onmouseenter?, onmouseleave? })` — portaled, positioned with `useAnchorPosition` (`data-side` = the side after flipping), closes on Escape (when it is the topmost open layer) and on a pointerdown outside it and its trigger (llms.dismiss.txt).
23
+
24
+ **Tooltip** — `TooltipProvider({ delayDuration? = 0 })` (provides `TooltipProviderKey`), `TooltipRoot({ delayDuration? })` (overrides the provider; provides `TooltipKey`: `TooltipApi` = `OpenApi & { scheduleOpen, cancelOpen, contentId }`), `TooltipTrigger` (pointer enter opens after the delay, focus at once; `aria-describedby` points at the content while open; leaving starts a 100 ms close, blur closes), `TooltipContent({ side? = "top", sideOffset? = 8 })` (`role="tooltip"`, its `id`; hovering it keeps it open, leaving it closes after 100 ms; Escape closes it when it is the topmost layer).
25
+
26
+ Types and keys: `OpenApi` (`open`, `setOpen`, `triggerEl`, `requestClose(delayMs?)`, `cancelClose`, `isHoverOpenBlocked`, `setPointerOverTrigger`), `DialogApi`, `DialogRootProps`, `DialogLabels`, `TooltipApi`, `DialogKey`, `DialogLabelsKey`, `CollapsibleKey`, `PopoverKey`, `TooltipKey`, `TooltipProviderKey`.
27
+
28
+ ## How it works
29
+
30
+ `createOpenState` holds the open signal (or follows the controlled prop), calls `onOpenChange`, and after a close ignores reopening for 280 ms (so the click that closed a layer does not reopen it through its trigger; tooltips have no such lock). Content parts render inside `Presence` (200 ms exit) and `UiPortal`, and register on the dismiss layer stack while open (`useDismissLayer`, llms.dismiss.txt): their `keydown` listeners on `document` act only when they are the topmost layer. A modal `DialogContent` calls `enterModal` (internal/llms.modal.txt) while open.
31
+
32
+ ## Examples
33
+
34
+ ```tsx
35
+ // browser (happy-dom), compiled by sinwan-compiler
36
+ import { DialogClose, DialogContent, DialogDescription, DialogRoot, DialogTitle, DialogTrigger } from "sinwan-ui-core/overlay";
37
+ import { mount } from "sinwan/renderer";
38
+ import { nextTick } from "sinwan/reactivity";
39
+
40
+ const changes: boolean[] = [];
41
+ export function Confirm() {
42
+ return (
43
+ <DialogRoot onOpenChange={(open: boolean) => changes.push(open)}>
44
+ <DialogTrigger>Delete</DialogTrigger>
45
+ <DialogContent role="alertdialog">
46
+ <DialogTitle>Delete the invoice?</DialogTitle>
47
+ <DialogDescription>This cannot be undone.</DialogDescription>
48
+ <DialogClose>Cancel</DialogClose>
49
+ </DialogContent>
50
+ </DialogRoot>
51
+ );
52
+ }
53
+
54
+ const root = document.createElement("div");
55
+ document.body.appendChild(root);
56
+ mount(Confirm, root);
57
+ const trigger = root.querySelector("button")!;
58
+ trigger.focus();
59
+ trigger.click();
60
+ await nextTick();
61
+ const dialog = document.querySelector("[role=alertdialog]")!;
62
+ const title = document.getElementById(dialog.getAttribute("aria-labelledby")!);
63
+ console.log(title?.textContent, document.activeElement === dialog); // Delete the invoice? true
64
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
65
+ await new Promise((resolve) => setTimeout(resolve, 250)); // the 200 ms exit
66
+ console.log(changes, document.querySelector("[role=alertdialog]"), document.activeElement === trigger); // [ true, false ] null true
67
+ ```
68
+
69
+ ```tsx
70
+ // browser (happy-dom), compiled by sinwan-compiler: modal lock, stacked Escape, tooltip
71
+ import { DialogContent, DialogRoot, DialogTitle, TooltipContent, TooltipProvider, TooltipRoot, TooltipTrigger } from "sinwan-ui-core/overlay";
72
+ import { mount } from "sinwan/renderer";
73
+ import { nextTick, signal } from "sinwan/reactivity";
74
+
75
+ const open = signal(true);
76
+ export function Settings() {
77
+ return (
78
+ <TooltipProvider delayDuration={0}>
79
+ <DialogRoot open={open.value} onOpenChange={(v: boolean) => (open.value = v)}>
80
+ <DialogContent>
81
+ <DialogTitle>Settings</DialogTitle>
82
+ <TooltipRoot>
83
+ <TooltipTrigger>?</TooltipTrigger>
84
+ <TooltipContent>Saved on change</TooltipContent>
85
+ </TooltipRoot>
86
+ </DialogContent>
87
+ </DialogRoot>
88
+ </TooltipProvider>
89
+ );
90
+ }
91
+ const root = document.createElement("div");
92
+ document.body.appendChild(root);
93
+ mount(Settings, root);
94
+ await nextTick();
95
+ console.log(document.body.style.overflow, root.getAttribute("aria-hidden")); // hidden true
96
+ const help = document.querySelector<HTMLElement>("[data-slot=tooltip-trigger]")!;
97
+ help.dispatchEvent(new MouseEvent("mouseenter"));
98
+ await nextTick();
99
+ console.log(help.getAttribute("aria-describedby") === document.querySelector("[role=tooltip]")!.id); // true
100
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); // the tooltip is on top: only it closes
101
+ await nextTick();
102
+ console.log(open.value, help.getAttribute("aria-describedby")); // true null
103
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
104
+ await nextTick();
105
+ console.log(open.value, document.body.style.overflow); // false
106
+ ```
107
+
108
+ ## Pitfalls
109
+
110
+ - Controlled roots: pass `open={state.value}` with `onOpenChange={(v) => (state.value = v)}`; without the handler the layer cannot close itself.
111
+ - Parts outside their root (a `DialogContent` with no `DialogRoot`) fail on `inject(...)!`.
112
+ - A non-modal dialog (`modal={false}`) leaves page scroll and screen readers alone; it still traps Tab while open.
113
+ - Your own layers join the Escape order with `useDismissLayer` (llms.dismiss.txt); sinwan-ui's menus and Select do.
114
+ - `TooltipProvider`'s `delayDuration` defaults to 0 (open at once); pass e.g. `700` for Radix's default.
115
+ - Before 2.0.0: one Escape closed every open layer; a modal dialog did not lock scroll or hide the page; dialog ids came from a page counter (server and hydration ids differed); tooltips ignored `delayDuration`, were not linked to their trigger, did not close on Escape and closed when hovered; a closing popover reported `onOpenChange(false)` again on Escape; an `asChild` Collapsible / Popover / Dialog trigger had no `aria-expanded` (and Dialog / Popover triggers no `aria-haspopup`).
116
+
117
+ ## Related
118
+
119
+ - llms.core.txt — `Presence`, `UiPortal`, `trapFocus`
120
+ - llms.floating.txt — `useAnchorPosition` for Popover and Tooltip
121
+ - llms.dismiss.txt — which outside presses close a popover
122
+ - llms.slot.txt — `asChild`
@@ -0,0 +1,33 @@
1
+ # sinwan-ui-core — sinwan-preload
2
+
3
+ > Source: src/sinwan-preload.ts · Import: not published (development and tests only) · Types: none
4
+
5
+ ## Purpose
6
+
7
+ A Bun preload (`bunfig.toml`) for this repository's own tests and scripts: it compiles `.tsx`/`.jsx` with sinwan-compiler (`derivedLocals: true`, `hoist: true`, `dev: false`) so the primitives behave in tests as in an app. It is not part of the package (`scripts/export-map.ts` lists it as private) and exports nothing.
8
+
9
+ ## API
10
+
11
+ None: importing it registers a Bun plugin with an `onLoad` for `.[tj]sx` files. A compile error becomes a module that throws it.
12
+
13
+ ## How it works
14
+
15
+ `plugin({ setup(build) { build.onLoad(...) } })` with `transformJSX` from sinwan-compiler. No resolve hook, cache or HMR (so a test run exits).
16
+
17
+ ## Examples
18
+
19
+ ```ts
20
+ // any environment (Bun): the preload has no exports; the package does not ship it
21
+ import { readFileSync } from "node:fs";
22
+
23
+ const pkg = JSON.parse(readFileSync(new URL("../node_modules/sinwan-ui-core/package.json", import.meta.url), "utf8"));
24
+ console.log(Object.keys(pkg.exports).some((key: string) => key.includes("preload"))); // false
25
+ ```
26
+
27
+ ## Pitfalls
28
+
29
+ - Apps use bun-plugin-sinwan or vite-plugin-sinwan, not this file.
30
+
31
+ ## Related
32
+
33
+ - llms.index.txt — what the package publishes
@@ -0,0 +1,51 @@
1
+ # sinwan-ui-core — slot
2
+
3
+ > Source: src/slot.ts · Import: sinwan-ui-core/slot (also sinwan-ui-core, sinwan-ui-core/controls) · Types: dist/slot.d.ts
4
+
5
+ ## Purpose
6
+
7
+ The `asChild` pattern: a part renders its one child element instead of its own (`<DialogTrigger asChild><a href="…">Open</a></DialogTrigger>`) and merges its props onto it.
8
+
9
+ ## API
10
+
11
+ - `Slot(props: { children?, ...props }): SinwanNode` — the child element with the slot's props merged in: `class` joined (child first, reactive classes stay live), event handlers (`on…`) both called (child's first), `ref`s both set (callbacks called, `{ current }` objects assigned; child first), `style` merged (objects per property, strings joined, mixed as CSS text with `px` for plain numbers; the slot wins; reactive styles stay live), every other prop **replaced** by the slot's. Throws `Slot expects exactly one Sinwan element child` for zero, several, or a non-element child.
12
+
13
+ ## How it works
14
+
15
+ It flattens the children, takes the single element and returns a new element with the merged props and the child's own children.
16
+
17
+ ## Examples
18
+
19
+ ```tsx
20
+ // browser (happy-dom), compiled by sinwan-compiler
21
+ import { Slot } from "sinwan-ui-core/slot";
22
+ import { mount } from "sinwan/renderer";
23
+
24
+ const calls: string[] = [];
25
+ let childEl: Element | null = null;
26
+ const root = document.createElement("div");
27
+ document.body.appendChild(root);
28
+ mount(
29
+ () => (
30
+ <Slot class="trigger" onclick={() => calls.push("slot")} data-state="closed" style={{ color: "red" }}>
31
+ <a href="/help" class="link" style={{ fontWeight: 600 }} ref={(el: Element | null) => (childEl = el)} onclick={() => calls.push("child")}>Help</a>
32
+ </Slot>
33
+ ),
34
+ root,
35
+ );
36
+ const link = root.querySelector("a")!;
37
+ link.addEventListener("click", (event) => event.preventDefault());
38
+ link.click();
39
+ console.log(link.className, link.dataset.state, calls, childEl === link, link.getAttribute("style")); // link trigger closed [ "child", "slot" ] true font-weight: 600; color: red;
40
+ ```
41
+
42
+ ## Pitfalls
43
+
44
+ - Other props are replaced by the slot's (an `id` or `aria-*` on the child loses to the slot's).
45
+ - Before 2.0.0: the slot's `ref` and `style` replaced the child's (an `asChild` child's own `ref` was never called).
46
+ - The child must be one element: wrap text or fragments.
47
+
48
+ ## Related
49
+
50
+ - llms.overlay.txt — `asChild` on triggers and close buttons
51
+ - llms.types.txt — `flattenChildren`, `isSinwanElement`
@@ -0,0 +1,59 @@
1
+ # sinwan-ui-core — theme
2
+
3
+ > Source: src/theme.tsx · Import: sinwan-ui-core/theme (also sinwan-ui-core) · Types: dist/theme.d.ts
4
+
5
+ ## Purpose
6
+
7
+ Light/dark mode and color palettes for the sinwan-ui stylesheet: `ThemeProvider` writes the mode on `<html>` (class `light`/`dark` or `data-theme`) and the palette as `html[data-palette]`, remembers both in `localStorage`, follows the system setting, and turns transitions off while switching.
8
+
9
+ ## API
10
+
11
+ - `ThemeProvider(props: ThemeProviderProps)` — `defaultTheme? = "system"`, `forcedTheme?`, `storageKey? = "sinwan-ui-theme"`, `enableSystem? = true`, `attribute? = "class" | "data-theme"`, `disableTransitionOnChange? = true`, `defaultPalette? = "carzow"`, `forcedPalette?`, `paletteStorageKey? = "sinwan-ui-palette"`, `palettes?` (the allowed palettes; omit to discover them from the stylesheets).
12
+ - `useTheme(): ThemeApi` — throws `useTheme() must be used within a ThemeProvider` outside one. `ThemeApi`: `theme` (`Signal<Theme>`), `resolved` (`Signal<"light" | "dark">`), `setTheme(theme)`, `themes`, `palette` (`Signal<Palette>`), `setPalette(name)` (ignored for a name that is not allowed, after one rescan), `palettes` (`Signal<Palette[]>`), `refreshPalettes()` (rescan, for CSS loaded later).
13
+ - `ThemeToggle({ class?, children? })` — an unstyled button switching light/dark (`aria-label="Toggle color theme"`).
14
+ - `discoverPalettes(doc?): Palette[]` — the palettes the page's stylesheets define (`html[data-palette="name"]`, also inside `@media`, `@supports`, `@layer`, `@import`), `carzow` first; `[]` without a DOM or with cross-origin CSS.
15
+ - `BUILT_IN_PALETTES` (`carzow`, `jomlaty`, `cazview`, `voltzig`), `ThemeKey`.
16
+ - Types: `Theme` (`"light" | "dark" | "system"`), `ResolvedTheme`, `BuiltInPalette`, `Palette` (built-in or any string), `ThemeApi`, `ThemeProviderProps`.
17
+
18
+ ## How it works
19
+
20
+ At setup it reads the stored theme and palette; on mount it writes the class/attribute, `color-scheme` and `data-palette` on `<html>` and listens to `prefers-color-scheme` when the theme is `system`. `setTheme`/`setPalette` store the value and write the DOM inside a transition lock (a temporary `transition: none` style).
21
+
22
+ ## Examples
23
+
24
+ ```tsx
25
+ // browser (happy-dom), compiled by sinwan-compiler
26
+ import { ThemeProvider, useTheme } from "sinwan-ui-core/theme";
27
+ import { mount } from "sinwan/renderer";
28
+ import { nextTick } from "sinwan/reactivity";
29
+
30
+ export function Picker() {
31
+ const theme = useTheme();
32
+ return (
33
+ <div>
34
+ <button onclick={() => theme.setTheme(theme.resolved.value === "dark" ? "light" : "dark")}>{theme.resolved.value}</button>
35
+ <button onclick={() => theme.setPalette("jomlaty")}>{theme.palette.value}</button>
36
+ </div>
37
+ );
38
+ }
39
+ const root = document.createElement("div");
40
+ document.body.appendChild(root);
41
+ mount(() => <ThemeProvider defaultTheme="light" palettes={["carzow", "jomlaty"]}><Picker /></ThemeProvider>, root);
42
+ const [mode, palette] = [...root.querySelectorAll("button")];
43
+ mode!.click();
44
+ palette!.click();
45
+ await nextTick();
46
+ const html = document.documentElement;
47
+ console.log(html.className, html.dataset.palette, localStorage.getItem("sinwan-ui-theme"), root.textContent); // dark jomlaty dark darkjomlaty
48
+ ```
49
+
50
+ ## Pitfalls
51
+
52
+ - **First paint**: the class is written on mount, so a server-rendered page (or a slow bundle) shows the default colors first. Put a small inline script in `<head>` that applies the stored class and `data-palette` before the app loads.
53
+ - On the server there is no `localStorage` or `matchMedia`: `system` renders as `light`, and the stored choice applies after hydration.
54
+ - Custom palettes must be same-origin CSS to be discovered (or pass `palettes`).
55
+ - One provider per page: it writes on `<html>`.
56
+
57
+ ## Related
58
+
59
+ - llms.direction.txt — the other app-wide provider
@@ -0,0 +1,45 @@
1
+ # sinwan-ui-core
2
+
3
+ > Headless behaviour for Sinwan UI components (the layer under the sinwan-ui registry): Dialog, Popover, Tooltip, Collapsible, Tabs, RadioGroup, Accordion, Checkbox, Switch, Toggle(Group), nested menus, floating positioning, outside-press dismissal, `asChild` slots, theme (light/dark, palettes) and direction. State, ARIA, focus and positioning; no styles. Read "Rules" before building components on it.
4
+
5
+ These files describe the `sinwan-ui-core` package for coding agents. Each file under `agents/` documents one source file (`agents/llms.<name>.txt` ↔ `src/<name>.ts(x)`, `agents/internal/…` ↔ `src/internal/…`), and every `dist/**/*.d.ts` names its doc in its first line. Sinwan itself is documented in `node_modules/sinwan/agents/llms.txt`.
6
+
7
+ ## Rules
8
+
9
+ - **Import from the subpath you need** (`sinwan-ui-core/overlay`, `/controls`, `/floating`, …); the root barrel has everything. [index](llms.index.txt)
10
+ - **Parts live inside their root**: `DialogContent` in `DialogRoot`, `TabsTrigger` in `TabsRoot`… (they `inject` the root's API). [overlay](llms.overlay.txt), [controls](llms.controls.txt)
11
+ - **Controlled or not**: pass `value`/`open`/`checked` with its `on…Change` to control; omit it for an internal state (`default…`). A present `undefined` freezes the control (SW202): start with `""`/`null`. [internal/controlled](internal/llms.controlled.txt)
12
+ - **Style with `data-state` / `data-side`** (`open`/`closed`, `checked`, `active`, `on`/`off`): content stays mounted 200 ms after closing for exit animations (`Presence`). [core](llms.core.txt)
13
+ - **Layers are portaled to `<body>` and positioned `fixed`** with Floating UI; bind the layer's `ref` to `content` when using `useAnchorPosition` yourself. [floating](llms.floating.txt)
14
+ - **One Escape closes the topmost layer only**: your own layers join the order with `useDismissLayer(() => open.value)` and check `layer.isTop()`; they need a `data-slot` ending in `-content`/`-sub-content`/`-overlay` (see the list) to count as "inside" for outside-press dismissal. [dismiss](llms.dismiss.txt)
15
+ - **Modal dialogs** (the default) lock page scroll and hide the rest of the page from screen readers while open; `modal={false}` for a non-blocking one. [overlay](llms.overlay.txt)
16
+ - **Forms**: give Checkbox, Switch and RadioGroup a `name` to submit them with their `<form>` (hidden inputs, reset supported). [controls](llms.controls.txt)
17
+ - **Menus**: `useMenuFocus` moves focus into a menu when it opens and back to its trigger when it closes; `handleMenuKeyDown` gives Arrow / Home / End / typeahead / Tab. [menu](llms.menu.txt)
18
+ - **Reading state**: `useDirection()` returns a computed (`dir.value`); controlled values follow at once. [direction](llms.direction.txt)
19
+ - **`asChild`** merges a part onto its one child (`class`, handlers, `ref`s and `style` merged; other props replaced by the part's). [slot](llms.slot.txt)
20
+ - **App providers**: `ThemeProvider` (mode and palette on `<html>`, stored) and `DirectionProvider` (RTL keys). [theme](llms.theme.txt), [direction](llms.direction.txt)
21
+ - **Server rendering** needs sinwan 2.6.1+: part ids come from the component tree, so they match after hydration.
22
+ - **Changes in sinwan-ui-core 2.0.0**: each Pitfalls section ends with what behaved differently before ("Before 2.0.0").
23
+
24
+ ## Primitives
25
+
26
+ - [index](llms.index.txt): every subpath and its doc
27
+ - [core](llms.core.txt): `Presence`, `UiPortal`, `useControllableState`, `trapFocus`
28
+ - [overlay](llms.overlay.txt): Dialog, Collapsible, Popover, Tooltip
29
+ - [controls](llms.controls.txt): Tabs, RadioGroup, Accordion, Checkbox, Switch, Toggle, ToggleGroup
30
+ - [menu](llms.menu.txt): menu keyboard and focus (`useMenuFocus`, `handleMenuKeyDown`)
31
+ - [menu-sub](llms.menu-sub.txt): nested menus
32
+ - [floating](llms.floating.txt): `useAnchorPosition`, `usePointPosition`, `computePosition`
33
+ - [dismiss](llms.dismiss.txt): `isDismissExemptPointerTarget`
34
+ - [slot](llms.slot.txt): `Slot`
35
+ - [types](llms.types.txt): prop aliases, `flattenChildren`, `isSinwanElement`
36
+ - [theme](llms.theme.txt): `ThemeProvider`, `useTheme`, `ThemeToggle`, palettes
37
+ - [direction](llms.direction.txt): `DirectionProvider`, `useDirection`
38
+
39
+ ## Internal
40
+
41
+ - [internal/controlled](internal/llms.controlled.txt): `isControlledProp`, SW202
42
+ - [internal/ids](internal/llms.ids.txt): `treeId` — ids equal on server and client
43
+ - [internal/modal](internal/llms.modal.txt): `enterModal` — scroll lock and hidden page
44
+ - [internal/form](internal/llms.form.txt): `useFormReset`
45
+ - [sinwan-preload](llms.sinwan-preload.txt): the repository's test compile preload (not published)
@@ -0,0 +1,39 @@
1
+ # sinwan-ui-core — types
2
+
3
+ > Source: src/types.ts · Import: sinwan-ui-core/types (also sinwan-ui-core) · Types: dist/types.d.ts
4
+
5
+ ## Purpose
6
+
7
+ Prop aliases for styled components built on the primitives, and two child helpers.
8
+
9
+ ## API
10
+
11
+ - Intrinsic prop aliases: `DivProps`, `ButtonHTMLProps`, `InputHTMLProps`, `TextareaHTMLProps`, `LabelHTMLProps`, `AnchorHTMLProps`, `SpanProps`, `HeadingProps`, `ParagraphProps`, `SVGProps` (`JSX.IntrinsicElements[tag]`).
12
+ - `isSinwanElement(node): node is SinwanElement` — an element object (`tag` and `props`).
13
+ - `flattenChildren(children): SinwanNode[]` — children unwrapped (getters resolved) and flattened, without `null`, `undefined` and booleans.
14
+
15
+ ## How it works
16
+
17
+ Type aliases only, plus two small functions.
18
+
19
+ ## Examples
20
+
21
+ ```tsx
22
+ // any environment, compiled by sinwan-compiler
23
+ import { flattenChildren, isSinwanElement, type ButtonHTMLProps } from "sinwan-ui-core/types";
24
+ import { cc } from "sinwan/component";
25
+
26
+ const Badge = cc((props: { label: string }) => <b>{props.label}</b>);
27
+ const props: ButtonHTMLProps = { type: "button", disabled: true };
28
+ const children = flattenChildren(["a", null, [<Badge label="x" />, false], () => "c"]);
29
+ console.log(props.type, children.length, children.filter((child) => isSinwanElement(child)).length); // button 3 1
30
+ ```
31
+
32
+ ## Pitfalls
33
+
34
+ - `flattenChildren` resolves getters once: call it where you render, not at setup, if the children change.
35
+ - **Standalone native markup may not be an element**: sinwan-compiler turns static native JSX in a variable or an array (`[<b>x</b>]`) into a template result, for which `isSinwanElement` is `false`. Component elements (`<Badge />`) and JSX passed as a component's children (what `Slot` receives) stay elements.
36
+
37
+ ## Related
38
+
39
+ - llms.slot.txt — uses both helpers
@@ -0,0 +1,126 @@
1
+ // src/menu.ts
2
+ import { effect, untrack } from "sinwan/reactivity";
3
+ var MENU_ITEM_SELECTOR2 = '[role="menuitem"],[role="menuitemcheckbox"],[role="menuitemradio"]';
4
+ function isDisabledItem(item) {
5
+ if (item.hasAttribute("disabled"))
6
+ return true;
7
+ if (item.getAttribute("aria-disabled") === "true")
8
+ return true;
9
+ const flag = item.getAttribute("data-disabled");
10
+ return flag !== null && flag !== "false";
11
+ }
12
+ function getMenuItems2(menu) {
13
+ return Array.from(menu.querySelectorAll(MENU_ITEM_SELECTOR2)).filter((item) => item.closest('[role="menu"]') === menu && !isDisabledItem(item) && item.closest("[hidden]") === null);
14
+ }
15
+ function focusMenuItem2(menu, which) {
16
+ const items = getMenuItems2(menu);
17
+ const item = which === "first" ? items[0] : items[items.length - 1];
18
+ if (!item)
19
+ return false;
20
+ item.focus({ preventScroll: true });
21
+ return true;
22
+ }
23
+ function isKeyboardClick2(event) {
24
+ return event.detail === 0;
25
+ }
26
+ function itemText(item) {
27
+ return (item.textContent ?? "").trim().toLowerCase();
28
+ }
29
+ function handleMenuKeyDown2(event, menu, options = {}) {
30
+ const from = event.target instanceof Element ? event.target : document.activeElement;
31
+ if (!from || from.closest('[role="menu"]') !== menu)
32
+ return false;
33
+ if (event.key === "Tab") {
34
+ options.onTab?.();
35
+ return false;
36
+ }
37
+ if (event.ctrlKey || event.metaKey || event.altKey)
38
+ return false;
39
+ const items = getMenuItems2(menu);
40
+ if (items.length === 0)
41
+ return false;
42
+ const index = items.findIndex((item) => item === from);
43
+ let next;
44
+ switch (event.key) {
45
+ case "ArrowDown":
46
+ next = items[index < 0 ? 0 : (index + 1) % items.length];
47
+ break;
48
+ case "ArrowUp":
49
+ next = items[index <= 0 ? items.length - 1 : index - 1];
50
+ break;
51
+ case "Home":
52
+ next = items[0];
53
+ break;
54
+ case "End":
55
+ next = items[items.length - 1];
56
+ break;
57
+ default: {
58
+ if (event.key.length !== 1 || event.key === " ")
59
+ return false;
60
+ const letter = event.key.toLowerCase();
61
+ for (let step = 1;step <= items.length; step++) {
62
+ const candidate = items[(index + step + items.length) % items.length];
63
+ if (candidate && itemText(candidate).startsWith(letter)) {
64
+ next = candidate;
65
+ break;
66
+ }
67
+ }
68
+ }
69
+ }
70
+ if (!next)
71
+ return false;
72
+ event.preventDefault();
73
+ next.focus({ preventScroll: true });
74
+ return true;
75
+ }
76
+ function useMenuFocus2(options) {
77
+ let keyboard = false;
78
+ let focusedThisOpen = false;
79
+ let wasOpen = false;
80
+ const restoreFromBody = options.restoreFromBody ?? true;
81
+ effect(() => {
82
+ const isOpen = options.open();
83
+ const el = options.content.value;
84
+ if (isOpen) {
85
+ wasOpen = true;
86
+ if (!el || focusedThisOpen)
87
+ return;
88
+ focusedThisOpen = true;
89
+ const firstItem = keyboard || untrack(() => options.openedByKeyboard?.() ?? false);
90
+ queueMicrotask(() => {
91
+ if (!untrack(options.open))
92
+ return;
93
+ if (firstItem && focusMenuItem2(el, "first"))
94
+ return;
95
+ el.focus({ preventScroll: true });
96
+ });
97
+ return;
98
+ }
99
+ if (!wasOpen)
100
+ return;
101
+ wasOpen = false;
102
+ focusedThisOpen = false;
103
+ keyboard = false;
104
+ const trigger = untrack(() => options.trigger.value);
105
+ if (!trigger)
106
+ return;
107
+ const active = document.activeElement;
108
+ const inside = el !== null && active !== null && el.contains(active);
109
+ const lost = restoreFromBody && (active === null || active === document.body);
110
+ if (inside || lost)
111
+ trigger.focus({ preventScroll: true });
112
+ });
113
+ return {
114
+ markOpenedByKeyboard: (event) => {
115
+ keyboard = event instanceof KeyboardEvent || isKeyboardClick2(event);
116
+ },
117
+ onKeyDown: (event) => {
118
+ const el = options.content.value;
119
+ if (!el)
120
+ return;
121
+ handleMenuKeyDown2(event, el, { onTab: options.close });
122
+ }
123
+ };
124
+ }
125
+
126
+ export { MENU_ITEM_SELECTOR2, getMenuItems2, focusMenuItem2, isKeyboardClick2, handleMenuKeyDown2, useMenuFocus2 };