@flowdrop/flowdrop 2.15.0 → 2.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.15.1] - 2026-10-17
9
+
10
+ ### Fixed
11
+
12
+ - **An autocomplete dropdown that opens above its field stays next to the field.** When there was too
13
+ little room below, the list was meant to open above the field but stuck to the top of the window
14
+ instead, which is where the third field of a cascade usually ended up.
15
+ - **A filled autocomplete field shows its label when the form opens.** It used to show the stored value
16
+ (`org-acme` instead of "Acme Corp") until the field was focused, because labels were only learned from
17
+ suggestions. When the field's config allows an empty query (`fetchOnFocus: true` and `minChars: 0`), it
18
+ now sends that empty query once when the form opens, and again when an undo or external edit brings in
19
+ values it has no label for: one extra request per filled field. Only values in that response get a
20
+ label, so an endpoint that returns just its first page leaves the others showing the stored value, as
21
+ do other configs until a search returns them. The request goes through the auth provider like any
22
+ other, so a `401`/`403` from it reaches `onUnauthorized`/`onForbidden` when the form opens. It runs
23
+ beside the field's own requests: no spinner, no error in the dropdown (a failure is only logged), and
24
+ focusing the field still loads its suggestions as before.
25
+ - **An autocomplete field keeps its loading state while a newer search is in flight.** A cancelled
26
+ request used to clear the spinner of the search that replaced it, and left that search impossible to
27
+ cancel, so results for old dependency values could still land after a dependency field changed.
28
+ - **An autocomplete search that times out says so.** After 5 seconds the request was cancelled like a
29
+ superseded one, leaving an empty list with no error and no retry. It now shows "The request timed
30
+ out" (`form.autocomplete.timedOut`, translatable like the other messages) with the retry button.
31
+ - **Requests that get a `401` at the same time share one `onUnauthorized()` call.** Each used to call it,
32
+ so a form whose autocomplete fields looked up their labels with an expired token refreshed it (or
33
+ asked for a login) once per field. They now wait for the one call and retry with its result; the next
34
+ `401` after it settles calls it again.
35
+
8
36
  ## [2.15.0] - 2026-10-16
9
37
 
10
38
  ### Added
@@ -9,6 +9,7 @@ import { buildEndpointUrl, getEndpointMethod, getRequestHeaders } from '../confi
9
9
  import { NoAuthProvider } from '../types/auth.js';
10
10
  import { getApiSettings } from '../stores/settingsStore.svelte.js';
11
11
  import { logger } from '../utils/logger.js';
12
+ import { refreshAuth } from '../utils/fetchWithAuth.js';
12
13
  import { DEFAULT_API_TIMEOUT_MS } from '../config/constants.js';
13
14
  /**
14
15
  * API error with additional context
@@ -166,7 +167,7 @@ export class EnhancedFlowDropApiClient {
166
167
  // Handle 401 Unauthorized
167
168
  if (response.status === 401) {
168
169
  if (this.authProvider.onUnauthorized) {
169
- const refreshed = await this.authProvider.onUnauthorized();
170
+ const refreshed = await refreshAuth(this.authProvider);
170
171
  if (refreshed && attempt < maxAttempts) {
171
172
  // Rebuild headers via the shared path to pick up the fresh token.
172
173
  fetchConfig.headers = {
@@ -24,7 +24,8 @@
24
24
  -->
25
25
 
26
26
  <script lang="ts">
27
- import { getContext, onMount } from 'svelte';
27
+ import { getContext, onMount, untrack } from 'svelte';
28
+ import { SvelteMap } from 'svelte/reactivity';
28
29
  import Icon from '@iconify/svelte';
29
30
  import type { AutocompleteConfig, AuthProvider } from '../../types/index.js';
30
31
  import type { FieldOption } from './types.js';
@@ -102,12 +103,19 @@
102
103
  let highlightedIndex = $state(-1);
103
104
  let debounceTimer: ReturnType<typeof setTimeout> | null = null;
104
105
  let abortController: AbortController | null = null;
106
+ // The label lookup's own request, and the key of the last one sent (see
107
+ // lookupLabels and the effect that calls it).
108
+ let labelController: AbortController | null = null;
109
+ let labelLookupKey = '';
110
+ // Values typed into this field rather than loaded from outside; no endpoint
111
+ // has a label for them, so the label lookup skips them.
112
+ const typed = new Set<string>();
105
113
 
106
114
  // Popover positioning style
107
115
  let popoverStyle = $state('');
108
116
 
109
117
  // Cache of value-to-label mappings for selected items
110
- let labelCache = $state<Map<string, string>>(new Map());
118
+ const labelCache = new SvelteMap<string, string>();
111
119
 
112
120
  // Resolved values for each param dependency: { paramName -> currentFieldValue }
113
121
  // Used both in buildUrl (appending to query) and in the dep-change effect.
@@ -170,18 +178,8 @@
170
178
  * Get display label for a selected value
171
179
  */
