@industream/flowmaker-flowbox-ui-components 1.0.6-poc.1 → 1.1.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.
@@ -0,0 +1,58 @@
1
+ /** Number of entries fetched per page. */
2
+ export const PAGE_SIZE = 100;
3
+ /** Query token that matches all entries (server-side wildcard). */
4
+ export const MATCH_ALL = '%';
5
+ /** Deduplicate entries by id, keeping the first occurrence and preserving order. */
6
+ export function deduplicateEntries(items) {
7
+ const seen = new Set();
8
+ const result = [];
9
+ for (const item of items) {
10
+ if (!seen.has(item.id)) {
11
+ seen.add(item.id);
12
+ result.push(item);
13
+ }
14
+ }
15
+ return result;
16
+ }
17
+ /** Append a freshly fetched page to the accumulated list, dropping duplicates. */
18
+ export function mergePage(existing, page) {
19
+ return deduplicateEntries([...existing, ...page]);
20
+ }
21
+ /** Trim a raw search input; an empty query becomes the match-all token. */
22
+ export function normalizeQuery(raw) {
23
+ const trimmed = raw.trim();
24
+ return trimmed === '' ? MATCH_ALL : trimmed;
25
+ }
26
+ /** True when the full match-all set is in memory (small catalog → client-side search). */
27
+ export function isAllLoaded(query, loadedCount, totalCount) {
28
+ return query === MATCH_ALL && loadedCount >= totalCount;
29
+ }
30
+ /** Whether more pages remain for the current query. */
31
+ export function hasMore(loadedCount, totalCount) {
32
+ return loadedCount < totalCount;
33
+ }
34
+ /** Number of not-yet-loaded entries for the current query (never negative). */
35
+ export function remainingCount(loadedCount, totalCount) {
36
+ return Math.max(0, totalCount - loadedCount);
37
+ }
38
+ /** Upsert every fetched entry into the selected-entry metadata cache (mutates and returns it). */
39
+ export function upsertSelectedCache(cache, items) {
40
+ for (const item of items) {
41
+ cache.set(item.id, item);
42
+ }
43
+ return cache;
44
+ }
45
+ /**
46
+ * Resolve the selected entries for display: prefer the currently loaded window,
47
+ * fall back to the cache, in the order of `selectedIds`. Ids absent from both are skipped.
48
+ */
49
+ export function resolveSelected(entries, cache, selectedIds) {
50
+ const windowById = new Map(entries.map(e => [e.id, e]));
51
+ const result = [];
52
+ for (const id of selectedIds) {
53
+ const found = windowById.get(id) ?? cache.get(id);
54
+ if (found)
55
+ result.push(found);
56
+ }
57
+ return result;
58
+ }
@@ -0,0 +1,61 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { PAGE_SIZE, MATCH_ALL, deduplicateEntries, mergePage, normalizeQuery, isAllLoaded, hasMore, remainingCount, upsertSelectedCache, resolveSelected } from './picker-pagination';
3
+ const entry = (id, name = id) => ({ id, name });
4
+ describe('constants', () => {
5
+ it('exposes the page size and match-all token', () => {
6
+ expect(PAGE_SIZE).toBe(100);
7
+ expect(MATCH_ALL).toBe('%');
8
+ });
9
+ });
10
+ describe('deduplicateEntries', () => {
11
+ it('keeps first occurrence by id and preserves order', () => {
12
+ const result = deduplicateEntries([entry('a'), entry('b'), entry('a')]);
13
+ expect(result.map(e => e.id)).toEqual(['a', 'b']);
14
+ });
15
+ });
16
+ describe('mergePage', () => {
17
+ it('appends a new page and drops duplicates against existing', () => {
18
+ const result = mergePage([entry('a'), entry('b')], [entry('b'), entry('c')]);
19
+ expect(result.map(e => e.id)).toEqual(['a', 'b', 'c']);
20
+ });
21
+ });
22
+ describe('normalizeQuery', () => {
23
+ it('trims and maps empty input to the match-all token', () => {
24
+ expect(normalizeQuery(' ')).toBe(MATCH_ALL);
25
+ expect(normalizeQuery('')).toBe(MATCH_ALL);
26
+ });
27
+ it('trims a real query', () => {
28
+ expect(normalizeQuery(' temp ')).toBe('temp');
29
+ });
30
+ });
31
+ describe('isAllLoaded', () => {
32
+ it('is true only for match-all with every item loaded', () => {
33
+ expect(isAllLoaded(MATCH_ALL, 50, 50)).toBe(true);
34
+ expect(isAllLoaded(MATCH_ALL, 50, 120)).toBe(false);
35
+ expect(isAllLoaded('temp', 50, 50)).toBe(false);
36
+ });
37
+ });
38
+ describe('hasMore / remainingCount', () => {
39
+ it('reports remaining pages relative to total', () => {
40
+ expect(hasMore(100, 350)).toBe(true);
41
+ expect(hasMore(350, 350)).toBe(false);
42
+ expect(remainingCount(100, 350)).toBe(250);
43
+ expect(remainingCount(350, 350)).toBe(0);
44
+ expect(remainingCount(400, 350)).toBe(0);
45
+ });
46
+ });
47
+ describe('selected cache', () => {
48
+ it('upserts fetched items by id', () => {
49
+ const cache = upsertSelectedCache(new Map(), [entry('a'), entry('b')]);
50
+ upsertSelectedCache(cache, [entry('b', 'renamed')]);
51
+ expect(cache.get('b')?.name).toBe('renamed');
52
+ expect(cache.size).toBe(2);
53
+ });
54
+ it('resolves selected entries from window first, cache as fallback, in selection order', () => {
55
+ const cache = upsertSelectedCache(new Map(), [entry('x'), entry('y')]);
56
+ const window = [entry('y', 'in-window')];
57
+ const result = resolveSelected(window, cache, ['x', 'y']);
58
+ expect(result.map(e => e.id)).toEqual(['x', 'y']);
59
+ expect(result.find(e => e.id === 'y')?.name).toBe('in-window');
60
+ });
61
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@industream/flowmaker-flowbox-ui-components",
3
- "version": "1.0.6-poc.1",
3
+ "version": "1.1.1",
4
4
  "description": "Reusable Svelte components for FlowMaker FlowBox UI",
5
5
  "type": "module",
6
6
  "svelte": "./dist/index.js",
@@ -40,11 +40,12 @@
40
40
  ],
41
41
  "scripts": {
42
42
  "build": "svelte-package --input src",
43
- "dev": "vite --config vite.dev.config.ts"
43
+ "test": "vitest",
44
+ "test:run": "vitest run"
44
45
  },
45
46
  "peerDependencies": {
46
47
  "svelte": "^5.0.0",
47
- "@industream/datacatalog-client": "1.9.2"
48
+ "@industream/datacatalog-client": "^1.9.1"
48
49
  },
49
50
  "devDependencies": {
50
51
  "@industream/datacatalog-client": "1.9.2",
@@ -52,7 +53,8 @@
52
53
  "vite": "^6.0.0",
53
54
  "@sveltejs/vite-plugin-svelte": "^5.0.0",
54
55
  "@sveltejs/package": "^2.0.0",
55
- "typescript": "^5.0.0"
56
+ "typescript": "^5.0.0",
57
+ "vitest": "^2.1.0"
56
58
  },
57
59
  "publishConfig": {
58
60
  "access": "public"
@@ -2,37 +2,46 @@
2
2
  /**
3
3
  * DCCatalogEntryPicker — DataCatalog entry picker with configurable columns.
4
4
  *
5
- * Composes TagBrowser (searchable table with multi-select) and SelectedTags
6
- * (collapsible summary with remove). Owns the DataCatalog fetch lifecycle.
5
+ * Composes TagBrowser (searchable, paginated table with multi-select) and
6
+ * SelectedTags (collapsible summary with remove). Owns the DataCatalog fetch
7
+ * lifecycle, pagination state, and the selected-entry metadata cache.
7
8
  *
8
- * Uses `client.catalogEntries.search()` (v1.4.0+) for both initial load and
9
- * server-side search. Filters by `sourceConnections` to scope entries.
10
- *
11
- * Load strategy:
12
- * 1. Initial load fetches up to MAX_ENTRIES + 1 items.
13
- * 2. If MAX_ENTRIES client mode (client-side search in TagBrowser).
14
- * 3. If > MAX_ENTRIES → server mode (TagBrowser search triggers server search
15
- * with 1s debounce, AbortSignal cancels in-flight requests).
9
+ * Strategy (see docs/superpowers/specs/2026-06-30-tag-picker-lazy-pagination-design.md):
10
+ * - Always load page 1 on open — never a blank table.
11
+ * - Lazy "load more" pagination via offset; totalCount drives the counter and end.
12
+ * - Search: client-side instant when the whole catalog is loaded (small catalogs),
13
+ * debounced server search otherwise.
14
+ * - Selected entries are cached independently of the loaded window so their
15
+ * metadata always renders.
16
16
  *
17
17
  * @prop dcApiUrl — DataCatalog API base URL
18
18
  * @prop sourceConnectionId — Filters catalog entries by source connection
19
19
  * @prop selectedIds — (bindable) Array of selected CatalogEntry IDs
20
20
  * @prop entries — (bindable) Loaded catalog entries (exposed for parent access)
21
- * @prop columns — Column keys for the browse table (default: name, dataType, labels)
22
- * @prop selectedColumnsDisplay — Column keys for the selected tags panel (default: name, dataType, labels)
21
+ * @prop columns — Column keys for the browse table
22
+ * @prop selectedColumnsDisplay — Column keys for the selected tags panel
23
23
  * @prop emptyMessage — Message when no entries match the source connection
24
24
  * @prop onSelectionChange — Called when selection changes (receives full selectedIds array)
25
25
  * @prop onRemove — Called when a single entry is removed from the selection
26
26
  */
27
- import { untrack } from 'svelte';
28
27
  import { DataCatalogClient } from '@industream/datacatalog-client';
29
28
  import type { CatalogEntry } from '@industream/datacatalog-client/dto';
30
29
  import { DEFAULT_COLUMNS, DEFAULT_SELECTED_COLUMNS_DISPLAY } from './picker-column-helpers';
30
+ import {
31
+ PAGE_SIZE,
32
+ MATCH_ALL,
33
+ mergePage,
34
+ deduplicateEntries,
35
+ normalizeQuery,
36
+ isAllLoaded,
37
+ hasMore,
38
+ remainingCount,
39
+ upsertSelectedCache,
40
+ resolveSelected
41
+ } from './picker-pagination';
31
42
  import TagBrowser from './TagBrowser.svelte';
32
43
  import SelectedTags from './SelectedTags.svelte';
33
44
 
34
- const MAX_ENTRIES = 100;
35
-
36
45
  interface Props {
37
46
  dcApiUrl?: string;
38
47
  sourceConnectionId?: string;
@@ -58,33 +67,46 @@
58
67
  }: Props = $props();
59
68
 
60
69
  let loading = $state(false);
70
+ let loadingMore = $state(false);
61
71
  let searching = $state(false);
62
72
  let error = $state('');
63
- let tooMany = $state(false);
73
+ let loadMoreError = $state('');
74
+ let totalCount = $state(0);
75
+ let currentQuery = $state(MATCH_ALL);
76
+ let offset = $state(0);
64
77
 
65
- /** Abort controller for cancelling in-flight search requests */
66
- let searchAbort: AbortController | null = null;
67
-
68
- /** Cached client instance recreated when dcApiUrl changes */
69
- let client: DataCatalogClient | null = null;
70
- let clientUrl = '';
78
+ /**
79
+ * Metadata for selected tags, kept across reloads/searches so SelectedTags always
80
+ * renders. Invariant: every mutation of this Map is paired with an `entries`
81
+ * reassignment, so the `selectedEntries` derived (which reads both) re-runs and picks
82
+ * up the change. Do NOT upsert the cache without also reassigning `entries`.
83
+ */
84
+ let selectedCache = new Map<string, CatalogEntry>();
71
85
 
72
86
  /**
73
- * Deduplicate entries by id keep only the first occurrence.
87
+ * Best-effort total for the current query. The server's search response MAY omit
88
+ * `totalCount`; when it does, we must not silently cap pagination at one page.
89
+ * Fall back to: a full page → "at least one more page" (loaded + PAGE_SIZE) so the
90
+ * load-more affordance stays available; a short page → exactly what is loaded (the end).
74
91
  */
75
- function deduplicateEntries(items: CatalogEntry[]): CatalogEntry[] {
76
- const seen = new Set<string>();
77
- const result: CatalogEntry[] = [];
78
- for (const item of items) {
79
- const id = item.id;
80
- if (!seen.has(id)) {
81
- seen.add(id);
82
- result.push(item);
83
- }
84
- }
85
- return result;
92
+ function estimateTotal(reported: number | undefined, loadedCount: number, lastPageLen: number): number {
93
+ if (reported != null) return reported;
94
+ return lastPageLen < PAGE_SIZE ? loadedCount : loadedCount + PAGE_SIZE;
86
95
  }
87
96
 
97
+ /** Abort controller for cancelling in-flight requests. */
98
+ let fetchAbort: AbortController | null = null;
99
+
100
+ /** Cached client instance — recreated when dcApiUrl changes. */
101
+ let client: DataCatalogClient | null = null;
102
+ let clientUrl = '';
103
+
104
+ /** Whether search runs server-side (large catalog) or client-side (everything loaded). */
105
+ const serverSearch = $derived(!isAllLoaded(MATCH_ALL, entries.length, totalCount) || currentQuery !== MATCH_ALL);
106
+
107
+ /** Resolved entries for the selected-tags panel: window first, cache fallback. */
108
+ const selectedEntries = $derived(resolveSelected(entries, selectedCache, selectedIds));
109
+
88
110
  function getClient(apiUrl: string): DataCatalogClient {
89
111
  if (client && clientUrl === apiUrl) return client;
90
112
  client = new DataCatalogClient({ baseUrl: apiUrl });
@@ -96,135 +118,124 @@
96
118
  if (dcApiUrl) {
97
119
  loadInitial(dcApiUrl, sourceConnectionId);
98
120
  } else {
121
+ fetchAbort?.abort();
99
122
  entries = [];
123
+ totalCount = 0;
100
124
  error = '';
101
- tooMany = false;
102
125
  }
103
126
  });
104
127
 
105
- /**
106
- * Initial load fetch MAX_ENTRIES + 1 to detect overflow.
107
- * If ≤ MAX_ENTRIES items, stay in client mode.
108
- * If more, switch to server search mode.
109
- */
110
- async function loadInitial(apiUrl: string, connId?: string) {
111
- // Cancel any in-flight search
112
- searchAbort?.abort();
113
- searchAbort = null;
128
+ /** (Re)load page 1 for the match-all query. Never leaves the table blank on success. */
129
+ async function loadInitial(apiUrl: string, connId: string = '') {
130
+ fetchAbort?.abort();
131
+ const abort = new AbortController();
132
+ fetchAbort = abort;
114
133
 
115
134
  loading = true;
116
135
  error = '';
117
- tooMany = false;
136
+ loadMoreError = '';
137
+ currentQuery = MATCH_ALL;
138
+ offset = 0;
118
139
  entries = [];
140
+ totalCount = 0;
119
141
 
120
142
  try {
121
143
  const dc = getClient(apiUrl);
122
- const result = await dc.catalogEntries.search('%', {
144
+ const result = await dc.catalogEntries.search(MATCH_ALL, {
123
145
  sourceConnectionIds: connId ? [connId] : [],
124
- limit: MAX_ENTRIES + 1
125
- });
126
- const items = result.items ?? [];
127
- const uniqueItems = deduplicateEntries(items);
128
-
129
- if (uniqueItems.length > MAX_ENTRIES) {
130
- // Too many for client-side filtering → server-search mode. Still show the
131
- // first MAX_ENTRIES as a browsable PREVIEW (with a "not all displayed"
132
- // warning in TagBrowser) instead of a blank "type to search" screen.
133
- tooMany = true;
134
- entries = uniqueItems.slice(0, MAX_ENTRIES);
135
- } else {
136
- tooMany = false;
137
- entries = uniqueItems;
138
- }
146
+ limit: PAGE_SIZE,
147
+ offset: 0
148
+ }, abort.signal);
149
+ if (abort.signal.aborted) return;
150
+ const items = deduplicateEntries(result.items ?? []);
151
+ entries = items;
152
+ totalCount = estimateTotal(result.totalCount, items.length, items.length);
153
+ offset = items.length;
154
+ upsertSelectedCache(selectedCache, items);
139
155
  } catch (err: any) {
140
- error = err.message ?? 'Failed to load catalog entries';
156
+ if (abort.signal.aborted) return;
157
+ error = err?.message ?? 'Failed to load catalog entries';
141
158
  entries = [];
142
159
  } finally {
143
- loading = false;
160
+ if (!abort.signal.aborted) loading = false;
144
161
  }
145
162
  }
146
163
 
147
- /**
148
- * Server-side search — called by TagBrowser when in server mode (tooMany).
149
- * Cancels previous in-flight request via AbortSignal.
150
- */
151
- function handleServerSearch(query: string) {
164
+ /** Server-side search (large catalogs). Resets pagination for the new query. */
165
+ function handleServerSearch(rawQuery: string) {
152
166
  if (!dcApiUrl) return;
153
-
154
- // Cancel previous in-flight search
155
- searchAbort?.abort();
156
-
157
- if (!query) {
158
- // Empty query in too-many mode → restore the first-N preview.
159
- searching = false;
160
- loadInitial(dcApiUrl, sourceConnectionId);
161
- return;
162
- }
163
-
167
+ fetchAbort?.abort();
164
168
  const abort = new AbortController();
165
- searchAbort = abort;
169
+ fetchAbort = abort;
170
+
171
+ const query = normalizeQuery(rawQuery);
172
+ currentQuery = query;
173
+ offset = 0;
174
+ entries = [];
175
+ totalCount = 0;
176
+ error = '';
177
+ loadMoreError = '';
166
178
  searching = true;
167
179
 
168
180
  const dc = getClient(dcApiUrl);
169
181
  dc.catalogEntries.search(query, {
170
182
  sourceConnectionIds: sourceConnectionId ? [sourceConnectionId] : [],
171
- limit: MAX_ENTRIES
183
+ limit: PAGE_SIZE,
184
+ offset: 0
172
185
  }, abort.signal)
173
186
  .then((result) => {
174
187
  if (abort.signal.aborted) return;
175
- const items = result.items ?? [];
176
- entries = deduplicateEntries(items);
188
+ const items = deduplicateEntries(result.items ?? []);
189
+ entries = items;
190
+ totalCount = estimateTotal(result.totalCount, items.length, items.length);
191
+ offset = items.length;
192
+ upsertSelectedCache(selectedCache, items);
177
193
  searching = false;
178
194
  })
179
- .catch((err) => {
195
+ .catch((err: any) => {
180
196
  if (abort.signal.aborted) return;
181
- error = err.message ?? 'Search failed';
197
+ error = err?.message ?? 'Search failed';
182
198
  entries = [];
183
199
  searching = false;
184
200
  });
185
201
  }
186
202
 
187
- /**
188
- * Full details of the SELECTED entries, fetched by ID — decoupled from the browse
189
- * list (`entries`), which is empty in `tooMany` mode and only holds the current
190
- * page/search otherwise. Without this, the SelectedTags panel can only render
191
- * selected tags that happen to be in `entries` → on large sources it shows
192
- * "No tags selected" / loses the selection visually despite a correct count.
193
- */
194
- let selectedEntries = $state<CatalogEntry[]>([]);
203
+ /** Append the next page for the current query. No-op when everything is loaded. */
204
+ function handleLoadMore() {
205
+ if (!dcApiUrl || loadingMore || loading || searching) return;
206
+ if (!hasMore(entries.length, totalCount)) return;
195
207
 
196
- $effect(() => {
197
- const ids = [...selectedIds]; // reactive dependency
198
- const url = dcApiUrl; // reactive dependency
199
-
200
- if (!url || ids.length === 0) {
201
- selectedEntries = [];
202
- return;
203
- }
204
-
205
- // Reuse already-resolved entries that are still selected; fetch only the missing.
206
- const idSet = new Set(ids);
207
- const current = untrack(() => selectedEntries);
208
- const keep = current.filter((e) => idSet.has(e.id));
209
- const have = new Set(keep.map((e) => e.id));
210
- const missing = ids.filter((id) => !have.has(id));
208
+ fetchAbort?.abort();
209
+ const abort = new AbortController();
210
+ fetchAbort = abort;
211
211
 
212
- if (missing.length === 0) {
213
- if (keep.length !== current.length) selectedEntries = keep;
214
- return;
215
- }
212
+ loadingMore = true;
213
+ loadMoreError = '';
214
+ const startOffset = offset;
216
215
 
217
- // get() auto-switches to POST /catalog-entries/query for large id lists (URI-safe).
218
- getClient(url).catalogEntries
219
- .get({ ids: missing })
220
- .then((res) => {
221
- const latest = new Set(untrack(() => selectedIds));
222
- selectedEntries = [...keep, ...(res.items ?? [])].filter((e) => latest.has(e.id));
216
+ const dc = getClient(dcApiUrl);
217
+ dc.catalogEntries.search(currentQuery, {
218
+ sourceConnectionIds: sourceConnectionId ? [sourceConnectionId] : [],
219
+ limit: PAGE_SIZE,
220
+ offset: startOffset
221
+ }, abort.signal)
222
+ .then((result) => {
223
+ if (abort.signal.aborted) return;
224
+ const items = result.items ?? [];
225
+ entries = mergePage(entries, items);
226
+ totalCount = estimateTotal(result.totalCount, entries.length, items.length);
227
+ offset = entries.length;
228
+ upsertSelectedCache(selectedCache, items);
229
+ loadingMore = false;
223
230
  })
224
- .catch(() => {
225
- // Keep what we have; SelectedTags falls back to the browse list below.
231
+ .catch((err: any) => {
232
+ if (abort.signal.aborted) return;
233
+ loadMoreError = err?.message ?? 'Failed to load more entries';
234
+ loadingMore = false;
226
235
  });
227
- });
236
+ }
237
+
238
+ const remaining = $derived(remainingCount(entries.length, totalCount));
228
239
  </script>
229
240
 
230
241
  <TagBrowser
@@ -232,17 +243,22 @@
232
243
  bind:selectedIds
233
244
  {columns}
234
245
  {loading}
246
+ {loadingMore}
235
247
  {error}
248
+ {loadMoreError}
236
249
  {emptyMessage}
237
- {onSelectionChange}
238
- onSearch={tooMany ? handleServerSearch : null}
250
+ {totalCount}
251
+ {remaining}
252
+ serverSearch={serverSearch}
239
253
  {searching}
240
- {tooMany}
254
+ {onSelectionChange}
255
+ onSearch={handleServerSearch}
256
+ onLoadMore={handleLoadMore}
241
257
  />
242
258
 
243
259
  {#if selectedIds.length > 0}
244
260
  <SelectedTags
245
- entries={selectedEntries.length > 0 ? selectedEntries : entries}
261
+ entries={selectedEntries}
246
262
  bind:selectedIds
247
263
  columns={selectedColumnsDisplay}
248
264
  {onRemove}