@hydrateless/svelte 0.9.0 → 0.10.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.
@@ -4,6 +4,7 @@
4
4
  import type { Snippet } from 'svelte';
5
5
  import type { HTMLAttributes } from 'svelte/elements';
6
6
  import { setAccordionContext } from '../context.js';
7
+ import { createRegistry } from '../registry.svelte.js';
7
8
  import { useEnhancer } from '../useEnhancer.svelte.js';
8
9
 
9
10
  interface Props extends HTMLAttributes<HTMLDivElement> {
@@ -31,13 +32,13 @@
31
32
  if (value === undefined) value = defaultValue ?? [];
32
33
 
33
34
  // Items register in document order so each `<details>` can render `open`
34
- // on the server from the shared value.
35
- let itemCount = 0;
35
+ // on the server from the shared value; indexes stay live for `{#each}`.
36
+ const items = createRegistry();
36
37
  setAccordionContext({
37
38
  get value() {
38
39
  return value ?? [];
39
40
  },
40
- registerItem: () => itemCount++,
41
+ registerItem: () => items.register(),
41
42
  });
42
43
 
43
44
  const accordion = useEnhancer(enhanceAccordion, () => ({
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import type { Snippet } from 'svelte';
2
+ import { onDestroy, type Snippet } from 'svelte';
3
3
  import type { HTMLAttributes } from 'svelte/elements';
4
4
  import { getAccordionContext } from '../context.js';
5
5
 
@@ -16,14 +16,17 @@
16
16
 
17
17
  let { value, title, summary, children, ...rest }: Props = $props();
18
18
  const accordion = getAccordionContext();
19
- const index = accordion?.registerItem() ?? 0;
20
- const ownValue = $derived(value ?? String(index));
19
+ const registration = accordion?.registerItem();
20
+ onDestroy(() => registration?.unregister());
21
+ let node = $state<HTMLDetailsElement | null>(null);
22
+ $effect(() => registration?.attach(node));
23
+ const ownValue = $derived(value ?? String(registration?.index ?? 0));
21
24
  // Rendered on the server from the Accordion's value so the open panel shows
22
25
  // before the enhancer runs; the enhancer then keeps `open` in step.
23
26
  const open = $derived(accordion ? accordion.value.includes(ownValue) : undefined);
24
27
  </script>
25
28
 
26
- <details {...rest} data-hl-value={value} {open}>
29
+ <details {...rest} bind:this={node} data-hl-value={value} {open}>
27
30
  <summary
28
31
  >{#if summary}{@render summary()}{:else}{title}{/if}</summary
29
32
  >
@@ -1,4 +1,4 @@
1
- import type { Snippet } from 'svelte';
1
+ import { type Snippet } from 'svelte';
2
2
  import type { HTMLAttributes } from 'svelte/elements';
3
3
  interface Props extends Omit<HTMLAttributes<HTMLDetailsElement>, 'title'> {
4
4
  /** Stable value identifying this item; defaults to its index. */
@@ -47,6 +47,6 @@
47
47
  });
48
48
  </script>
49
49
 
50
- <div {...rest} data-hl-command data-hl-command-hotkey={hotkey} {@attach command.attach}>
50
+ <div {...rest} data-hl-command data-hl-hotkey={hotkey} {@attach command.attach}>
51
51
  {@render children?.()}
52
52
  </div>
@@ -45,6 +45,9 @@
45
45
  setDropdownContext({
46
46
  menuId: `hl-dropdown-menu-${generatedId}`,
47
47
  triggerId: `hl-dropdown-trigger-${generatedId}`,
48
+ get open() {
49
+ return open ?? false;
50
+ },
48
51
  });
49
52
 
50
53
  const dropdown = useEnhancer(enhanceDropdown, () => ({
@@ -19,7 +19,7 @@
19
19
  data-hl-dropdown-trigger
20
20
  popovertarget={dropdown?.menuId}
21
21
  aria-haspopup="menu"
22
- aria-expanded="false"
22
+ aria-expanded={dropdown?.open ?? false}
23
23
  aria-controls={dropdown?.menuId}
24
24
  >
25
25
  {@render children?.()}
@@ -24,7 +24,7 @@
24
24
  <button type="button" role="menuitem" data-hl-value={value} disabled={disabled || undefined}>
25
25
  {#if trigger}{@render trigger()}{:else}{label}{/if}
26
26
  </button>
27
- <ul {...rest} role="menu" data-hl-menu-submenu class={klass}>
27
+ <ul {...rest} role="menu" data-hl-submenu class={klass}>
28
28
  {@render children?.()}
29
29
  </ul>
30
30
  </li>
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import type { Snippet } from 'svelte';
2
+ import { onDestroy, type Snippet } from 'svelte';
3
3
  import type { HTMLButtonAttributes } from 'svelte/elements';
4
4
  import { getTabsContext } from '../context.js';
5
5
 
@@ -12,14 +12,17 @@
12
12
 
13
13
  let { value, type, children, ...rest }: Props = $props();
14
14
  const tabs = getTabsContext();
15
- // svelte-ignore state_referenced_locally -- the value identifies this tab for its lifetime
16
- const index = tabs?.registerTab(value) ?? 0;
17
- const ownValue = $derived(value ?? String(index));
15
+ const registration = tabs?.registerTab(() => value);
16
+ onDestroy(() => registration?.unregister());
17
+ let node = $state<HTMLButtonElement | null>(null);
18
+ $effect(() => registration?.attach(node));
19
+ const ownValue = $derived(value ?? String(registration?.index ?? 0));
18
20
  const selected = $derived(tabs ? tabs.value === ownValue : undefined);
19
21
  </script>
20
22
 
21
23
  <button
22
24
  {...rest}
25
+ bind:this={node}
23
26
  type={type ?? 'button'}
24
27
  role="tab"
25
28
  data-hl-value={value}
@@ -1,4 +1,4 @@
1
- import type { Snippet } from 'svelte';
1
+ import { type Snippet } from 'svelte';
2
2
  import type { HTMLButtonAttributes } from 'svelte/elements';
3
3
  interface Props extends HTMLButtonAttributes {
4
4
  /** Stable value identifying this tab; defaults to its index. */
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import type { Snippet } from 'svelte';
2
+ import { onDestroy, type Snippet } from 'svelte';
3
3
  import type { HTMLAttributes } from 'svelte/elements';
4
4
  import { getTabsContext } from '../context.js';
5
5
 
@@ -10,12 +10,15 @@
10
10
 
11
11
  let { children, ...rest }: Props = $props();
12
12
  const tabs = getTabsContext();
13
- const index = tabs?.registerPanel() ?? 0;
13
+ const registration = tabs?.registerPanel();
14
+ onDestroy(() => registration?.unregister());
15
+ let node = $state<HTMLDivElement | null>(null);
16
+ $effect(() => registration?.attach(node));
14
17
  // Rendered on the server too, so the unselected panels never flash before
15
18
  // the enhancer takes over `hidden`.
16
- const hidden = $derived(tabs ? tabs.value !== tabs.tabValueAt(index) : false);
19
+ const hidden = $derived(tabs ? tabs.value !== tabs.tabValueAt(registration?.index ?? 0) : false);
17
20
  </script>
18
21
 
19
- <div {...rest} role="tabpanel" {hidden} tabindex={tabs ? 0 : undefined}>
22
+ <div {...rest} bind:this={node} role="tabpanel" {hidden} tabindex={tabs ? 0 : undefined}>
20
23
  {@render children?.()}
21
24
  </div>
@@ -1,4 +1,4 @@
1
- import type { Snippet } from 'svelte';
1
+ import { type Snippet } from 'svelte';
2
2
  import type { HTMLAttributes } from 'svelte/elements';
3
3
  interface Props extends HTMLAttributes<HTMLDivElement> {
4
4
  /** Panel content, shown while the tab at the same index is selected. */
@@ -4,6 +4,7 @@
4
4
  import type { Snippet } from 'svelte';
5
5
  import type { HTMLAttributes } from 'svelte/elements';
6
6
  import { setTabsContext } from '../context.js';
7
+ import { createRegistry } from '../registry.svelte.js';
7
8
  import { useEnhancer } from '../useEnhancer.svelte.js';
8
9
 
9
10
  interface Props extends HTMLAttributes<HTMLDivElement> {
@@ -35,24 +36,20 @@
35
36
 
36
37
  // Tabs and panels register in document order so `aria-selected`/`hidden`
37
38
  // render on the server and the enhancer finds them already in agreement.
38
- const tabValues: string[] = [];
39
- let panelCount = 0;
39
+ // Registries keep indexes live when an `{#each}` adds or removes tabs.
40
+ const tabs = createRegistry<() => string | undefined>();
41
+ const panels = createRegistry();
42
+ const tabValues = $derived(tabs.entries.map((get, index) => get() ?? String(index)));
40
43
  setTabsContext({
41
44
  get value() {
42
45
  return value ?? tabValues[0];
43
46
  },
44
- registerTab(tabValue) {
45
- const index = tabValues.length;
46
- tabValues.push(tabValue ?? String(index));
47
- return index;
48
- },
49
- registerPanel() {
50
- return panelCount++;
51
- },
47
+ registerTab: (getValue) => tabs.register(getValue),
48
+ registerPanel: () => panels.register(),
52
49
  tabValueAt: (index) => tabValues[index],
53
50
  });
54
51
 
55
- const tabs = useEnhancer(enhanceTabs, () => ({
52
+ const enhanced = useEnhancer(enhanceTabs, () => ({
56
53
  activation,
57
54
  orientation,
58
55
  defaultValue: untrack(() => value),
@@ -63,10 +60,10 @@
63
60
  }));
64
61
 
65
62
  $effect(() => {
66
- if (value != null) tabs.api?.setValue(value);
63
+ if (value != null) enhanced.api?.setValue(value);
67
64
  });
68
65
  </script>
69
66
 
70
- <div {...rest} data-hl-tabs data-hl-orientation={orientation} {@attach tabs.attach}>
67
+ <div {...rest} data-hl-tabs data-hl-orientation={orientation} {@attach enhanced.attach}>
71
68
  {@render children?.()}
72
69
  </div>
@@ -2,9 +2,10 @@
2
2
  import { enhanceTooltip, type EnhanceTooltipOptions } from '@hydrateless/enhancers';
3
3
  import type { Snippet } from 'svelte';
4
4
  import type { HTMLAttributes } from 'svelte/elements';
5
+ import type { TooltipTriggerProps } from '../context.js';
5
6
  import { useEnhancer } from '../useEnhancer.svelte.js';
6
7
 
7
- interface Props extends HTMLAttributes<HTMLSpanElement> {
8
+ interface Props extends Omit<HTMLAttributes<HTMLSpanElement>, 'children'> {
8
9
  /** The hint shown on hover/focus: plain text or a snippet for rich content. */
9
10
  content?: string | Snippet;
10
11
  /** Preferred placement relative to the trigger. Defaults to `top`. */
@@ -17,8 +18,20 @@
17
18
  open?: boolean;
18
19
  /** Called after the tip shows or hides. */
19
20
  onOpenChange?: (open: boolean) => void;
20
- /** A single focusable element that triggers the tooltip. */
21
- children?: Snippet;
21
+ /**
22
+ * A single focusable element that triggers the tooltip. The snippet
23
+ * receives the trigger attributes; spread them so server-rendered markup
24
+ * links the trigger to the tip before any script runs:
25
+ *
26
+ * ```svelte
27
+ * <Tooltip content="Save">
28
+ * {#snippet children(trigger)}<Button {...trigger}>Save</Button>{/snippet}
29
+ * </Tooltip>
30
+ * ```
31
+ *
32
+ * Without the spread, the first child is linked on the client instead.
33
+ */
34
+ children?: Snippet<[TooltipTriggerProps]>;
22
35
  }
23
36
 
24
37
  let {
@@ -36,14 +49,20 @@
36
49
  // SSR-safe: $props.id() is stable across server and client renders.
37
50
  const generatedId = $props.id();
38
51
  const tipId = `hl-tip-${generatedId}`;
52
+ const triggerProps: TooltipTriggerProps = {
53
+ 'data-hl-tooltip': tipId,
54
+ 'aria-describedby': tipId,
55
+ };
39
56
 
40
- // The trigger is whatever the consumer renders first, so it's linked to the
41
- // tip here rather than asking them to repeat the id.
57
+ // Consumers that don't spread the snippet's trigger props still get linked
58
+ // on the client: whatever they rendered first is the trigger.
42
59
  const tooltip = useEnhancer(
43
60
  (node: HTMLElement, options?: Partial<EnhanceTooltipOptions>) => {
44
61
  const trigger = node.querySelector<HTMLElement>(':scope > :first-child');
45
- trigger?.setAttribute('data-hl-tooltip', tipId);
46
- trigger?.setAttribute('aria-describedby', tipId);
62
+ if (trigger && !trigger.hasAttribute('data-hl-tooltip')) {
63
+ trigger.setAttribute('data-hl-tooltip', tipId);
64
+ trigger.setAttribute('aria-describedby', tipId);
65
+ }
47
66
  return enhanceTooltip(node, options);
48
67
  },
49
68
  () => ({
@@ -68,7 +87,7 @@
68
87
  style={['position:relative;display:inline-block', style].filter(Boolean).join(';')}
69
88
  {@attach tooltip.attach}
70
89
  >
71
- {@render children?.()}
90
+ {@render children?.(triggerProps)}
72
91
  <span id={tipId} role="tooltip" hidden
73
92
  >{#if typeof content === 'function'}{@render content()}{:else}{content}{/if}</span
74
93
  >
@@ -1,7 +1,8 @@
1
1
  import { type EnhanceTooltipOptions } from '@hydrateless/enhancers';
2
2
  import type { Snippet } from 'svelte';
3
3
  import type { HTMLAttributes } from 'svelte/elements';
4
- interface Props extends HTMLAttributes<HTMLSpanElement> {
4
+ import type { TooltipTriggerProps } from '../context.js';
5
+ interface Props extends Omit<HTMLAttributes<HTMLSpanElement>, 'children'> {
5
6
  /** The hint shown on hover/focus: plain text or a snippet for rich content. */
6
7
  content?: string | Snippet;
7
8
  /** Preferred placement relative to the trigger. Defaults to `top`. */
@@ -14,8 +15,20 @@ interface Props extends HTMLAttributes<HTMLSpanElement> {
14
15
  open?: boolean;
15
16
  /** Called after the tip shows or hides. */
16
17
  onOpenChange?: (open: boolean) => void;
17
- /** A single focusable element that triggers the tooltip. */
18
- children?: Snippet;
18
+ /**
19
+ * A single focusable element that triggers the tooltip. The snippet
20
+ * receives the trigger attributes; spread them so server-rendered markup
21
+ * links the trigger to the tip before any script runs:
22
+ *
23
+ * ```svelte
24
+ * <Tooltip content="Save">
25
+ * {#snippet children(trigger)}<Button {...trigger}>Save</Button>{/snippet}
26
+ * </Tooltip>
27
+ * ```
28
+ *
29
+ * Without the spread, the first child is linked on the client instead.
30
+ */
31
+ children?: Snippet<[TooltipTriggerProps]>;
19
32
  }
20
33
  declare const Tooltip: import("svelte").Component<Props, {}, "open">;
21
34
  type Tooltip = ReturnType<typeof Tooltip>;
package/dist/context.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Registration } from './registry.svelte.js';
1
2
  /**
2
3
  * What a Field shares with its descendants. The getters stay live, so controls
3
4
  * re-render when `invalid`/`required` change.
@@ -40,6 +41,16 @@ export interface FieldBindings {
40
41
  * ```
41
42
  */
42
43
  export declare function useField(): FieldBindings | null;
44
+ /**
45
+ * Attributes a `<Tooltip>` hands to its `children` snippet. Spread them onto
46
+ * the trigger element so server-rendered markup already links it to the tip.
47
+ */
48
+ export interface TooltipTriggerProps {
49
+ /** Marks the trigger and names the tip it describes. */
50
+ 'data-hl-tooltip': string;
51
+ /** Points at the tip so assistive tech announces it. */
52
+ 'aria-describedby': string;
53
+ }
43
54
  /** Shared state a RadioGroup provides to its radios (name, selected value, and a setter). @internal */
44
55
  export interface RadioGroupContext {
45
56
  readonly name: string | undefined;
@@ -52,12 +63,14 @@ export declare function setRadioGroupContext(ctx: RadioGroupContext): void;
52
63
  export declare function getRadioGroupContext(): RadioGroupContext | undefined;
53
64
  /**
54
65
  * Ids a Dropdown generates so the trigger's `popovertarget` and the menu's
55
- * `id` agree in server-rendered markup, before any script runs.
66
+ * `id` agree in server-rendered markup, before any script runs, plus the live
67
+ * open state so the trigger's `aria-expanded` renders correctly too.
56
68
  * @internal
57
69
  */
58
70
  export interface DropdownContext {
59
71
  readonly menuId: string;
60
72
  readonly triggerId: string;
73
+ readonly open: boolean;
61
74
  }
62
75
  /** Publish a {@link DropdownContext}; called by `<Dropdown>` only. @internal */
63
76
  export declare function setDropdownContext(ctx: DropdownContext): void;
@@ -67,15 +80,17 @@ export declare function getDropdownContext(): DropdownContext | undefined;
67
80
  * Selection state a Tabs root shares with its tabs and panels so `aria-selected`,
68
81
  * `tabindex`, and `hidden` can be rendered on the server. Tabs and panels
69
82
  * register in document order; a panel pairs with the tab at the same index.
83
+ * Indexes are live, so an `{#each}` that adds or removes tabs renumbers the
84
+ * rest; children unregister on destroy.
70
85
  * @internal
71
86
  */
72
87
  export interface TabsContext {
73
88
  /** The selected tab's value (falls back to the first registered tab). */
74
89
  readonly value: string | undefined;
75
- /** Register a tab and get its index. `value` defaults to that index. */
76
- registerTab: (value: string | undefined) => number;
77
- /** Register a panel and get its index. */
78
- registerPanel: () => number;
90
+ /** Register a tab by a getter for its value, which defaults to its index. */
91
+ registerTab: (value: () => string | undefined) => Registration;
92
+ /** Register a panel. */
93
+ registerPanel: () => Registration;
79
94
  /** Value of the tab registered at `index`. */
80
95
  tabValueAt: (index: number) => string | undefined;
81
96
  }
@@ -91,8 +106,8 @@ export declare function getTabsContext(): TabsContext | undefined;
91
106
  export interface AccordionContext {
92
107
  /** Values of the open items. */
93
108
  readonly value: readonly string[];
94
- /** Register an item and get its index, which is its default value. */
95
- registerItem: () => number;
109
+ /** Register an item; its live index is its default value. */
110
+ registerItem: () => Registration;
96
111
  }
97
112
  /** Publish an {@link AccordionContext}; called by `<Accordion>` only. @internal */
98
113
  export declare function setAccordionContext(ctx: AccordionContext): void;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { useEnhancer } from './useEnhancer.svelte.js';
2
2
  export type { UseEnhancer } from './useEnhancer.svelte.js';
3
3
  export { useField } from './context.js';
4
- export type { FieldBindings } from './context.js';
4
+ export type { FieldBindings, TooltipTriggerProps } from './context.js';
5
5
  export { useToast } from './toast.js';
6
6
  export { default as Accordion } from './components/Accordion.svelte';
7
7
  export { default as AccordionItem } from './components/AccordionItem.svelte';
@@ -0,0 +1,29 @@
1
+ /** A live position in a parent's item list plus its disposer. @internal */
2
+ export interface Registration {
3
+ /** Current index in document order; shifts as siblings mount or unmount. */
4
+ readonly index: number;
5
+ /**
6
+ * Report the rendered element (from `bind:this`, inside an `$effect`) so
7
+ * items inserted out of registration order, such as a prepend, sort into
8
+ * their real document position.
9
+ */
10
+ attach(node: Element | null): void;
11
+ /** Free the slot (call from `onDestroy`). */
12
+ unregister(): void;
13
+ }
14
+ /** A parent-side list of registered children. @internal */
15
+ export interface Registry<T = void> {
16
+ /** Register a child; `value` is any per-child getter the parent needs. */
17
+ register(value: T): Registration;
18
+ /** Registered children's values in document order. */
19
+ readonly entries: T[];
20
+ }
21
+ /**
22
+ * Tracks children so their indexes stay dense and in document order while an
23
+ * `{#each}` inserts or removes them after mount. Registration happens during
24
+ * child init (so server output is right), and the write is untracked to keep
25
+ * it out of the parent's render. Shared by the accordion and tabs, whose
26
+ * enhancers fall back to the same positional indexes.
27
+ * @internal
28
+ */
29
+ export declare function createRegistry<T = void>(): Registry<T>;
@@ -0,0 +1,44 @@
1
+ import { untrack } from 'svelte';
2
+ const DOCUMENT_POSITION_FOLLOWING = 4;
3
+ /** Orders mounted entries by document position; unmounted ones keep their place. */
4
+ function byDocumentOrder(a, b) {
5
+ if (!a.node || !b.node || a.node === b.node)
6
+ return 0;
7
+ return a.node.compareDocumentPosition(b.node) & DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
8
+ }
9
+ /**
10
+ * Tracks children so their indexes stay dense and in document order while an
11
+ * `{#each}` inserts or removes them after mount. Registration happens during
12
+ * child init (so server output is right), and the write is untracked to keep
13
+ * it out of the parent's render. Shared by the accordion and tabs, whose
14
+ * enhancers fall back to the same positional indexes.
15
+ * @internal
16
+ */
17
+ export function createRegistry() {
18
+ let items = $state.raw([]);
19
+ return {
20
+ get entries() {
21
+ return items.map((item) => item.value);
22
+ },
23
+ register(value) {
24
+ const entry = { value, node: null };
25
+ untrack(() => {
26
+ items = [...items, entry];
27
+ });
28
+ return {
29
+ get index() {
30
+ return items.indexOf(entry);
31
+ },
32
+ attach(node) {
33
+ if (entry.node === node)
34
+ return;
35
+ entry.node = node;
36
+ items = [...items].sort(byDocumentOrder);
37
+ },
38
+ unregister() {
39
+ items = items.filter((item) => item !== entry);
40
+ },
41
+ };
42
+ },
43
+ };
44
+ }
package/dist/toast.js CHANGED
@@ -31,5 +31,8 @@ export function useToast(options) {
31
31
  dismiss(toast) {
32
32
  resolve()?.dismiss(toast);
33
33
  },
34
+ dismissAll() {
35
+ resolve()?.dismissAll();
36
+ },
34
37
  };
35
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hydrateless/svelte",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Svelte 5 bindings for Hydrateless: rune-based components, a useEnhancer attachment, field wiring, and toasts.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,7 +32,7 @@
32
32
  "test": "vitest run"
33
33
  },
34
34
  "dependencies": {
35
- "@hydrateless/enhancers": "^0.9.0"
35
+ "@hydrateless/enhancers": "^0.10.0"
36
36
  },
37
37
  "peerDependencies": {
38
38
  "svelte": ">=5.29"