172
180
  function getDisplayLabel(val: string): string {
173
- // Check cache first
174
- if (labelCache.has(val)) {
175
- return labelCache.get(val) ?? val;
176
- }
177
- // Check current suggestions
178
- const match = suggestions.find((s) => s.value === val);
179
- if (match) {
180
- labelCache.set(val, match.label);
181
- return match.label;
182
- }
183
- // Return value as fallback
184
- return val;
181
+ // Every fetched suggestion and every pick lands in the cache.
182
+ return labelCache.get(val) ?? val;
185
183
  }
186
184
 
187
185
  /**
@@ -222,6 +220,14 @@
222
220
  }));
223
221
  }
224
222
 
223
+ /**
224
+ * Abort reason for a request that ran out of time. Unlike a plain abort
225
+ * (superseded or unmounted), it is a failure the field reports.
226
+ */
227
+ function timeoutError(): DOMException {
228
+ return new DOMException('Request timed out', 'TimeoutError');
229
+ }
230
+
225
231
  /**
226
232
  * Fetch suggestions from the callback URL
227
233
  * @param query - The search query
@@ -248,7 +254,7 @@
248
254
 
249
255
  let timeoutId: ReturnType<typeof setTimeout> | null = null;
250
256
  try {
251
- timeoutId = setTimeout(() => controller.abort(), 5000);
257
+ timeoutId = setTimeout(() => controller.abort(timeoutError()), 5000);
252
258
 
253
259
  // authenticatedFetch merges auth headers (call getter for current value)
254
260
  // and applies the 401/403 lifecycle consistently with the rest of the lib.
@@ -263,6 +269,8 @@
263
269
  }
264
270
 
265
271
  const data = await response.json();
272
+ // A newer request (or a dependency change) superseded this one.
273
+ if (controller.signal.aborted) return;
266
274
  const mapped = mapResponse(data);
267
275
 
268
276
  // Update label cache with fetched suggestions
@@ -278,12 +286,21 @@
278
286
  return;
279
287
  }
280
288
  logger.error('[FormAutocomplete] Fetch error:', err);
281
- error = err instanceof Error ? err.message : 'Failed to fetch suggestions';
289
+ error =
290
+ err instanceof Error
291
+ ? err.name === 'TimeoutError'
292
+ ? t.timedOut
293
+ : err.message
294
+ : 'Failed to fetch suggestions';
282
295
  suggestions = [];
283
296
  } finally {
284
297
  if (timeoutId !== null) clearTimeout(timeoutId);
285
- isLoading = false;
286
- abortController = null;
298
+ // An aborted request settles after its replacement started; the loading
299
+ // state and controller belong to that replacement then.
300
+ if (abortController === controller) {
301
+ isLoading = false;
302
+ abortController = null;
303
+ }
287
304
  }
288
305
  }
289
306
 
@@ -363,14 +380,26 @@
363
380
  // Backspace-on-empty. Replaces the per-keystroke commit dropped from
364
381
  // handleInput; see issue #32.
365
382
  if (allowFreeText && !multiple && inputValue !== '') {
366
- const currentSingle = selectedValues[0] ?? '';
367
- if (inputValue !== currentSingle) {
368
- onChange(inputValue);
369
- }
383
+ commitFreeText(inputValue);
370
384
  }
371
385
  }, 200);
372
386
  }
373
387
 
388
+ /**
389
+ * Commit text the user typed as a value (free-text mode). Adds it in
390
+ * multiple mode unless already selected; replaces the value in single mode
391
+ * unless unchanged.
392
+ * @param text - The typed text
393
+ */
394
+ function commitFreeText(text: string): void {
395
+ typed.add(text);
396
+ if (multiple) {
397
+ if (!selectedValues.includes(text)) onChange([...selectedValues, text]);
398
+ } else if (text !== (selectedValues[0] ?? '')) {
399
+ onChange(text);
400
+ }
401
+ }
402
+
374
403
  /**
375
404
  * Handle option selection
376
405
  * @param option - Selected option
@@ -464,14 +493,10 @@
464
493
  if (highlightedIndex >= 0 && highlightedIndex < suggestions.length) {
465
494
  selectOption(suggestions[highlightedIndex]);
466
495
  } else if (allowFreeText && inputValue !== '') {
496
+ commitFreeText(inputValue);
467
497
  if (multiple) {
468
- const current = selectedValues;
469
- if (!current.includes(inputValue)) {
470
- onChange([...current, inputValue]);
471
- }
472
498
  inputValue = '';
473
499
  } else {
474
- onChange(inputValue);
475
500
  hideDropdown();
476
501
  }
477
502
  }
@@ -508,22 +533,6 @@
508
533
  inputElement?.focus();
509
534
  }
510
535
 
511
- /**
512
- * Sync label cache when value prop changes externally
513
- */
514
- $effect(() => {
515
- // When value changes, try to find labels from suggestions
516
- const vals = selectedValues;
517
- vals.forEach((val) => {
518
- if (!labelCache.has(val)) {
519
- const match = suggestions.find((s) => s.value === val);
520
- if (match) {
521
- labelCache.set(val, match.label);
522
- }
523
- }
524
- });
525
- });
526
-
527
536
  /**
528
537
  * Calculate popover position relative to viewport
529
538
  * Popover API renders in top layer, bypassing all stacking contexts
@@ -613,8 +622,60 @@
613
622
  // parent form's handleFieldChange so it only fires on user-driven changes,
614
623
  // not on undo/redo, programmatic resets, or collaborative edits (#33).
615
624
  abortController?.abort();
625
+ labelController?.abort();
616
626
  suggestions = [];
617
- labelCache = new Map();
627
+ labelCache.clear();
628
+ // The cleared labels need a new lookup, even for a key looked up before.
629
+ labelLookupKey = '';
630
+ });
631
+
632
+ /**
633
+ * Look up labels for values the cache does not know, with the empty query
634
+ * the field would send on focus. Its own request: it never touches the
635
+ * suggestions, the loading state or the error, so it cannot disturb a
636
+ * search the user is running, and a search cannot cancel it.
637
+ */
638
+ async function lookupLabels(): Promise<void> {
639
+ labelController?.abort();
640
+ const controller = new AbortController();
641
+ labelController = controller;
642
+ const fingerprint = depFingerprint;
643
+ const timeoutId = setTimeout(() => controller.abort(timeoutError()), 5000);
644
+ try {
645
+ const response = await authenticatedFetch(
646
+ buildUrl(''),
647
+ { method: 'GET', signal: controller.signal },
648
+ { authProvider: getAuthProvider?.() }
649
+ );
650
+ if (!response.ok) {
651
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
652
+ }
653
+ const mapped = mapResponse(await response.json());
654
+ // Labels fetched for other dependency values would be wrong now.
655
+ if (controller.signal.aborted || fingerprint !== depFingerprint) return;
656
+ for (const opt of mapped) labelCache.set(opt.value, opt.label);
657
+ } catch (err) {
658
+ if (err instanceof Error && err.name === 'AbortError') return;
659
+ logger.warn('[FormAutocomplete] Label lookup failed:', err);
660
+ } finally {
661
+ clearTimeout(timeoutId);
662
+ if (labelController === controller) labelController = null;
663
+ }
664
+ }
665
+
666
+ // Labels are otherwise only learned from suggestions, so a preloaded value
667
+ // (form open, undo, external edit) would show its raw value until the user
668
+ // focuses the field. When the config allows an empty query, look the labels
669
+ // up once per set of unknown values and dependency values, so a value the
670
+ // endpoint does not return is not retried in a loop.
671
+ $effect(() => {
672
+ if (!fetchOnFocus || minChars > 0) return;
673
+ const missing = selectedValues.filter((val) => !labelCache.has(val) && !typed.has(val));
674
+ if (missing.length === 0) return;
675
+ const key = `${depFingerprint}|${missing.join('\u0000')}`;
676
+ if (key === labelLookupKey) return;
677
+ labelLookupKey = key;
678
+ untrack(() => lookupLabels());
618
679
  });
