@diegopluna/narvi 0.4.0 → 0.5.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 (183) hide show
  1. package/README.md +3 -1
  2. package/dist/base.css +3 -0
  3. package/dist/components/button/Button.svelte +29 -17
  4. package/dist/components/checkbox/Checkbox.svelte +106 -54
  5. package/dist/components/checkbox/Checkbox.svelte.d.ts +22 -8
  6. package/dist/components/choice-cards/ChoiceCards.svelte +68 -39
  7. package/dist/components/choice-cards/ChoiceCards.svelte.d.ts +12 -8
  8. package/dist/components/collapsible/CollapsibleContent.svelte +71 -17
  9. package/dist/components/collapsible/CollapsibleContent.svelte.d.ts +14 -10
  10. package/dist/components/collapsible/CollapsibleRoot.svelte +13 -9
  11. package/dist/components/collapsible/CollapsibleRoot.svelte.d.ts +8 -9
  12. package/dist/components/collapsible/CollapsibleTrigger.svelte +24 -15
  13. package/dist/components/collapsible/CollapsibleTrigger.svelte.d.ts +10 -14
  14. package/dist/components/color-field/ColorField.svelte +13 -7
  15. package/dist/components/command/CommandDialog.svelte +30 -20
  16. package/dist/components/command/CommandDialog.svelte.d.ts +4 -3
  17. package/dist/components/command/CommandEmpty.svelte +11 -9
  18. package/dist/components/command/CommandEmpty.svelte.d.ts +6 -17
  19. package/dist/components/command/CommandGroup.svelte +32 -11
  20. package/dist/components/command/CommandGroup.svelte.d.ts +7 -11
  21. package/dist/components/command/CommandInput.svelte +25 -10
  22. package/dist/components/command/CommandInput.svelte.d.ts +8 -12
  23. package/dist/components/command/CommandItem.svelte +67 -29
  24. package/dist/components/command/CommandItem.svelte.d.ts +6 -32
  25. package/dist/components/command/CommandList.svelte +8 -10
  26. package/dist/components/command/CommandList.svelte.d.ts +6 -8
  27. package/dist/components/command/CommandRoot.svelte +247 -57
  28. package/dist/components/command/CommandRoot.svelte.d.ts +14 -28
  29. package/dist/components/command/CommandSeparator.svelte +18 -0
  30. package/dist/components/command/CommandSeparator.svelte.d.ts +7 -0
  31. package/dist/components/command/context.d.ts +27 -0
  32. package/dist/components/command/context.js +16 -0
  33. package/dist/components/command/index.d.ts +6 -4
  34. package/dist/components/command/index.js +5 -4
  35. package/dist/components/command/score.d.ts +27 -0
  36. package/dist/components/command/score.js +77 -0
  37. package/dist/components/command/styles.d.ts +32 -9
  38. package/dist/components/command/styles.js +42 -14
  39. package/dist/components/composer/ComposerModelPicker.svelte +365 -347
  40. package/dist/components/composer/ComposerModelPicker.svelte.d.ts +6 -3
  41. package/dist/components/composer/ComposerRoot.svelte.d.ts +1 -1
  42. package/dist/components/dialog/ConfirmDialog.svelte +73 -53
  43. package/dist/components/dialog/DialogClose.svelte +17 -0
  44. package/dist/components/dialog/DialogClose.svelte.d.ts +10 -0
  45. package/dist/components/dialog/DialogContent.svelte +35 -33
  46. package/dist/components/dialog/DialogContent.svelte.d.ts +6 -20
  47. package/dist/components/dialog/DialogDescription.svelte +9 -12
  48. package/dist/components/dialog/DialogDescription.svelte.d.ts +6 -8
  49. package/dist/components/dialog/DialogRoot.svelte +20 -0
  50. package/dist/components/dialog/DialogRoot.svelte.d.ts +7 -0
  51. package/dist/components/dialog/DialogTitle.svelte +12 -8
  52. package/dist/components/dialog/DialogTitle.svelte.d.ts +8 -8
  53. package/dist/components/dialog/DialogTrigger.svelte +17 -0
  54. package/dist/components/dialog/DialogTrigger.svelte.d.ts +10 -0
  55. package/dist/components/dialog/index.d.ts +6 -5
  56. package/dist/components/dialog/index.js +3 -6
  57. package/dist/components/dialog/styles.d.ts +1 -2
  58. package/dist/components/dialog/styles.js +11 -8
  59. package/dist/components/hover-card/HoverCardContent.svelte +35 -29
  60. package/dist/components/hover-card/HoverCardContent.svelte.d.ts +8 -12
  61. package/dist/components/hover-card/HoverCardRoot.svelte +7 -7
  62. package/dist/components/hover-card/HoverCardRoot.svelte.d.ts +5 -4
  63. package/dist/components/hover-card/HoverCardTrigger.svelte +18 -0
  64. package/dist/components/hover-card/HoverCardTrigger.svelte.d.ts +10 -0
  65. package/dist/components/hover-card/index.d.ts +2 -3
  66. package/dist/components/hover-card/index.js +1 -5
  67. package/dist/components/input/Input.svelte.d.ts +1 -1
  68. package/dist/components/markdown/MarkdownBlock.svelte +6 -3
  69. package/dist/components/markdown/MarkdownTable.svelte +15 -7
  70. package/dist/components/menu/ContextMenuContent.svelte +15 -15
  71. package/dist/components/menu/ContextMenuContent.svelte.d.ts +6 -9
  72. package/dist/components/menu/ContextMenuTrigger.svelte +14 -16
  73. package/dist/components/menu/ContextMenuTrigger.svelte.d.ts +8 -14
  74. package/dist/components/menu/MenuCheckboxItem.svelte +22 -11
  75. package/dist/components/menu/MenuCheckboxItem.svelte.d.ts +8 -22
  76. package/dist/components/menu/MenuContent.svelte +16 -18
  77. package/dist/components/menu/MenuContent.svelte.d.ts +6 -18
  78. package/dist/components/menu/MenuGroup.svelte +4 -4
  79. package/dist/components/menu/MenuGroup.svelte.d.ts +5 -4
  80. package/dist/components/menu/MenuItem.svelte +25 -12
  81. package/dist/components/menu/MenuItem.svelte.d.ts +6 -21
  82. package/dist/components/menu/MenuLabel.svelte +7 -11
  83. package/dist/components/menu/MenuLabel.svelte.d.ts +6 -8
  84. package/dist/components/menu/MenuRadioGroup.svelte +4 -4
  85. package/dist/components/menu/MenuRadioGroup.svelte.d.ts +5 -4
  86. package/dist/components/menu/MenuRadioItem.svelte +16 -14
  87. package/dist/components/menu/MenuRadioItem.svelte.d.ts +6 -19
  88. package/dist/components/menu/MenuSeparator.svelte +6 -10
  89. package/dist/components/menu/MenuSeparator.svelte.d.ts +6 -7
  90. package/dist/components/menu/MenuSubContent.svelte +22 -19
  91. package/dist/components/menu/MenuSubContent.svelte.d.ts +8 -15
  92. package/dist/components/menu/MenuSubTrigger.svelte +7 -11
  93. package/dist/components/menu/MenuSubTrigger.svelte.d.ts +6 -15
  94. package/dist/components/menu/MenuTrigger.svelte +17 -0
  95. package/dist/components/menu/MenuTrigger.svelte.d.ts +10 -0
  96. package/dist/components/menu/context-menu.d.ts +2 -2
  97. package/dist/components/menu/context-menu.js +3 -2
  98. package/dist/components/menu/group.js +1 -1
  99. package/dist/components/menu/index.d.ts +5 -4
  100. package/dist/components/menu/index.js +5 -5
  101. package/dist/components/menu/row.d.ts +20 -0
  102. package/dist/components/menu/row.js +12 -0
  103. package/dist/components/popover/PopoverClose.svelte +17 -0
  104. package/dist/components/popover/PopoverClose.svelte.d.ts +10 -0
  105. package/dist/components/popover/PopoverContent.svelte +30 -29
  106. package/dist/components/popover/PopoverContent.svelte.d.ts +6 -17
  107. package/dist/components/popover/PopoverTrigger.svelte +17 -0
  108. package/dist/components/popover/PopoverTrigger.svelte.d.ts +10 -0
  109. package/dist/components/popover/index.d.ts +6 -4
  110. package/dist/components/popover/index.js +6 -5
  111. package/dist/components/progress/Progress.svelte +16 -22
  112. package/dist/components/progress/Progress.svelte.d.ts +6 -5
  113. package/dist/components/queued-message/QueuedMessage.svelte +10 -3
  114. package/dist/components/queued-message/QueuedMessage.svelte.d.ts +2 -1
  115. package/dist/components/rail/RailItem.svelte +20 -6
  116. package/dist/components/reasoning/ReasoningRoot.svelte.d.ts +1 -1
  117. package/dist/components/segmented/SegmentedControl.svelte +100 -91
  118. package/dist/components/segmented/SegmentedControl.svelte.d.ts +6 -4
  119. package/dist/components/select/Select.svelte +97 -59
  120. package/dist/components/select/Select.svelte.d.ts +3 -2
  121. package/dist/components/sheet/SheetContent.svelte +31 -38
  122. package/dist/components/sheet/SheetContent.svelte.d.ts +7 -22
  123. package/dist/components/sheet/index.d.ts +3 -5
  124. package/dist/components/sheet/index.js +3 -5
  125. package/dist/components/sheet/styles.js +26 -5
  126. package/dist/components/sidebar/SidebarItem.svelte +10 -6
  127. package/dist/components/slider/Slider.svelte +86 -65
  128. package/dist/components/slider/Slider.svelte.d.ts +9 -8
  129. package/dist/components/split-button/SplitButton.svelte +20 -3
  130. package/dist/components/split-button/SplitButton.svelte.d.ts +1 -1
  131. package/dist/components/switch/Switch.svelte +77 -49
  132. package/dist/components/switch/Switch.svelte.d.ts +15 -8
  133. package/dist/components/tab-strip/TabStrip.svelte +110 -76
  134. package/dist/components/tab-strip/TabStrip.svelte.d.ts +7 -2
  135. package/dist/components/tabs/Tabs.svelte +129 -99
  136. package/dist/components/tabs/Tabs.svelte.d.ts +6 -4
  137. package/dist/components/textarea/Textarea.svelte.d.ts +1 -1
  138. package/dist/components/toast/Toaster.svelte +132 -115
  139. package/dist/components/toast/Toaster.svelte.d.ts +5 -0
  140. package/dist/components/toast/toasts.svelte.d.ts +10 -23
  141. package/dist/components/toast/toasts.svelte.js +62 -40
  142. package/dist/components/toggle/Toggle.svelte +15 -9
  143. package/dist/components/toggle/Toggle.svelte.d.ts +8 -17
  144. package/dist/components/toggle-group/ToggleGroupItem.svelte +20 -9
  145. package/dist/components/toggle-group/ToggleGroupItem.svelte.d.ts +10 -10
  146. package/dist/components/toggle-group/ToggleGroupRoot.svelte +33 -18
  147. package/dist/components/toggle-group/ToggleGroupRoot.svelte.d.ts +4 -4
  148. package/dist/components/tool/ToolRoot.svelte.d.ts +1 -1
  149. package/dist/components/tooltip/TooltipContent.svelte +38 -28
  150. package/dist/components/tooltip/TooltipContent.svelte.d.ts +6 -15
  151. package/dist/components/tooltip/TooltipProvider.svelte +34 -10
  152. package/dist/components/tooltip/TooltipProvider.svelte.d.ts +18 -4
  153. package/dist/components/tooltip/TooltipRoot.svelte +52 -23
  154. package/dist/components/tooltip/TooltipRoot.svelte.d.ts +10 -10
  155. package/dist/components/tooltip/TooltipTrigger.svelte +14 -17
  156. package/dist/components/tooltip/TooltipTrigger.svelte.d.ts +10 -4
  157. package/dist/components/tooltip/index.d.ts +1 -1
  158. package/dist/components/tooltip/index.js +1 -1
  159. package/dist/components/work-fold/WorkFold.svelte +14 -5
  160. package/dist/index.d.ts +5 -5
  161. package/dist/index.js +1 -1
  162. package/dist/internal/TooltipScope.svelte +4 -4
  163. package/dist/internal/layer.d.ts +11 -9
  164. package/dist/internal/layer.js +21 -15
  165. package/dist/internal/loose.d.ts +30 -5
  166. package/dist/internal/loose.js +1 -1
  167. package/dist/internal/markers.stylex.d.ts +0 -4
  168. package/dist/internal/markers.stylex.js +0 -2
  169. package/dist/internal/toggle.d.ts +3 -0
  170. package/dist/internal/toggle.js +6 -2
  171. package/dist/internal/tooltip-trigger.d.ts +7 -6
  172. package/dist/internal/tooltip-trigger.js +9 -12
  173. package/dist/typography.d.ts +5 -0
  174. package/dist/typography.js +5 -0
  175. package/dist/vite.d.ts +7 -1
  176. package/dist/vite.js +20 -5
  177. package/package.json +3 -2
  178. package/skills/building-ui/SKILL.md +21 -21
  179. package/skills/building-ui/references/components.md +22 -7
  180. package/skills/markdown/SKILL.md +1 -1
  181. package/skills/setup/SKILL.md +4 -8
  182. package/skills/styling/SKILL.md +4 -2
  183. package/skills/theming/SKILL.md +3 -7
