@torpor/ui 1.1.6 → 1.2.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.
@@ -31,6 +31,12 @@ interface ComboBoxProps {
31
31
  * options are rendered automatically.
32
32
  */
33
33
  load?: Loader;
34
+ /**
35
+ * Delays loader refetches while the user types: with a loader set, the
36
+ * fetch fires this many milliseconds after the last keystroke instead of
37
+ * on every keystroke. Only used together with `load`.
38
+ */
39
+ debounceMs?: number;
34
40
  /** Called after each successful load with the normalized result */
35
41
  onload?: (result: LoadResult) => void;
36
42
  /** Extracts the display text for a loaded item (defaults to `label ?? text ?? item`) */
@@ -119,9 +125,12 @@ export default function ComboBox($props: ComboBoxProps | undefined) {
119
125
  get name() {
120
126
  return $props?.name;
121
127
  },
122
- get multiple() {
123
- return $props?.multiple === true;
124
- },
128
+ get multiple() {
129
+ return $props?.multiple === true;
130
+ },
131
+ get debounceMs() {
132
+ return $props?.debounceMs;
133
+ },
125
134
  inField: () => form.inField,
126
135
  valid: () => form.valid,
127
136
  messageId: () => form.messageId,
@@ -48,6 +48,25 @@ export default function ComboBoxInput($props: ComboBoxInputProps | undefined) {
48
48
  // Set the trigger ID so that it can be used with aria-labelledby
49
49
  $state.triggerId = $props?.id ?? defaultId;
50
50
 
51
+ // When a loader is set with a debounceMs, keystrokes are pushed into a
52
+ // stream whose debounced handler writes the search text (which drives the
53
+ // loader's fetch). The stream owns the timer and drops pending calls on
54
+ // unmount; without a debounceMs, handleInput writes the search text
55
+ // directly and no stream is wired up.
56
+ let pushSearchText: ((value: string) => void) | undefined;
57
+ const debounceMs = context.getLoadedItems ? context.debounceMs : undefined;
58
+ if (debounceMs) {
59
+ $stream(
60
+ (push) => {
61
+ pushSearchText = push;
62
+ },
63
+ (value: string) => {
64
+ $state.searchText = value;
65
+ },
66
+ { debounce: debounceMs },
67
+ );
68
+ }
69
+
51
70
  function focusInput() {
52
71
  input.focus();
53
72
  }
@@ -72,9 +91,14 @@ export default function ComboBoxInput($props: ComboBoxInputProps | undefined) {
72
91
 
73
92
  function handleInput(e: InputEvent) {
74
93
  if (context.getLoadedItems) {
75
- // Loaded from a network loader: refetch with the current text
76
- $state.searchText = input.value;
94
+ // Loaded from a network loader: open the popout right away, and
95
+ // refetch with the current text (debounced when debounceMs is set)
77
96
  $state.visible = true;
97
+ if (pushSearchText) {
98
+ pushSearchText(input.value);
99
+ } else {
100
+ $state.searchText = input.value;
101
+ }
78
102
  } else if (context.searchItems) {
79
103
  context.searchText = input.value;
80
104
  const found = context.searchItems(context.searchText);
@@ -22,6 +22,8 @@ export interface ComboBoxContext extends PopoutContext {
22
22
  handleBlur?: () => void;
23
23
  /** Returns the items loaded from the network loader, when one is set */
24
24
  getLoadedItems?: () => any[];
25
+ /** The loader refetch debounce in milliseconds, when set */
26
+ debounceMs?: number;
25
27
  /** Extracts the display text for a loaded item */
26
28
  getItemLabel?: (item: any) => any;
27
29
  /** Extracts the value for a loaded item */
@@ -20,6 +20,12 @@ interface ComboBoxProps {
20
20
  * options are rendered automatically.
21
21
  */
22
22
  load?: Loader;
23
+ /**
24
+ * Delays loader refetches while the user types: with a loader set, the
25
+ * fetch fires this many milliseconds after the last keystroke instead of
26
+ * on every keystroke. Only used together with `load`.
27
+ */
28
+ debounceMs?: number;
23
29
  /** Called after each successful load with the normalized result */
24
30
  onload?: (result: LoadResult) => void;
25
31
  /** Extracts the display text for a loaded item (defaults to `label ?? text ?? item`) */
@@ -55,6 +55,8 @@ interface DataGridProps {
55
55
  ariaLabelledBy?: string;
56
56
  /** Called after each successful load with the normalized result (including `total`) */
57
57
  onload?: (result: LoadResult) => void;
58
+ /** Called when a load starts, including reloads triggered by sorting or paging */
59
+ onloadstart?: () => void;
58
60
  /** Called when the user sorts by a column */
59
61
  onsortchange?: (sortBy: string | undefined, sortDirection: "asc" | "desc") => void;
60
62
  }
@@ -117,6 +119,10 @@ export default function DataGrid($props: DataGridProps) {
117
119
  sortDirection: $props.sortDirection ?? "asc",
118
120
  activeCell: { row: 0, col: 0 },
119
121
 
122
+ // True while a loader request is in flight, so reloads (which keep the
123
+ // stale rows visible) can flag the table with aria-busy / data-loading
124
+ reloading: false,
125
+
120
126
  // The result of the current load. Suspends while pending when read,
121
127
  // which drives the @await boundary in the template.
122
128
  get loadResult(): LoadResult | undefined {
@@ -219,6 +225,10 @@ export default function DataGrid($props: DataGridProps) {
219
225
  };
220
226
  }
221
227
 
228
+ // Incremented on every load; only the latest load's settle updates
229
+ // the pending flag
230
+ let loadGeneration = 0;
231
+
222
232
  function runLoad(): Promise<LoadResult> {
223
233
  const request: LoadRequest = {};
224
234
  if ($props.pageSize) {
@@ -229,10 +239,28 @@ export default function DataGrid($props: DataGridProps) {
229
239
  request.sortBy = $state.sortBy;
230
240
  request.sortDirection = $state.sortDirection;
231
241
  }
242
+ // Flag the load as pending (and notify the consumer) before awaiting;
243
+ // only the latest load's settle clears the flag, so a reload that
244
+ // overtakes an older request doesn't drop the indicator early
245
+ const generation = ++loadGeneration;
246
+ $state.reloading = true;
247
+ $props.onloadstart?.();
232
248
  const result = Promise.resolve(($props.load as Loader)(request)).then(normalizeLoadResult);
233
249
  // Report successful loads to the consumer; failures surface through
234
250
  // the component's error boundary, not this notification chain
235
- result.then((r) => $props.onload?.(r), () => {});
251
+ result.then(
252
+ (r) => {
253
+ if (generation === loadGeneration) {
254
+ $state.reloading = false;
255
+ }
256
+ $props.onload?.(r);
257
+ },
258
+ () => {
259
+ if (generation === loadGeneration) {
260
+ $state.reloading = false;
261
+ }
262
+ },
263
+ );
236
264
  return result;
237
265
  }
238
266
 
@@ -422,6 +450,8 @@ export default function DataGrid($props: DataGridProps) {
422
450
  aria-label={$props.ariaLabel}
423
451
  aria-labelledby={$props.ariaLabelledBy}
424
452
  aria-rowcount={hasLoader || isVirtual() ? $state.totalCount : undefined}
453
+ aria-busy={$state.reloading ? "true" : undefined}
454
+ data-loading={$state.reloading ? "true" : undefined}
425
455
  onkeydown={handleKeydown}
426
456
  onfocusin={handleFocusin}
427
457
  >
@@ -45,6 +45,8 @@ interface DataGridProps {
45
45
  ariaLabelledBy?: string;
46
46
  /** Called after each successful load with the normalized result (including `total`) */
47
47
  onload?: (result: LoadResult) => void;
48
+ /** Called when a load starts, including reloads triggered by sorting or paging */
49
+ onloadstart?: () => void;
48
50
  /** Called when the user sorts by a column */
49
51
  onsortchange?: (sortBy: string | undefined, sortDirection: "asc" | "desc") => void;
50
52
  }
@@ -34,7 +34,7 @@ export default function DialogHeader($props: DialogHeaderProps | undefined) {
34
34
  }
35
35
 
36
36
  @render {
37
- <div id={$props?.id ?? defaultId} class={["torp-dialog-footer", $props?.class]} {$props?.style}>
37
+ <div id={$props?.id ?? defaultId} class={["torp-dialog-header", $props?.class]} {$props?.style}>
38
38
  <slot />
39
39
  </div>
40
40
  }
@@ -54,33 +54,56 @@ export default function Form<Data = Record<string, any>>($props: FormProps<Data>
54
54
 
55
55
  $context[FormContextName] = context;
56
56
 
57
- async function validate() {
58
- if ($props?.schema) {
59
- const validator = $props.schema["~standard"];
60
- let result = validator.validate($props.data);
61
- if (result instanceof Promise) {
62
- result = await result;
63
- }
64
- let issues: ValidationIssue[] = [];
65
- if (result.issues) {
66
- for (let issue of result.issues) {
67
- if (issue.path) {
68
- // TODO: arrays with `[0]` etc
69
- issues.push({
70
- // @ts-ignore
71
- path: issue.path.map((p) => p.key ?? p).join("."),
72
- message: issue.message,
73
- });
74
- }
57
+ function applyIssues(result: StandardSchemaV1.Result<any> | undefined) {
58
+ let issues: ValidationIssue[] = [];
59
+ if (result?.issues) {
60
+ for (let issue of result.issues) {
61
+ if (issue.path) {
62
+ // TODO: arrays with `[0]` etc
63
+ issues.push({
64
+ // @ts-ignore
65
+ path: issue.path.map((p) => p.key ?? p).join("."),
66
+ message: issue.message,
67
+ });
75
68
  }
76
69
  }
77
- $state.issues = issues;
78
70
  }
71
+ $state.issues = issues;
72
+ }
73
+
74
+ /**
75
+ * Validates the form's data. Returns synchronously for synchronous schemas,
76
+ * or a promise that must be awaited for asynchronous ones.
77
+ */
78
+ function validate(): void | Promise<void> {
79
+ if (!$props?.schema) {
80
+ return;
81
+ }
82
+ const result = $props.schema["~standard"].validate($props.data);
83
+ if (result instanceof Promise) {
84
+ return result.then(applyIssues);
85
+ }
86
+ applyIssues(result);
79
87
  }
80
88
 
81
89
  async function handleSubmit(e: SubmitEvent) {
82
- // Validate, and proceed with submission if there are no errors
83
- await validate();
90
+ // Run validation. A synchronous schema is fully resolved by this point,
91
+ // but an async one returns a promise -- and if we awaited it we'd only
92
+ // call `preventDefault` after the browser had already started its own
93
+ // submission (loading the action's response as a full page). So stop the
94
+ // native submit up front and carry on once validation resolves.
95
+ const validation = validate();
96
+ if (validation instanceof Promise) {
97
+ e.preventDefault();
98
+ await validation;
99
+ await finishSubmit(e, true);
100
+ } else {
101
+ await finishSubmit(e, false);
102
+ }
103
+ }
104
+
105
+ async function finishSubmit(e: SubmitEvent, prePrevented: boolean) {
106
+ // Validation has run: proceed if there are no errors
84
107
  let proceed = $state.valid;
85
108
 
86
109
  // Changing inputs from now on will cause revalidation
@@ -98,7 +121,10 @@ export default function Form<Data = Record<string, any>>($props: FormProps<Data>
98
121
  if (userSubmit instanceof Promise) {
99
122
  userSubmit = await userSubmit;
100
123
  }
101
- proceed = userSubmit !== false && !e.defaultPrevented;
124
+ // When the default was already prevented (async validation) we
125
+ // can't use `defaultPrevented` to see if the handler opted out, so
126
+ // only its return value counts
127
+ proceed = userSubmit !== false && (prePrevented || !e.defaultPrevented);
102
128
  }
103
129
 
104
130
  // If the user handled the submit, don't continue
@@ -107,23 +133,26 @@ export default function Form<Data = Record<string, any>>($props: FormProps<Data>
107
133
  return false;
108
134
  }
109
135
 
110
- // If there's a @torpor/build context, call its submit event
136
+ // If there's a @torpor/build context, it handles the submission itself
137
+ // (it posts the form and prevents the native submit)
111
138
  let buildContext = $context?.["TorporBuildContext"];
112
139
  if (buildContext?.onformsubmit) {
113
140
  let buildSubmit = buildContext.onformsubmit(e);
114
141
  if (buildSubmit instanceof Promise) {
115
142
  buildSubmit = await buildSubmit;
116
143
  }
117
- proceed = buildSubmit !== false && !e.defaultPrevented;
118
- }
119
-
120
- // If @torpor/build handled the submit, don't continue
121
- if (!proceed) {
122
- e.preventDefault();
144
+ if (buildSubmit === false) {
145
+ e.preventDefault();
146
+ }
123
147
  return false;
124
148
  }
125
149
 
126
- // Otherwise just let normal form submission go ahead...
150
+ // Nothing handled the submit. When validation was synchronous the
151
+ // browser's own submission is still pending, so let it happen.
152
+ // Otherwise it was already prevented, so submit the form ourselves.
153
+ if (prePrevented) {
154
+ (e.target as HTMLFormElement).submit();
155
+ }
127
156
  }
128
157
 
129
158
  async function handleValidate() {
@@ -10,6 +10,8 @@
10
10
  * cancels a pending close entirely
11
11
  */
12
12
 
13
+ import { consumeFocusOpenSuppress } from "./suppressFocusOpen";
14
+
13
15
  export interface HoverRevealOptions {
14
16
  /** Shows the popout */
15
17
  show: () => void;
@@ -51,7 +53,6 @@ export function createHoverReveal(options: HoverRevealOptions): HoverRevealHandl
51
53
 
52
54
  let openTimer: ReturnType<typeof setTimeout> | undefined;
53
55
  let closeTimer: ReturnType<typeof setTimeout> | undefined;
54
- let suppressFocusOpen = false;
55
56
 
56
57
  function clearTimers() {
57
58
  if (openTimer !== undefined) {
@@ -78,10 +79,9 @@ export function createHoverReveal(options: HoverRevealOptions): HoverRevealHandl
78
79
  closeTimer = setTimeout(() => {
79
80
  closeTimer = undefined;
80
81
  stopListening();
81
- // The content hides with `refocusAnchorOnHide`, which drops
82
- // focus back onto this trigger -- that is not user intent,
83
- // so swallow the one focus-driven open that follows
84
- suppressFocusOpen = true;
82
+ // The content hides with `refocusAnchorOnHide`, which drops focus
83
+ // back onto this trigger; the popout machinery arms the scripted-
84
+ // focus guard before it does, so handleFocus ignores it
85
85
  hide();
86
86
  }, exitGrace);
87
87
 
@@ -164,8 +164,10 @@ export function createHoverReveal(options: HoverRevealOptions): HoverRevealHandl
164
164
  handleFocus() {
165
165
  if (disabled()) return;
166
166
 
167
- if (suppressFocusOpen) {
168
- suppressFocusOpen = false;
167
+ // The content just hid and refocused this trigger
168
+ // (`refocusAnchorOnHide` + the scripted-focus guard); that
169
+ // refocus is not user intent, so don't re-open
170
+ if (consumeFocusOpenSuppress()) {
169
171
  return;
170
172
  }
171
173
 
@@ -1,6 +1,7 @@
1
1
  import { addDocumentEvent, removeDocumentEvent } from "./documentEvents";
2
2
  import getScrollParent from "./getScrollParent";
3
3
  import setPopoverPosition from "./setPopoverPosition";
4
+ import { suppressFocusOpen } from "./suppressFocusOpen";
4
5
 
5
6
  export interface PopoutContentOptions {
6
7
  /** Resolves the element to position the content against */
@@ -128,7 +129,13 @@ export function createPopoutContent(options: PopoutContentOptions): {
128
129
  document.activeElement === document.body
129
130
  ) {
130
131
  const el = options.getAnchor();
131
- el?.focus?.();
132
+ if (el) {
133
+ // The refocus is script-driven, not user intent: arm the
134
+ // guard so focus-to-open triggers (e.g. hover popovers)
135
+ // don't immediately re-open
136
+ suppressFocusOpen();
137
+ el.focus();
138
+ }
132
139
  }
133
140
  }
134
141
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * One-shot guard for focus events caused by the popout machinery itself.
3
+ *
4
+ * When popout content hides with `refocusAnchorOnHide`, focus drops back
5
+ * onto the anchor -- which may be a component that opens on focus (e.g.
6
+ * PopoverHover, ContextualHover). That scripted refocus is not user intent,
7
+ * so focus-to-open handlers consult `consumeFocusOpenSuppress` to ignore it,
8
+ * instead of arming their own workaround guards.
9
+ */
10
+
11
+ let armed = false;
12
+
13
+ /**
14
+ * Arms the guard, so the next focus-to-open check treats the focus as
15
+ * script-driven. Call immediately before a scripted `focus()` call.
16
+ */
17
+ export function suppressFocusOpen(): void {
18
+ armed = true;
19
+ // If the scripted refocus never fires (the anchor was already focused,
20
+ // so focus() is a no-op), the guard must not swallow a real user focus
21
+ queueMicrotask(() => {
22
+ armed = false;
23
+ });
24
+ }
25
+
26
+ /** Returns whether the current focus was armed, and disarms it */
27
+ export function consumeFocusOpenSuppress(): boolean {
28
+ if (!armed) return false;
29
+ armed = false;
30
+ return true;
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torpor/ui",
3
- "version": "1.1.6",
3
+ "version": "1.2.0",
4
4
  "description": "Accessible, unstyled components for use in your Torpor front-end",
5
5
  "type": "module",
6
6
  "torpor": true,
@@ -181,25 +181,25 @@
181
181
  "author": "",
182
182
  "license": "ISC",
183
183
  "dependencies": {
184
- "@torpor/unplugin": "^1.2.0",
185
- "@torpor/view": "^1.1.2"
184
+ "@torpor/unplugin": "^1.2.2",
185
+ "@torpor/view": "^1.2.0"
186
186
  },
187
187
  "devDependencies": {
188
- "@testing-library/dom": "^10.4.1",
189
- "@testing-library/jest-dom": "^7.0.0",
190
- "@testing-library/user-event": "^14.6.3",
191
- "@types/jsdom": "^28.0.3",
192
- "@types/node": "^26.1.2",
188
+ "@testing-library/dom": "^10.4.2",
189
+ "@testing-library/jest-dom": "^7.0.1",
190
+ "@testing-library/user-event": "^14.6.7",
191
+ "@types/jsdom": "^30.0.0",
192
+ "@types/node": "^26.6.4",
193
193
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
194
- "chalk": "^6.0.0",
195
- "jsdom": "^30.0.1",
196
- "tsx": "^4.23.5",
194
+ "chalk": "^6.0.1",
195
+ "jsdom": "^30.1.2",
196
+ "tsx": "^4.23.15",
197
197
  "typescript": "^7.0.2",
198
- "vite": "npm:@voidzero-dev/vite-plus-core@0.3.0",
199
- "vite-plus": "0.3.0",
200
- "zod": "^4.4.3",
201
- "@torpor/prettier": "^1.0.6",
202
- "@torpor/check": "^1.0.6"
198
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.1.0",
199
+ "vite-plus": "1.1.0",
200
+ "zod": "^4.6.5",
201
+ "@torpor/prettier": "^1.0.8",
202
+ "@torpor/check": "^1.0.8"
203
203
  },
204
204
  "scripts": {
205
205
  "build": "tsgo --noEmit && vp pack",