619
680
 
620
681
  /**
@@ -630,6 +691,7 @@
630
691
  if (abortController) {
631
692
  abortController.abort();
632
693
  }
694
+ labelController?.abort();
633
695
  };
634
696
  });
635
697
  </script>
@@ -979,6 +1041,10 @@
979
1041
  /* Popover container - renders in top layer via Popover API */
980
1042
  .form-autocomplete__popover {
981
1043
  position: fixed;
1044
+ /* UA [popover] sets inset: 0; without this reset the inline `bottom`
1045
+ of the flip-above placement loses to top: 0 and the list sticks to
1046
+ the top of the viewport. */
1047
+ inset: auto;
982
1048
  margin: 0;
983
1049
  padding: 0;
984
1050
  border: none;
@@ -131,6 +131,7 @@ export declare const defaultMessages: {
131
131
  readonly clearAll: "Clear all selections";
132
132
  readonly suggestions: "Suggestions";
133
133
  readonly retry: "Retry";
134
+ readonly timedOut: "The request timed out";
134
135
  readonly noResults: "No results found";
135
136
  };
136
137
  readonly field: {
@@ -105,6 +105,7 @@ export const defaultMessages = {
105
105
  clearAll: 'Clear all selections',
106
106
  suggestions: 'Suggestions',
107
107
  retry: 'Retry',
108
+ timedOut: 'The request timed out',
108
109
  noResults: 'No results found'
109
110
  },
110
111
  field: {
@@ -35,6 +35,16 @@ export interface AuthenticatedFetchOptions {
35
35
  /** Base headers for requests not tied to a configured endpoint. */
36
36
  baseHeaders?: Record<string, string>;
37
37
  }
38
+ /**
39
+ * Call the provider's `onUnauthorized()`, sharing one call between every
40
+ * request that gets a `401` while it is pending. A form whose autocomplete
41
+ * fields all look up their labels at once would otherwise refresh the token
42
+ * (or prompt for a login) once per field.
43
+ *
44
+ * @param authProvider - The provider whose session expired
45
+ * @returns Whether the provider refreshed its credentials
46
+ */
47
+ export declare function refreshAuth(authProvider: AuthProvider): Promise<boolean>;
38
48
  /**
39
49
  * Perform an authenticated fetch with consistent 401/403 handling.
40
50
  *
@@ -37,6 +37,28 @@ async function buildHeaders(init, opts) {
37
37
  }
38
38
  return headers;
39
39
  }
40
+ const pendingRefreshes = new WeakMap();
41
+ /**
42
+ * Call the provider's `onUnauthorized()`, sharing one call between every
43
+ * request that gets a `401` while it is pending. A form whose autocomplete
44
+ * fields all look up their labels at once would otherwise refresh the token
45
+ * (or prompt for a login) once per field.
46
+ *
47
+ * @param authProvider - The provider whose session expired
48
+ * @returns Whether the provider refreshed its credentials
49
+ */
50
+ export function refreshAuth(authProvider) {
51
+ if (!authProvider.onUnauthorized)
52
+ return Promise.resolve(false);
53
+ let pending = pendingRefreshes.get(authProvider);
54
+ if (!pending) {
55
+ pending = authProvider.onUnauthorized().finally(() => {
56
+ pendingRefreshes.delete(authProvider);
57
+ });
58
+ pendingRefreshes.set(authProvider, pending);
59
+ }
60
+ return pending;
61
+ }
40
62
  /**
41
63
  * Perform an authenticated fetch with consistent 401/403 handling.
42
64
  *
@@ -50,7 +72,7 @@ export async function authenticatedFetch(url, init = {}, opts = {}) {
50
72
  let response = await fetch(url, { ...init, headers });
51
73
  // 401 → let the provider refresh, then retry once with fresh headers.
52
74
  if (response.status === 401 && opts.authProvider?.onUnauthorized) {
53
- const refreshed = await opts.authProvider.onUnauthorized();
75
+ const refreshed = await refreshAuth(opts.authProvider);
54
76
  if (refreshed) {
55
77
  const retryHeaders = await buildHeaders(init, opts);
56
78
  response = await fetch(url, { ...init, headers: retryHeaders });
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "A drop-in visual workflow editor for any web application. You own the backend. You own the data. You own the orchestration.",
4
4
  "license": "MIT",
5
5
  "private": false,
6
- "version": "2.15.0",
6
+ "version": "2.15.1",
7
7
  "author": "Shibin Das (D34dMan)",
8
8
  "bugs": {
9
9
  "url": "https://github.com/flowdrop-io/flowdrop/issues"