@@ -8,22 +8,36 @@
8
8
  move its caret.
9
9
  -->
10
10
  <script lang="ts" module>
11
- import type { Loose } from '../../internal/loose.js';
12
- import { Command } from 'bits-ui';
11
+ import type { Loose, PartProps } from '../../internal/loose.js';
12
+ import { Command, createCommandController } from '@ui-sdk/svelte/command';
13
13
  import type { Snippet } from 'svelte';
14
14
  import { attrs, type Sx } from '../../internal/sx.js';
15
+ import { provideCommand, useDialogLabel } from './context.js';
16
+ import { scoreItem } from './score.js';
15
17
  import { command } from './styles.js';
16
18
 
17
- export type CommandRootProps = Loose<
18
- Omit<Command.RootProps, 'children' | 'child'> & {
19
+ export interface CommandRootProps extends Loose<
20
+ Omit<
21
+ PartProps<typeof Command>,
22
+ | 'children'
23
+ | 'render'
24
+ | 'value'
25
+ | 'defaultValue'
26
+ | 'query'
27
+ | 'defaultQuery'
28
+ | 'items'
29
+ | 'emptyItems'
30
+ > & {
19
31
  /**
20
32
  * The value of the highlighted item. Bindable: set it to move the highlight from
21
33
  * outside. When the highlighted item goes, the highlight goes back to the first.
22
34
  */
23
35
  value?: string | undefined;
36
+ /** What the search field is called, for assistive technology, if it has no name of its own. */
37
+ label?: string | undefined;
24
38
  /**
25
- * Whether it filters and sorts the items itself, as the search changes. Pass `false`
26
- * to rank them yourself and list only those that match: results from a server, say.
39
+ * Whether it filters the items itself, as the search changes. Pass `false` to rank them
40
+ * yourself and list only those that match: results from a server, say.
27
41
  */
28
42
  shouldFilter?: boolean | undefined;
29
43
  /**
@@ -31,25 +45,43 @@
31
45
  * Off, those keys are left to the app's own shortcuts.
32
46
  */
33
47
  vimBindings?: boolean | undefined;
48
+ /** The root element. Bindable. */
49
+ ref?: HTMLElement | null | undefined;
34
50
  sx?: Sx | undefined;
35
51
  /** A Command.Input, a Command.List and, if you like, a Command.Footer. */
36
52
  children?: Snippet | undefined;
37
53
  }
38
- >;
54
+ > {}
39
55
 
40
56
  // Page Up and Page Down move the highlight this many items
41
57
  const PAGE = 8;
42
58
 
43
- // What a caret moves through, where Home and End are the field's
44
- const FIELD = '[data-command-input]';
59
+ const ITEM = '[data-slot="command-item"]';
60
+ const GROUP = '[data-slot="command-group"]';
61
+
62
+ // Where an element stands while the search ranks the list: the `order` the item, or its
63
+ // group, was given (`score.ts`), 0 when it has none
64
+ const placeOf = (element: Element | null) =>
65
+ element instanceof HTMLElement ? Number(element.style.order) || 0 : 0;
66
+
67
+ // ui-sdk moves the highlight with Ctrl and N or P on Apple platforms, which Narvi leaves to the app
68
+ const apple = () =>
69
+ typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
70
+
71
+ /** The step Ctrl and a letter takes, as in Vim (J, K) and Emacs (N, P). */
72
+ const VIM: Record<string, number> = { j: 1, n: 1, k: -1, p: -1 };
45
73
  </script>
46
74
 
47
75
  <script lang="ts">
48
76
  let {
49
77
  value = $bindable(''),
50
78
  ref = $bindable(null),
79
+ label,
51
80
  loop = true,
81
+ shouldFilter = true,
82
+ filter,
52
83
  vimBindings = false,
84
+ controller = createCommandController(),
53
85
  sx,
54
86
  class: className,
55
87
  children,
@@ -57,81 +89,239 @@
57
89
  ...rest
58
90
  }: CommandRootProps = $props();
59
91
 
60
- let root = $state<ReturnType<typeof Command.Root> | null>(null);
92
+ const dialogLabel = useDialogLabel();
61
93
 
62
- /** The items that can be highlighted, in order: not disabled, and not filtered out. */
94
+ // The search, which the field binds when it is there
95
+ let ownQuery = $state('');
96
+ let field = $state.raw<{ get: () => string; set: (query: string) => void } | null>(null);
97
+
98
+ // The search, from the field or the root's own
99
+ const query = $derived(field ? field.get() : ownQuery);
100
+ // Ranking the list is Narvi's while it filters: by the caller's `filter` if it scores
101
+ type Score = (
102
+ item: { label: string; keywords?: readonly string[] | undefined },
103
+ query: string
104
+ ) => number | boolean;
105
+ const scorer = $derived<Score | undefined>(
106
+ shouldFilter
107
+ ? typeof filter === 'function'
108
+ ? (filter as unknown as Score)
109
+ : filter
110
+ ? undefined
111
+ : scoreItem
112
+ : undefined
113
+ );
114
+ const ranking = $derived(scorer !== undefined && query.trim() !== '');
115
+
116
+ /**
117
+ * The items that can be highlighted, in the order they are shown: not disabled, and not
118
+ * filtered out. While the search ranks them, that is best first.
119
+ */
63
120
  export function getValidItems(): HTMLElement[] {
64
- return root?.getValidItems() ?? [];
121
+ if (!ref) return [];
122
+ const items = [...ref.querySelectorAll<HTMLElement>(ITEM)].filter(
123
+ (item) => !item.closest('[hidden]') && !item.hasAttribute('data-disabled')
124
+ );
125
+ if (!ranking) return items;
126
+ // A stable sort: items that score the same keep the order they are written in
127
+ return items.sort((a, b) => {
128
+ const groupA = a.closest(GROUP);
129
+ const groupB = b.closest(GROUP);
130
+ const outer = placeOf(groupA ?? a) - placeOf(groupB ?? b);
131
+ if (outer !== 0 || groupA !== groupB) return outer;
132
+ return placeOf(a) - placeOf(b);
133
+ });
65
134
  }
66
135
 
136
+ const set = (item: HTMLElement | undefined, event?: Event) => {
137
+ const key = item?.dataset.value;
138
+ if (key === undefined) return;
139
+ controller.setValue(key, event ? { reason: 'list-navigation', event } : undefined);
140
+ };
141
+
142
+ const current = (items: HTMLElement[]) =>
143
+ items.findIndex((item) => item.hasAttribute('data-highlighted'));
144
+
67
145
  /** Highlights the item at `index` among the valid items. */
68
146
  export function highlight(index: number): void {
69
- root?.updateSelectedToIndex(index);
147
+ set(getValidItems()[index]);
70
148
  }
71
149
 
72
150
  /** Moves the highlight by `step` items, stopping at the ends. */
73
- export function move(step: number): void {
151
+ export function move(step: number, event?: Event): void {
74
152
  const items = getValidItems();
75
153
  if (!items.length) return;
76
- const at = items.findIndex((item) => item.hasAttribute('data-selected'));
77
- highlight(Math.min(Math.max((at === -1 ? 0 : at) + step, 0), items.length - 1));
154
+ const at = current(items);
155
+ set(items[Math.min(Math.max((at === -1 ? 0 : at) + step, 0), items.length - 1)], event);
78
156
  }
79
157
 
80
- const keydown = (
81
- event: KeyboardEvent & { currentTarget: HTMLDivElement },
82
- list: ((event: KeyboardEvent) => void) | undefined
83
- ) => {
84
- onkeydown?.(event);
85
- // A word being composed keeps its keys (229: Safari's Japanese input, which sends no
86
- // `isComposing`)
87
- if (event.defaultPrevented || event.isComposing || event.keyCode === 229) return;
88
- const target = event.target instanceof Element ? event.target : null;
89
- const inField = !!target?.matches(FIELD);
90
- if (target !== event.currentTarget && !inField) return;
91
- if (inField && (event.key === 'Home' || event.key === 'End')) return;
158
+ // One item on, or back, wrapping past the ends with `loop`
159
+ const step = (by: 1 | -1, event: Event) => {
160
+ const items = getValidItems();
161
+ if (!items.length) return;
162
+ const at = current(items);
163
+ const next = at === -1 ? (by === 1 ? 0 : items.length - 1) : at + by;
164
+ if (loop) set(items[(next + items.length) % items.length], event);
165
+ else move(by, event);
166
+ };
167
+
168
+ const composing = (event: KeyboardEvent) =>
169
+ // 229: Safari's Japanese input, which sends no `isComposing`
170
+ event.isComposing || event.keyCode === 229;
171
+
172
+ const ctrlOnly = (event: KeyboardEvent) =>
173
+ event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
174
+
175
+ // Keys Narvi takes in the field before ui-sdk does: Page Up and Down by eight, and Ctrl
176
+ // with a letter, as asked
177
+ const fieldKeydown = (event: KeyboardEvent) => {
178
+ if (event.defaultPrevented || composing(event)) return;
179
+ // ui-sdk walks the items in the order they are written; while they are ranked, the
180
+ // arrows walk them in the order they are shown
181
+ if (ranking && (event.key === 'ArrowDown' || event.key === 'ArrowUp') && !event.altKey) {
182
+ event.preventDefault();
183
+ const down = event.key === 'ArrowDown';
184
+ if (event.metaKey) move(down ? Infinity : -Infinity, event);
185
+ else step(down ? 1 : -1, event);
186
+ return;
187
+ }
92
188
  if (event.key === 'PageDown' || event.key === 'PageUp') {
93
189
  event.preventDefault();
94
- move(event.key === 'PageDown' ? PAGE : -PAGE);
190
+ move(event.key === 'PageDown' ? PAGE : -PAGE, event);
191
+ return;
192
+ }
193
+ const by = ctrlOnly(event) ? VIM[event.key.toLowerCase()] : undefined;
194
+ if (by === undefined) return;
195
+ if (vimBindings) {
196
+ event.preventDefault();
197
+ step(by === 1 ? 1 : -1, event);
198
+ } else if (apple() && (event.key === 'n' || event.key === 'p')) {
199
+ // Keeps ui-sdk's Emacs keys off; the app's own listeners still hear the key
200
+ event.preventDefault();
201
+ }
202
+ };
203
+
204
+ // The root holding the focus itself, with no field: the keys ui-sdk gives only the field
205
+ const rootKeydown = (event: KeyboardEvent & { currentTarget: EventTarget & HTMLDivElement }) => {
206
+ onkeydown?.(event);
207
+ if (event.defaultPrevented || composing(event) || event.target !== event.currentTarget) return;
208
+ const by = ctrlOnly(event) && vimBindings ? VIM[event.key.toLowerCase()] : undefined;
209
+ if (by !== undefined) {
210
+ event.preventDefault();
211
+ step(by === 1 ? 1 : -1, event);
95
212
  return;
96
213
  }
97
- list?.(event);
214
+ switch (event.key) {
215
+ case 'ArrowDown':
216
+ case 'ArrowUp': {
217
+ event.preventDefault();
218
+ const down = event.key === 'ArrowDown';
219
+ if (event.metaKey) move(down ? Infinity : -Infinity, event);
220
+ else step(down ? 1 : -1, event);
221
+ return;
222
+ }
223
+ case 'Home':
224
+ case 'End':
225
+ event.preventDefault();
226
+ move(event.key === 'End' ? Infinity : -Infinity, event);
227
+ return;
228
+ case 'PageDown':
229
+ case 'PageUp':
230
+ event.preventDefault();
231
+ move(event.key === 'PageDown' ? PAGE : -PAGE, event);
232
+ return;
233
+ case 'Enter':
234
+ if (!controller.getValue()) return;
235
+ event.preventDefault();
236
+ controller.run();
237
+ }
98
238
  };
99
239
 
100
- // bits-ui means to move the highlight as its item goes, but compares the item's value with
101
- // the element's id, so it never does. Here, once the items change, a highlight left on one
102
- // that is gone goes back to the first.
240
+ provideCommand({
241
+ label: () => label ?? dialogLabel?.(),
242
+ bindQuery(get, setQuery) {
243
+ const own = { get, set: setQuery };
244
+ field = own;
245
+ return () => {
246
+ if (field === own) field = null;
247
+ };
248
+ },
249
+ keydown: fieldKeydown,
250
+ score: (item) => {
251
+ if (!ranking || !scorer) return undefined;
252
+ const result = scorer(item, query);
253
+ return typeof result === 'number' ? result : undefined;
254
+ }
255
+ });
256
+
257
+ // As the search changes, the best match is highlighted, so Enter runs it: the first item
258
+ // shown, once the list has taken its new order
259
+ $effect(() => {
260
+ if (!ranking) return;
261
+ void query;
262
+ let frame = requestAnimationFrame(() => {
263
+ set(getValidItems()[0]);
264
+ // ui-sdk brings it into view just under the edge; at the top of the list, its group's
265
+ // name shows over it
266
+ frame = requestAnimationFrame(() =>
267
+ ref?.querySelector('[data-slot="command-list"]')?.scrollTo({ top: 0 })
268
+ );
269
+ });
270
+ return () => cancelAnimationFrame(frame);
271
+ });
272
+
273
+ // The bound `value` is the highlight's, read from ui-sdk rather than passed to it: held
274
+ // there, it would keep the highlight where it was as the search changes. A `value` the
275
+ // caller sets moves the highlight.
276
+ $effect(() => {
277
+ const next = value;
278
+ if (!ref || !next) return;
279
+ const highlighted = ref.querySelector<HTMLElement>(`${ITEM}[data-highlighted]`);
280
+ if (highlighted?.dataset.value !== next) controller.setValue(next);
281
+ });
282
+
283
+ // ui-sdk highlights the first item as the list settles without saying so, where only a
284
+ // change it makes after is reported. Its highlight is written on the item, so the bound
285
+ // value follows that, as bits-ui's did.
103
286
  $effect(() => {
104
287
  const node = ref;
105
288
  if (!node) return;
106
- const observer = new MutationObserver(() => {
107
- const items = getValidItems();
108
- if (!items.length || items.some((item) => item.dataset.value === value)) return;
109
- highlight(0);
110
- });
111
- observer.observe(node, { childList: true, subtree: true });
289
+ const follow = () => {
290
+ const key = node.querySelector<HTMLElement>(`${ITEM}[data-highlighted]`)?.dataset.value;
291
+ if (key !== undefined && key !== value) value = key;
292
+ };
293
+ const observer = new MutationObserver(follow);
294
+ observer.observe(node, { subtree: true, attributeFilter: ['data-highlighted'] });
295
+ follow();
112
296
  return () => observer.disconnect();
113
297
  });
298
+
299
+ const hold = (node: HTMLElement) => {
300
+ ref = node;
301
+ return () => {
302
+ if (ref === node) ref = null;
303
+ };
304
+ };
114
305
  </script>
115
306
 
116
- <Command.Root
117
- bind:this={root}
118
- bind:value
119
- bind:ref
307
+ <Command
308
+ onValueChange={(next) => {
309
+ if ((next ?? '') !== value) value = next ?? '';
310
+ }}
311
+ bind:query={
312
+ () => (field ? field.get() : ownQuery),
313
+ (next) => {
314
+ if (field) field.set(next);
315
+ else ownQuery = next;
316
+ }
317
+ }
120
318
  {loop}
121
- {vimBindings}
122
- data-slot="command"
319
+ filter={shouldFilter ? ((scorer as typeof filter) ?? filter) : false}
320
+ {controller}
123
321
  {...rest}
322
+ onkeydown={rootKeydown}
323
+ {@attach hold}
124
324
  {...attrs([command.root, sx], className)}
125
325
  >
126
- {#snippet child({ props })}
127
- {@const { onkeydown: list, ...own } = props as typeof props & {
128
- onkeydown?: (event: KeyboardEvent) => void;
129
- }}
130
- <div
131
- {...own}
132
- onkeydown={(event: KeyboardEvent & { currentTarget: HTMLDivElement }) => keydown(event, list)}
133
- >
134
- {@render children?.()}
135
- </div>
136
- {/snippet}
137
- </Command.Root>
326
+ {@render children?.()}
327
+ </Command>
@@ -1,16 +1,18 @@
1
- import type { Loose } from '../../internal/loose.js';
2
- import { Command } from 'bits-ui';
1
+ import type { Loose, PartProps } from '../../internal/loose.js';
2
+ import { Command } from '@ui-sdk/svelte/command';
3
3
  import type { Snippet } from 'svelte';
4
4
  import { type Sx } from '../../internal/sx.js';
5
- export type CommandRootProps = Loose<Omit<Command.RootProps, 'children' | 'child'> & {
5
+ export interface CommandRootProps extends Loose<Omit<PartProps<typeof Command>, 'children' | 'render' | 'value' | 'defaultValue' | 'query' | 'defaultQuery' | 'items' | 'emptyItems'> & {
6
6
  /**
7
7
  * The value of the highlighted item. Bindable: set it to move the highlight from
8
8
  * outside. When the highlighted item goes, the highlight goes back to the first.
9
9
  */
10
10
  value?: string | undefined;
11
+ /** What the search field is called, for assistive technology, if it has no name of its own. */
12
+ label?: string | undefined;
11
13
  /**
12
- * Whether it filters and sorts the items itself, as the search changes. Pass `false`
13
- * to rank them yourself and list only those that match: results from a server, say.
14
+ * Whether it filters the items itself, as the search changes. Pass `false` to rank them
15
+ * yourself and list only those that match: results from a server, say.
14
16
  */
15
17
  shouldFilter?: boolean | undefined;
16
18
  /**
@@ -18,33 +20,17 @@ export type CommandRootProps = Loose<Omit<Command.RootProps, 'children' | 'child
18
20
  * Off, those keys are left to the app's own shortcuts.
19
21
  */
20
22
  vimBindings?: boolean | undefined;
23
+ /** The root element. Bindable. */
24
+ ref?: HTMLElement | null | undefined;
21
25
  sx?: Sx | undefined;
22
26
  /** A Command.Input, a Command.List and, if you like, a Command.Footer. */
23
27
  children?: Snippet | undefined;
24
- }>;
25
- declare const CommandRoot: import("svelte").Component<Loose<Omit<Command.RootProps, "children" | "child"> & {
26
- /**
27
- * The value of the highlighted item. Bindable: set it to move the highlight from
28
- * outside. When the highlighted item goes, the highlight goes back to the first.
29
- */
30
- value?: string | undefined;
31
- /**
32
- * Whether it filters and sorts the items itself, as the search changes. Pass `false`
33
- * to rank them yourself and list only those that match: results from a server, say.
34
- */
35
- shouldFilter?: boolean | undefined;
36
- /**
37
- * Whether Ctrl with J and N, or K and P, moves the highlight too, as in Vim and Emacs.
38
- * Off, those keys are left to the app's own shortcuts.
39
- */
40
- vimBindings?: boolean | undefined;
41
- sx?: Sx | undefined;
42
- /** A Command.Input, a Command.List and, if you like, a Command.Footer. */
43
- children?: Snippet | undefined;
44
- }>, {
28
+ }> {
29
+ }
30
+ declare const CommandRoot: import("svelte").Component<CommandRootProps, {
45
31
  getValidItems: () => HTMLElement[];
46
32
  highlight: (index: number) => void;
47
- move: (step: number) => void;
48
- }, "ref" | "value">;
33
+ move: (step: number, event?: Event) => void;
34
+ }, "value" | "ref">;
49
35
  type CommandRoot = ReturnType<typeof CommandRoot>;
50
36
  export default CommandRoot;
@@ -0,0 +1,18 @@
1
+ <script lang="ts" module>
2
+ import type { Loose, PartProps } from '../../internal/loose.js';
3
+ import { CommandSeparator as UiCommandSeparator } from '@ui-sdk/svelte/command';
4
+ import { useCommand } from './context.js';
5
+
6
+ export interface CommandSeparatorProps extends Loose<PartProps<typeof UiCommandSeparator>> {}
7
+ </script>
8
+
9
+ <script lang="ts">
10
+ let { ...rest }: CommandSeparatorProps = $props();
11
+
12
+ const root = useCommand();
13
+ // While the search ranks the items, the groups move and a line between two would land
14
+ // anywhere, so it steps aside, as bits-ui's did
15
+ const searching = $derived(root?.score({ label: '' }) !== undefined);
16
+ </script>
17
+
18
+ <UiCommandSeparator {...rest} hidden={searching || undefined} />
@@ -0,0 +1,7 @@
1
+ import type { Loose, PartProps } from '../../internal/loose.js';
2
+ import { CommandSeparator as UiCommandSeparator } from '@ui-sdk/svelte/command';
3
+ export interface CommandSeparatorProps extends Loose<PartProps<typeof UiCommandSeparator>> {
4
+ }
5
+ declare const CommandSeparator: import("svelte").Component<CommandSeparatorProps, {}, "">;
6
+ type CommandSeparator = ReturnType<typeof CommandSeparator>;
7
+ export default CommandSeparator;
@@ -0,0 +1,27 @@
1
+ export type CommandContext = {
2
+ /** What the field is called, for assistive technology. */
3
+ label: () => string | undefined;
4
+ /** Lends the root the field's bound `value` as the search. Returns how to take it back. */
5
+ bindQuery: (get: () => string, set: (query: string) => void) => () => void;
6
+ /** The root's own keys in the field, read before ui-sdk's. */
7
+ keydown: (event: KeyboardEvent) => void;
8
+ /**
9
+ * How well an item matches the search, while the list ranks it: `undefined` with nothing
10
+ * typed, or with filtering left to the app.
11
+ */
12
+ score: (item: {
13
+ label: string;
14
+ keywords?: readonly string[] | undefined;
15
+ }) => number | undefined;
16
+ };
17
+ /** What a Command.Group hears from its items: the place of each that matches, to go by the best. */
18
+ export type CommandGroupContext = {
19
+ place: (id: string, order: number | undefined) => void;
20
+ };
21
+ export declare const provideCommand: (context: CommandContext) => CommandContext;
22
+ export declare const useCommand: () => CommandContext | undefined;
23
+ export declare const provideCommandGroup: (context: CommandGroupContext) => CommandGroupContext;
24
+ export declare const useCommandGroup: () => CommandGroupContext | undefined;
25
+ /** The dialog's label, which names a field that has none of its own. */
26
+ export declare const provideDialogLabel: (label: () => string | undefined) => () => string | undefined;
27
+ export declare const useDialogLabel: () => (() => string | undefined) | undefined;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What a Command.Root shares with its Command.Input, and a Command.Dialog with the root inside
3
+ * it. ui-sdk keeps the search on the root, where Narvi binds it on the field, so the field lends
4
+ * the root its `value`; and the field takes its name from the root's `label`, or the dialog's.
5
+ */
6
+ import { getContext, setContext } from 'svelte';
7
+ const ROOT = Symbol('narvi.command');
8
+ const GROUP = Symbol('narvi.command-group');
9
+ const DIALOG = Symbol('narvi.command-dialog');
10
+ export const provideCommand = (context) => setContext(ROOT, context);
11
+ export const useCommand = () => getContext(ROOT);
12
+ export const provideCommandGroup = (context) => setContext(GROUP, context);
13
+ export const useCommandGroup = () => getContext(GROUP);
14
+ /** The dialog's label, which names a field that has none of its own. */
15
+ export const provideDialogLabel = (label) => setContext(DIALOG, label);
16
+ export const useDialogLabel = () => getContext(DIALOG);
@@ -1,4 +1,4 @@
1
- import { Command } from 'bits-ui';
1
+ import { CommandStatus } from '@ui-sdk/svelte/command';
2
2
  import { type Loosened } from '../../internal/loose.js';
3
3
  import Dialog from './CommandDialog.svelte';
4
4
  import Empty from './CommandEmpty.svelte';
@@ -8,9 +8,10 @@ import Input from './CommandInput.svelte';
8
8
  import Item from './CommandItem.svelte';
9
9
  import List from './CommandList.svelte';
10
10
  import Root from './CommandRoot.svelte';
11
- declare const Separator: Loosened<typeof Command.Separator>;
12
- declare const Loading: Loosened<typeof Command.Loading>;
13
- export { Dialog, Root, Input, List, Group, Item, Empty, Separator, Loading, Footer };
11
+ import Separator from './CommandSeparator.svelte';
12
+ /** Says how many items are listed, or that they are loading, from the root's `status`. */
13
+ declare const Status: Loosened<typeof CommandStatus>;
14
+ export { Dialog, Root, Input, List, Group, Item, Empty, Separator, Status, Footer };
14
15
  export type { CommandDialogProps } from './CommandDialog.svelte';
15
16
  export type { CommandEmptyProps } from './CommandEmpty.svelte';
16
17
  export type { CommandFooterProps } from './CommandFooter.svelte';
@@ -19,3 +20,4 @@ export type { CommandInputProps } from './CommandInput.svelte';
19
20
  export type { CommandItemProps } from './CommandItem.svelte';
20
21
  export type { CommandListProps } from './CommandList.svelte';
21
22
  export type { CommandRootProps } from './CommandRoot.svelte';
23
+ export type { CommandSeparatorProps } from './CommandSeparator.svelte';
@@ -1,4 +1,4 @@
1
- import { Command } from 'bits-ui';
1
+ import { CommandStatus } from '@ui-sdk/svelte/command';
2
2
  import { loose } from '../../internal/loose.js';
3
3
  import Dialog from './CommandDialog.svelte';
4
4
  import Empty from './CommandEmpty.svelte';
@@ -8,6 +8,7 @@ import Input from './CommandInput.svelte';
8
8
  import Item from './CommandItem.svelte';
9
9
  import List from './CommandList.svelte';
10
10
  import Root from './CommandRoot.svelte';
11
- const Separator = loose(Command.Separator);
12
- const Loading = loose(Command.Loading);
13
- export { Dialog, Root, Input, List, Group, Item, Empty, Separator, Loading, Footer };
11
+ import Separator from './CommandSeparator.svelte';
12
+ /** Says how many items are listed, or that they are loading, from the root's `status`. */
13
+ const Status = loose(CommandStatus);
14
+ export { Dialog, Root, Input, List, Group, Item, Empty, Separator, Status, Footer };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * How well an item matches the search, from 0 (not at all: it hides) to 1 (exactly).
3
+ *
4
+ * ui-sdk filters items written in markup by a score like this one, and highlights the best,
5
+ * but leaves them in the order they are written, where bits-ui sorted them. Narvi sorts them
6
+ * again (`style:order` on items and groups), so it scores them itself, with ui-sdk's own rules,
7
+ * and hands ui-sdk the same function: what hides, what comes first and what is highlighted
8
+ * then agree.
9
+ *
10
+ * - The whole text: 1.
11
+ * - The text starting with the search: from 0.9, more the more of the text it covers.
12
+ * - The search at the start of a word: from 0.75; anywhere else in a word: from 0.6.
13
+ * - Its letters in order across words: 0.1 to 0.5, more for letters that start words or
14
+ * follow each other.
15
+ */
16
+ /** How well `text` matches `query`. An empty search matches everything fully. */
17
+ export declare function scoreText(text: string, query: string): number;
18
+ /** An item's score: its label's, or a keyword's a little below it. */
19
+ export declare function scoreItem(item: {
20
+ label: string;
21
+ keywords?: readonly string[] | undefined;
22
+ }, query: string): number;
23
+ /**
24
+ * Where an item with this score goes: the CSS `order` that puts the best first. Items that
25
+ * score the same keep the order they are written in.
26
+ */
27
+ export declare const orderOf: (score: number) => number;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * How well an item matches the search, from 0 (not at all: it hides) to 1 (exactly).
3
+ *
4
+ * ui-sdk filters items written in markup by a score like this one, and highlights the best,
5
+ * but leaves them in the order they are written, where bits-ui sorted them. Narvi sorts them
6
+ * again (`style:order` on items and groups), so it scores them itself, with ui-sdk's own rules,
7
+ * and hands ui-sdk the same function: what hides, what comes first and what is highlighted
8
+ * then agree.
9
+ *
10
+ * - The whole text: 1.
11
+ * - The text starting with the search: from 0.9, more the more of the text it covers.
12
+ * - The search at the start of a word: from 0.75; anywhere else in a word: from 0.6.
13
+ * - Its letters in order across words: 0.1 to 0.5, more for letters that start words or
14
+ * follow each other.
15
+ */
16
+ // A word starts after one of these, as in ui-sdk
17
+ const SEPARATORS = new Set([' ', '-', '_', '/', '.', ':', ',', '(', ')', '[', ']', '@', '#']);
18
+ const startsWord = (text, index) => index === 0 || SEPARATORS.has(text[index - 1] ?? '');
19
+ /** Lower case, without accents, so `é` matches `e`. */
20
+ const fold = (text) => text.normalize('NFD').replace(/\p{M}/gu, '').toLocaleLowerCase().trim();
21
+ const coverage = (needle, haystack) => (0.09 * needle.length) / haystack.length;
22
+ function wordStart(haystack, needle, from) {
23
+ for (let index = from; index !== -1; index = haystack.indexOf(needle, index + 1)) {
24
+ if (startsWord(haystack, index))
25
+ return index;
26
+ }
27
+ return -1;
28
+ }
29
+ function subsequence(haystack, needle) {
30
+ let position = 0;
31
+ let previous = -2;
32
+ let bonus = 0;
33
+ let letters = 0;
34
+ for (const char of needle) {
35
+ if (char === ' ')
36
+ continue;
37
+ const found = haystack.indexOf(char, position);
38
+ if (found === -1)
39
+ return 0;
40
+ letters++;
41
+ if (startsWord(haystack, found))
42
+ bonus += 1;
43
+ if (found === previous + 1)
44
+ bonus += 1;
45
+ previous = found;
46
+ position = found + 1;
47
+ }
48
+ return letters ? 0.1 + (0.4 * bonus) / (2 * letters) : 0;
49
+ }
50
+ /** How well `text` matches `query`. An empty search matches everything fully. */
51
+ export function scoreText(text, query) {
52
+ const needle = fold(query);
53
+ if (!needle)
54
+ return 1;
55
+ const haystack = fold(text);
56
+ if (haystack === needle)
57
+ return 1;
58
+ const index = haystack.indexOf(needle);
59
+ if (index === 0)
60
+ return 0.9 + coverage(needle, haystack);
61
+ if (index > 0) {
62
+ return (wordStart(haystack, needle, index) !== -1 ? 0.75 : 0.6) + coverage(needle, haystack);
63
+ }
64
+ return subsequence(haystack, needle);
65
+ }
66
+ /** An item's score: its label's, or a keyword's a little below it. */
67
+ export function scoreItem(item, query) {
68
+ let best = scoreText(item.label, query);
69
+ for (const keyword of item.keywords ?? [])
70
+ best = Math.max(best, scoreText(keyword, query) * 0.95);
71
+ return best;
72
+ }
73
+ /**
74
+ * Where an item with this score goes: the CSS `order` that puts the best first. Items that
75
+ * score the same keep the order they are written in.
76
+ */
77
+ export const orderOf = (score) => Math.round((1 - score) * 10_000);