@asteby/metacore-runtime-react 53.7.0 → 53.8.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  3. package/dist/action-modal-dispatcher.js +3 -1
  4. package/dist/api-context.d.ts.map +1 -1
  5. package/dist/api-context.js +15 -0
  6. package/dist/cache-scope.d.ts +52 -0
  7. package/dist/cache-scope.d.ts.map +1 -0
  8. package/dist/cache-scope.js +200 -0
  9. package/dist/capability-providers/index.d.ts +4 -0
  10. package/dist/capability-providers/index.d.ts.map +1 -0
  11. package/dist/capability-providers/index.js +3 -0
  12. package/dist/capability-providers/model.d.ts +201 -0
  13. package/dist/capability-providers/model.d.ts.map +1 -0
  14. package/dist/capability-providers/model.js +293 -0
  15. package/dist/capability-providers/provider-sortable-list.d.ts +86 -0
  16. package/dist/capability-providers/provider-sortable-list.d.ts.map +1 -0
  17. package/dist/capability-providers/provider-sortable-list.js +263 -0
  18. package/dist/capability-providers/reorder.d.ts +10 -0
  19. package/dist/capability-providers/reorder.d.ts.map +1 -0
  20. package/dist/capability-providers/reorder.js +31 -0
  21. package/dist/dashboard-types.d.ts +2 -4
  22. package/dist/dashboard-types.d.ts.map +1 -1
  23. package/dist/dynamic-kanban.d.ts.map +1 -1
  24. package/dist/dynamic-kanban.js +9 -4
  25. package/dist/dynamic-relation.d.ts.map +1 -1
  26. package/dist/dynamic-relation.js +5 -2
  27. package/dist/dynamic-table.d.ts +2 -0
  28. package/dist/dynamic-table.d.ts.map +1 -1
  29. package/dist/dynamic-table.js +40 -6
  30. package/dist/dynamic-view.d.ts.map +1 -1
  31. package/dist/dynamic-view.js +3 -1
  32. package/dist/index.d.ts +4 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +5 -1
  35. package/dist/metadata-cache.d.ts +22 -2
  36. package/dist/metadata-cache.d.ts.map +1 -1
  37. package/dist/metadata-cache.js +73 -13
  38. package/dist/query-batch.d.ts +12 -0
  39. package/dist/query-batch.d.ts.map +1 -1
  40. package/dist/query-batch.js +70 -29
  41. package/dist/use-option-ids.d.ts.map +1 -1
  42. package/dist/use-option-ids.js +3 -1
  43. package/dist/use-options-resolver.d.ts +4 -1
  44. package/dist/use-options-resolver.d.ts.map +1 -1
  45. package/dist/use-options-resolver.js +27 -16
  46. package/dist/widgets/charts.d.ts.map +1 -1
  47. package/dist/widgets/charts.js +11 -43
  48. package/dist/widgets/widget-format.d.ts +1 -41
  49. package/dist/widgets/widget-format.d.ts.map +1 -1
  50. package/dist/widgets/widget-format.js +3 -138
  51. package/package.json +4 -4
  52. package/src/__tests__/charts-reexport.test.ts +30 -0
  53. package/src/action-modal-dispatcher.tsx +3 -1
  54. package/src/api-context.tsx +14 -0
  55. package/src/cache-scope-inflight.test.ts +369 -0
  56. package/src/cache-scope.test.ts +234 -0
  57. package/src/cache-scope.ts +202 -0
  58. package/src/capability-providers/index.ts +46 -0
  59. package/src/capability-providers/model.test.ts +186 -0
  60. package/src/capability-providers/model.ts +464 -0
  61. package/src/capability-providers/provider-sortable-list.test.tsx +284 -0
  62. package/src/capability-providers/provider-sortable-list.tsx +452 -0
  63. package/src/capability-providers/reorder.ts +29 -0
  64. package/src/dashboard-types.ts +2 -11
  65. package/src/dynamic-kanban.tsx +9 -4
  66. package/src/dynamic-relation.tsx +5 -2
  67. package/src/dynamic-table.tsx +41 -10
  68. package/src/dynamic-view.tsx +3 -1
  69. package/src/index.ts +13 -0
  70. package/src/metadata-cache.ts +85 -15
  71. package/src/query-batch.ts +71 -30
  72. package/src/use-option-ids.ts +3 -1
  73. package/src/use-options-resolver.ts +28 -15
  74. package/src/widgets/charts.tsx +26 -189
  75. package/src/widgets/widget-format.ts +14 -181
  76. package/vitest.setup.ts +16 -0
@@ -0,0 +1,293 @@
1
+ // Pure model of GET /api/capabilities + GET /api/markets, kept free of
2
+ // runtime imports so it is unit-testable without the app's api client.
3
+ //
4
+ // A host screen groups the technical capability contracts
5
+ // (e.g. commerce.<domain>.<operation>) by business DOMAIN and lets the admin
6
+ // choose ONE provider per domain and market; the choice is applied to every
7
+ // contract of the bundle the provider offers. The resolution below mirrors the
8
+ // kernel's capability.Select v1 (market selection, org default, only eligible
9
+ // provider). It does NOT model Select v2 (per-market priority and provider
10
+ // state), which is pending the kernel's F2 release: until then the order
11
+ // produced by ProviderSortableList is a display/intent order this model does
12
+ // not consume, so a host must not present it as what dispatch will do.
13
+ /** Pick a locale's text: exact, base language, es, en, any. */
14
+ export function pickText(text, locale) {
15
+ if (!text)
16
+ return '';
17
+ const l = (locale ?? '').trim();
18
+ if (l && text[l])
19
+ return text[l];
20
+ const baseLang = l.split(/[-_]/)[0]?.toLowerCase();
21
+ if (baseLang && text[baseLang])
22
+ return text[baseLang];
23
+ for (const k of ['es', 'en', 'default'])
24
+ if (text[k])
25
+ return text[k];
26
+ return Object.values(text).find(Boolean) ?? '';
27
+ }
28
+ /** "commerce.payments.session" → "commerce.payments" (fallback when the API has no domain). */
29
+ export function domainOf(key) {
30
+ const parts = key.split('.');
31
+ return parts.length > 2 ? parts.slice(0, 2).join('.') : key;
32
+ }
33
+ /** Readable title from a key segment, never the dotted id ("loyalty" → "Loyalty"). */
34
+ export function humanizeSegment(key) {
35
+ const seg = key.split('.').pop() ?? key;
36
+ return seg.replace(/[_-]+/g, ' ').replace(/^\w/, (m) => m.toUpperCase());
37
+ }
38
+ export function servesMarket(p, m) {
39
+ if (!m)
40
+ return true;
41
+ const pc = p.countries ?? [];
42
+ const mc = m.countries ?? [];
43
+ if (pc.length === 0 || mc.length === 0)
44
+ return true;
45
+ return pc.some((c) => mc.some((x) => x.toUpperCase() === c.toUpperCase()));
46
+ }
47
+ /**
48
+ * Which provider answers capability `c` in market `m` (null = organization
49
+ * level). Mirrors kernel capability.Select v1 (today's rule): market
50
+ * selection, then org default among eligible, then the only eligible
51
+ * provider. Select v2 (priority and provider state) is pending kernel F2 and
52
+ * is not modeled here.
53
+ */
54
+ export function resolveCapability(c, m) {
55
+ const installed = c.providers.filter((p) => p.installed);
56
+ const selected = m ? installed.filter((p) => (p.markets ?? []).includes(m.code)) : [];
57
+ const eligible = installed.filter((p) => servesMarket(p, m));
58
+ const eligibleKeys = eligible.map((p) => p.addon_key);
59
+ if (c.fanout) {
60
+ const answering = selected.length ? selected : eligible;
61
+ if (answering.length === 0)
62
+ return { key: c.key, reason: 'none', eligible: eligibleKeys };
63
+ return { key: c.key, reason: 'fanout', addons: answering.map((p) => p.addon_key), eligible: eligibleKeys };
64
+ }
65
+ if (selected.length === 1)
66
+ return { key: c.key, addon: selected[0].addon_key, reason: 'selected', eligible: eligibleKeys };
67
+ if (selected.length > 1)
68
+ return { key: c.key, reason: 'ambiguous', eligible: eligibleKeys };
69
+ const defaults = eligible.filter((p) => p.default);
70
+ if (defaults.length === 1)
71
+ return { key: c.key, addon: defaults[0].addon_key, reason: 'default', eligible: eligibleKeys };
72
+ if (defaults.length > 1)
73
+ return { key: c.key, reason: 'ambiguous', eligible: eligibleKeys };
74
+ if (eligible.length === 1)
75
+ return { key: c.key, addon: eligible[0].addon_key, reason: 'only', eligible: eligibleKeys };
76
+ if (eligible.length === 0)
77
+ return { key: c.key, reason: 'none', eligible: eligibleKeys };
78
+ return { key: c.key, reason: 'ambiguous', eligible: eligibleKeys };
79
+ }
80
+ const isReady = (info) => !info?.connection || info.connection.state !== 'missing_credentials';
81
+ export function recommendProvider(candidates, providers) {
82
+ if (candidates.length === 0)
83
+ return undefined;
84
+ if (candidates.length === 1)
85
+ return candidates[0];
86
+ const connected = candidates.filter((a) => providers?.[a]?.connection?.state === 'connected');
87
+ if (connected.length === 1)
88
+ return connected[0];
89
+ const ready = candidates.filter((a) => isReady(providers?.[a]));
90
+ if (ready.length === 1)
91
+ return ready[0];
92
+ return undefined;
93
+ }
94
+ function buildCell(caps, m, provides, providers) {
95
+ const resolutions = caps.map((c) => resolveCapability(c, m));
96
+ const chosen = caps.filter((c) => !c.fanout);
97
+ const single = resolutions.filter((_, i) => !caps[i].fanout);
98
+ const inUse = [...new Set(single.map((r) => r.addon).filter((a) => !!a))];
99
+ const checkoutGaps = caps
100
+ .filter((c, i) => c.checkout && (resolutions[i].reason === 'none' || resolutions[i].reason === 'ambiguous'))
101
+ .map((c) => c.key);
102
+ // Candidates: providers that serve this market for at least one
103
+ // choosable contract of the domain.
104
+ const candidates = Object.keys(provides)
105
+ .filter((a) => chosen.some((c) => c.providers.some((p) => p.addon_key === a && p.installed && servesMarket(p, m))))
106
+ .sort();
107
+ const blocked = Object.keys(provides)
108
+ .filter((a) => !candidates.includes(a) && chosen.length > 0)
109
+ .sort();
110
+ const base = { market: m, resolutions, candidates, blocked, checkoutGaps };
111
+ if (chosen.length === 0) {
112
+ const answering = [...new Set(resolutions.flatMap((r) => r.addons ?? []))].sort();
113
+ return { ...base, status: answering.length ? 'fanout' : 'no_provider', providers: answering };
114
+ }
115
+ if (single.some((r) => r.reason === 'ambiguous')) {
116
+ return { ...base, status: 'needs_choice', providers: inUse, recommended: recommendProvider(candidates, providers) };
117
+ }
118
+ if (inUse.length > 1)
119
+ return { ...base, status: 'mixed', providers: inUse };
120
+ if (inUse.length === 0)
121
+ return { ...base, status: 'no_provider', providers: [] };
122
+ return { ...base, status: 'ok', provider: inUse[0], providers: inUse };
123
+ }
124
+ /**
125
+ * Group the usable capabilities (at least one installed provider) by domain
126
+ * and resolve each domain per market. With no active market the single
127
+ * column is the organization level (market null).
128
+ */
129
+ export function groupByDomain(payload, markets) {
130
+ const usable = payload.data.filter((c) => c.providers.some((p) => p.installed));
131
+ const domainMeta = new Map((payload.domains ?? []).map((d) => [d.key, d]));
132
+ const byDomain = new Map();
133
+ for (const c of usable) {
134
+ const d = c.domain || domainOf(c.key);
135
+ byDomain.set(d, [...(byDomain.get(d) ?? []), c]);
136
+ }
137
+ const columns = activeMarkets(markets).length ? activeMarkets(markets) : [null];
138
+ const groups = [];
139
+ for (const [key, caps] of byDomain) {
140
+ const provides = {};
141
+ for (const c of caps)
142
+ for (const p of c.providers)
143
+ if (p.installed)
144
+ provides[p.addon_key] = [...(provides[p.addon_key] ?? []), c.key];
145
+ groups.push({
146
+ key,
147
+ domain: domainMeta.get(key) ?? { key, order: 1000 },
148
+ capabilities: caps,
149
+ providers: Object.keys(provides).sort(),
150
+ provides,
151
+ cells: columns.map((m) => buildCell(caps, m, provides, payload.providers)),
152
+ fanoutOnly: caps.every((c) => c.fanout),
153
+ });
154
+ }
155
+ return groups.sort((a, b) => (a.domain.order ?? 1000) - (b.domain.order ?? 1000) || a.key.localeCompare(b.key));
156
+ }
157
+ /** Active markets, default first, then by name. */
158
+ export function activeMarkets(markets) {
159
+ return markets
160
+ .filter((m) => m.active !== false)
161
+ .sort((a, b) => Number(!!b.is_default) - Number(!!a.is_default) || (a.name ?? a.code).localeCompare(b.name ?? b.code));
162
+ }
163
+ /**
164
+ * The selections to send when `addon` becomes the provider of the whole
165
+ * domain in market m: every choosable contract of the domain the addon
166
+ * provides and serves there. Contracts it does not provide are left as they
167
+ * are.
168
+ */
169
+ export function bundleSelections(group, addon, m) {
170
+ const out = {};
171
+ for (const c of group.capabilities) {
172
+ if (c.fanout)
173
+ continue;
174
+ const p = c.providers.find((x) => x.addon_key === addon && x.installed);
175
+ if (p && servesMarket(p, m))
176
+ out[c.key] = addon;
177
+ }
178
+ return out;
179
+ }
180
+ /**
181
+ * What is stored today for these keys in market m ("" = nothing chosen), so
182
+ * the host can send it back as is (undo).
183
+ */
184
+ export function storedSelections(group, keys, m) {
185
+ const out = {};
186
+ for (const k of keys) {
187
+ const c = group.capabilities.find((x) => x.key === k);
188
+ const hit = c?.providers.find((p) => p.installed && (m ? (p.markets ?? []).includes(m.code) : p.default));
189
+ out[k] = hit?.addon_key ?? '';
190
+ }
191
+ return out;
192
+ }
193
+ /** Why `addon` cannot be the domain provider in market m (null = it can). */
194
+ export function choiceBlock(group, addon, m) {
195
+ const offers = group.capabilities.filter((c) => !c.fanout && c.providers.some((p) => p.addon_key === addon && p.installed));
196
+ if (offers.length === 0)
197
+ return { addon, reason: 'not_provided' };
198
+ const serving = offers.filter((c) => servesMarket(c.providers.find((p) => p.addon_key === addon), m));
199
+ if (serving.length === 0) {
200
+ const countries = offers[0].providers.find((p) => p.addon_key === addon)?.countries;
201
+ return { addon, reason: 'market', countries };
202
+ }
203
+ return null;
204
+ }
205
+ /** Markets whose checkout lacks a provider for a contract it needs. */
206
+ export function checkoutBlockers(groups) {
207
+ const out = [];
208
+ for (const g of groups)
209
+ for (const cell of g.cells)
210
+ if (cell.checkoutGaps.length)
211
+ out.push({ group: g, cell });
212
+ return out;
213
+ }
214
+ /** Impact preview of making `addon` the provider of the domain in market m. */
215
+ export function changeImpact(group, addon, m) {
216
+ const keys = Object.keys(bundleSelections(group, addon, m));
217
+ const idx = group.cells.findIndex((c) => (c.market?.code ?? '') === (m?.code ?? ''));
218
+ const res = idx >= 0 ? group.cells[idx].resolutions.filter((r) => keys.includes(r.key)) : [];
219
+ const from = [...new Set(res.map((r) => r.addon).filter((a) => !!a))];
220
+ const sameProvider = res.length > 0 && res.every((r) => r.addon === addon);
221
+ const stored = storedSelections(group, keys, m);
222
+ const alreadyStored = keys.length > 0 && keys.every((k) => stored[k] === addon);
223
+ return { keys, from, sameProvider, alreadyStored, saveable: keys.length > 0 && !alreadyStored };
224
+ }
225
+ // Only capabilities the org can actually use (at least one provider
226
+ // installed), mirroring the host's choice: the marked default, else the only
227
+ // installed provider; several without a default is ambiguous.
228
+ export function usableCapabilities(data) {
229
+ return data
230
+ .map((c) => {
231
+ const installed = c.providers.filter((p) => p.installed);
232
+ const current = installed.find((p) => p.default) ??
233
+ (installed.length === 1 ? installed[0] : undefined);
234
+ return {
235
+ ...c,
236
+ installed,
237
+ current,
238
+ ambiguous: installed.length > 1 && !current,
239
+ };
240
+ })
241
+ .filter((c) => c.installed.length > 0);
242
+ }
243
+ /**
244
+ * Is there anything to decide on the provider-choice screen? Only when the
245
+ * organization sells in more than one market, or some function can be served
246
+ * by more than one installed provider. With a single market and one provider
247
+ * per function the screen would only repeat what is already installed
248
+ * («MX» under «MX»), so the entry stays out of the way until it matters.
249
+ */
250
+ export function needsProviderChoice(capabilities, markets) {
251
+ const activeMarkets = (markets ?? []).filter((m) => m.active !== false);
252
+ if (activeMarkets.length > 1)
253
+ return true;
254
+ return (capabilities ?? []).some((c) => !c.fanout && c.providers.filter((p) => p.installed).length > 1);
255
+ }
256
+ /**
257
+ * Installed addons that compete with another installed addon for the same
258
+ * function (a non-fan-out capability with 2+ installed providers). The host
259
+ * links their card in the installed-addons list to the provider-choice
260
+ * screen, where the choice is made.
261
+ */
262
+ export function competingProviderAddons(capabilities) {
263
+ const out = new Set();
264
+ for (const c of capabilities ?? []) {
265
+ if (c.fanout)
266
+ continue;
267
+ const installed = c.providers.filter((p) => p.installed);
268
+ if (installed.length > 1)
269
+ installed.forEach((p) => out.add(p.addon_key));
270
+ }
271
+ return out;
272
+ }
273
+ /**
274
+ * The badge a provider deserves in market `m`, first match wins:
275
+ * `unavailable` when it is not installed or does not serve the market,
276
+ * `disabled` when `opts.enabled === false`, `missing_credentials` when it
277
+ * still needs to be connected, `unhealthy` when `opts.healthy === false`,
278
+ * `sandbox` when it runs against a test environment, else `ready`.
279
+ * Providers that need no connection are ready.
280
+ */
281
+ export function providerStatus(provider, info, m, opts) {
282
+ if (!provider.installed || !servesMarket(provider, m))
283
+ return 'unavailable';
284
+ if (opts?.enabled === false)
285
+ return 'disabled';
286
+ if (info?.connection?.state === 'missing_credentials')
287
+ return 'missing_credentials';
288
+ if (opts?.healthy === false)
289
+ return 'unhealthy';
290
+ if (info?.connection?.state === 'connected' && info.connection.environment === 'sandbox')
291
+ return 'sandbox';
292
+ return 'ready';
293
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * ProviderSortableList: an ordered list of options with a status badge, a
3
+ * keyboard-accessible drag handle and an "inherits from the organization"
4
+ * marker. Domain-agnostic: the host decides what the ids mean and what to do
5
+ * with the new order.
6
+ *
7
+ * Keyboard: focus the handle, Space/Enter grabs, ArrowUp/ArrowDown move,
8
+ * Space/Enter drops, Escape cancels. Pointer: press the handle and drag.
9
+ * Items that are not eligible (status `unavailable` / `disabled`, `enabled:
10
+ * false` or `eligible: false`) are rendered after the sortable ones in their
11
+ * own list, have no handle, and are never part of the emitted order.
12
+ *
13
+ * `onReorder` emits ONLY the eligible ids. A host that persists the whole
14
+ * list (including ineligible entries that are not merely "does not serve the
15
+ * market", e.g. disabled ones) must merge: keep its own ineligible entries
16
+ * and replace the order of the eligible ones with what is emitted here.
17
+ */
18
+ import * as React from 'react';
19
+ import type { ProviderStatus } from './model';
20
+ export interface ProviderSortableItem {
21
+ id: string;
22
+ /**
23
+ * What to show. If it is not plain text, also pass `textLabel`: the handle
24
+ * and the live region announce `textLabel` (never the raw id when avoidable).
25
+ */
26
+ label: React.ReactNode;
27
+ /** Plain-text name for assistive technology (handle, live region). */
28
+ textLabel?: string;
29
+ status: ProviderStatus;
30
+ /** Secondary line (e.g. the account or environment). */
31
+ description?: React.ReactNode;
32
+ /** Defaults to `status` not being `unavailable` / `disabled`, and `enabled !== false`. */
33
+ eligible?: boolean;
34
+ /**
35
+ * The row's own `enabled` flag. `false` shows the `disabled` badge and
36
+ * makes the item ineligible. With `onEnabledChange` a switch is rendered.
37
+ */
38
+ enabled?: boolean;
39
+ /** Per-item actions (e.g. a "connect" link while `missing_credentials`). */
40
+ actions?: React.ReactNode;
41
+ }
42
+ export interface ProviderSortableListLabels {
43
+ ready: string;
44
+ missing_credentials: string;
45
+ sandbox: string;
46
+ unavailable: string;
47
+ unhealthy: string;
48
+ disabled: string;
49
+ inherited: string;
50
+ /** Heading (aria-label) of the list of items that cannot be ordered. */
51
+ unavailableGroup: string;
52
+ /** Keyboard instructions, linked to every handle with aria-describedby. */
53
+ instructions: string;
54
+ /** aria-label of the drag handle; receives the item's text label. */
55
+ handle: (label: string) => string;
56
+ /** aria-label of the enabled switch. */
57
+ enable: (label: string) => string;
58
+ /** Live-region messages. */
59
+ grabbed: (label: string, position: number, total: number) => string;
60
+ moved: (label: string, position: number, total: number) => string;
61
+ dropped: (label: string, position: number, total: number) => string;
62
+ cancelled: (label: string) => string;
63
+ }
64
+ /** Spanish defaults, kept as a plain constant for hosts that want to spread/override it. */
65
+ export declare const DEFAULT_PROVIDER_LIST_LABELS: ProviderSortableListLabels;
66
+ export interface ProviderSortableListProps {
67
+ items: ProviderSortableItem[];
68
+ /** Ids of the eligible items in their current order; unlisted eligible items follow in `items` order. */
69
+ order?: string[];
70
+ /** Emits the new order of the ELIGIBLE items on drop (keyboard or pointer). Never called when nothing moved. */
71
+ onReorder: (order: string[]) => void;
72
+ /** The order shown is the organization's, not the market's own. */
73
+ inherited?: boolean;
74
+ /** Renders the "inherits from the organization" switch instead of a plain note. */
75
+ onInheritedChange?: (inherited: boolean) => void;
76
+ /** Renders a per-item enabled switch. */
77
+ onEnabledChange?: (id: string, enabled: boolean) => void;
78
+ disabled?: boolean;
79
+ labels?: Partial<ProviderSortableListLabels>;
80
+ className?: string;
81
+ 'aria-label'?: string;
82
+ }
83
+ /** Eligible ids in display order, honoring `order` first. */
84
+ export declare function sortableOrder(items: readonly ProviderSortableItem[], order?: readonly string[]): string[];
85
+ export declare function ProviderSortableList({ items, order, onReorder, inherited, onInheritedChange, onEnabledChange, disabled, labels: labelsProp, className, 'aria-label': ariaLabel, }: ProviderSortableListProps): React.JSX.Element;
86
+ //# sourceMappingURL=provider-sortable-list.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-sortable-list.d.ts","sourceRoot":"","sources":["../../src/capability-providers/provider-sortable-list.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAG7C,MAAM,WAAW,oBAAoB;IACjC,EAAE,EAAE,MAAM,CAAA;IACV;;;OAGG;IACH,KAAK,EAAE,KAAK,CAAC,SAAS,CAAA;IACtB,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,cAAc,CAAA;IACtB,wDAAwD;IACxD,WAAW,CAAC,EAAE,KAAK,CAAC,SAAS,CAAA;IAC7B,0FAA0F;IAC1F,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,4EAA4E;IAC5E,OAAO,CAAC,EAAE,KAAK,CAAC,SAAS,CAAA;CAC5B;AAED,MAAM,WAAW,0BAA0B;IACvC,KAAK,EAAE,MAAM,CAAA;IACb,mBAAmB,EAAE,MAAM,CAAA;IAC3B,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,EAAE,MAAM,CAAA;IACnB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,MAAM,CAAA;IACjB,wEAAwE;IACxE,gBAAgB,EAAE,MAAM,CAAA;IACxB,2EAA2E;IAC3E,YAAY,EAAE,MAAM,CAAA;IACpB,qEAAqE;IACrE,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACjC,wCAAwC;IACxC,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACjC,4BAA4B;IAC5B,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACnE,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACjE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACnE,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;CACvC;AAED,4FAA4F;AAC5F,eAAO,MAAM,4BAA4B,EAAE,0BAgB1C,CAAA;AAyCD,MAAM,WAAW,yBAAyB;IACtC,KAAK,EAAE,oBAAoB,EAAE,CAAA;IAC7B,yGAAyG;IACzG,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;IAChB,gHAAgH;IAChH,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,CAAA;IACpC,mEAAmE;IACnE,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,KAAK,IAAI,CAAA;IAChD,yCAAyC;IACzC,eAAe,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,CAAA;IACxD,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,MAAM,CAAC,EAAE,OAAO,CAAC,0BAA0B,CAAC,CAAA;IAC5C,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,YAAY,CAAC,EAAE,MAAM,CAAA;CACxB;AAsBD,6DAA6D;AAC7D,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,oBAAoB,EAAE,EAAE,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAKzG;AAED,wBAAgB,oBAAoB,CAAC,EACjC,KAAK,EACL,KAAK,EACL,SAAS,EACT,SAAS,EACT,iBAAiB,EACjB,eAAe,EACf,QAAQ,EACR,MAAM,EAAE,UAAU,EAClB,SAAS,EACT,YAAY,EAAE,SAAS,GAC1B,EAAE,yBAAyB,qBAiQ3B"}
@@ -0,0 +1,263 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * ProviderSortableList: an ordered list of options with a status badge, a
4
+ * keyboard-accessible drag handle and an "inherits from the organization"
5
+ * marker. Domain-agnostic: the host decides what the ids mean and what to do
6
+ * with the new order.
7
+ *
8
+ * Keyboard: focus the handle, Space/Enter grabs, ArrowUp/ArrowDown move,
9
+ * Space/Enter drops, Escape cancels. Pointer: press the handle and drag.
10
+ * Items that are not eligible (status `unavailable` / `disabled`, `enabled:
11
+ * false` or `eligible: false`) are rendered after the sortable ones in their
12
+ * own list, have no handle, and are never part of the emitted order.
13
+ *
14
+ * `onReorder` emits ONLY the eligible ids. A host that persists the whole
15
+ * list (including ineligible entries that are not merely "does not serve the
16
+ * market", e.g. disabled ones) must merge: keep its own ineligible entries
17
+ * and replace the order of the eligible ones with what is emitted here.
18
+ */
19
+ import * as React from 'react';
20
+ import { useTranslation } from 'react-i18next';
21
+ import { dropIndexFromPointer, moveId } from './reorder';
22
+ /** Spanish defaults, kept as a plain constant for hosts that want to spread/override it. */
23
+ export const DEFAULT_PROVIDER_LIST_LABELS = {
24
+ ready: 'Listo',
25
+ missing_credentials: 'Sin credenciales',
26
+ sandbox: 'Sandbox',
27
+ unavailable: 'No atiende',
28
+ unhealthy: 'Con fallas',
29
+ disabled: 'Desactivado',
30
+ inherited: 'Hereda de la organización',
31
+ unavailableGroup: 'Sin orden: no disponibles',
32
+ instructions: 'Espacio o Enter para tomar, flechas para mover, Espacio o Enter para soltar, Escape para cancelar.',
33
+ handle: (l) => `Reordenar ${l}`,
34
+ enable: (l) => `Activar ${l}`,
35
+ grabbed: (l, p, t) => `${l} tomado, posición ${p} de ${t}. Usa las flechas para mover.`,
36
+ moved: (l, p, t) => `${l}, posición ${p} de ${t}.`,
37
+ dropped: (l, p, t) => `${l} soltado en la posición ${p} de ${t}.`,
38
+ cancelled: (l) => `Reordenamiento de ${l} cancelado.`,
39
+ };
40
+ /** Replaces any `{{name}}` that the translator left (e.g. no i18n instance yet). */
41
+ function fill(s, vars) {
42
+ return s.replace(/\{\{\s*(\w+)\s*\}\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
43
+ }
44
+ /**
45
+ * Default labels through the host's i18n (`capability_providers.*` keys, same
46
+ * convention as the rest of the package), falling back to the Spanish text.
47
+ * `overrides` always wins.
48
+ */
49
+ function useProviderListLabels(overrides) {
50
+ const { t } = useTranslation();
51
+ const D = DEFAULT_PROVIDER_LIST_LABELS;
52
+ const s = (key, def) => t(`capability_providers.${key}`, { defaultValue: def });
53
+ const f = (key, def, vars) => fill(t(`capability_providers.${key}`, { defaultValue: def, ...vars }), vars);
54
+ return {
55
+ ready: s('ready', D.ready),
56
+ missing_credentials: s('missing_credentials', D.missing_credentials),
57
+ sandbox: s('sandbox', D.sandbox),
58
+ unavailable: s('unavailable', D.unavailable),
59
+ unhealthy: s('unhealthy', D.unhealthy),
60
+ disabled: s('disabled', D.disabled),
61
+ inherited: s('inherited', D.inherited),
62
+ unavailableGroup: s('unavailableGroup', D.unavailableGroup),
63
+ instructions: s('instructions', D.instructions),
64
+ handle: (label) => f('handle', 'Reordenar {{label}}', { label }),
65
+ enable: (label) => f('enable', 'Activar {{label}}', { label }),
66
+ grabbed: (label, position, total) => f('grabbed', '{{label}} tomado, posición {{position}} de {{total}}. Usa las flechas para mover.', { label, position, total }),
67
+ moved: (label, position, total) => f('moved', '{{label}}, posición {{position}} de {{total}}.', { label, position, total }),
68
+ dropped: (label, position, total) => f('dropped', '{{label}} soltado en la posición {{position}} de {{total}}.', { label, position, total }),
69
+ cancelled: (label) => f('cancelled', 'Reordenamiento de {{label}} cancelado.', { label }),
70
+ ...overrides,
71
+ };
72
+ }
73
+ const cx = (...c) => c.filter(Boolean).join(' ');
74
+ const BADGE_TONE = {
75
+ ready: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300',
76
+ missing_credentials: 'bg-amber-100 text-amber-800 dark:bg-amber-500/15 dark:text-amber-300',
77
+ sandbox: 'bg-sky-100 text-sky-800 dark:bg-sky-500/15 dark:text-sky-300',
78
+ unhealthy: 'bg-red-100 text-red-800 dark:bg-red-500/15 dark:text-red-300',
79
+ unavailable: 'bg-muted text-muted-foreground',
80
+ disabled: 'bg-muted text-muted-foreground',
81
+ };
82
+ function statusOf(i) {
83
+ return i.enabled === false ? 'disabled' : i.status;
84
+ }
85
+ function isEligible(i) {
86
+ if (i.enabled === false)
87
+ return false;
88
+ return i.eligible ?? (i.status !== 'unavailable' && i.status !== 'disabled');
89
+ }
90
+ /** Eligible ids in display order, honoring `order` first. */
91
+ export function sortableOrder(items, order) {
92
+ const eligible = items.filter(isEligible).map((i) => i.id);
93
+ const set = new Set(eligible);
94
+ const head = (order ?? []).filter((id, n, a) => set.has(id) && a.indexOf(id) === n);
95
+ return [...head, ...eligible.filter((id) => !head.includes(id))];
96
+ }
97
+ export function ProviderSortableList({ items, order, onReorder, inherited, onInheritedChange, onEnabledChange, disabled, labels: labelsProp, className, 'aria-label': ariaLabel, }) {
98
+ const labels = useProviderListLabels(labelsProp);
99
+ const helpId = React.useId();
100
+ const byId = React.useMemo(() => new Map(items.map((i) => [i.id, i])), [items]);
101
+ const base = React.useMemo(() => sortableOrder(items, order), [items, order]);
102
+ // While grabbed (keyboard) or dragging (pointer) the list shows a draft.
103
+ const [draft, setDraft] = React.useState(null);
104
+ const [active, setActive] = React.useState(null);
105
+ const [announce, setAnnounce] = React.useState('');
106
+ const rows = React.useRef(new Map());
107
+ const handles = React.useRef(new Map());
108
+ const mode = React.useRef('keyboard');
109
+ // True between a programmatic reorder and the moment focus is restored:
110
+ // moving the focused <li> in the DOM makes browsers blur the handle.
111
+ const reordering = React.useRef(false);
112
+ // The draft is reconciled against the CURRENT items on every render, so an
113
+ // items/order change (refetch, market switch, addon uninstalled) in the
114
+ // middle of a grab can never leave ids that no longer exist.
115
+ const shown = React.useMemo(() => {
116
+ if (!draft)
117
+ return base;
118
+ const live = new Set(base);
119
+ const kept = draft.filter((id, n, a) => live.has(id) && a.indexOf(id) === n);
120
+ return [...kept, ...base.filter((id) => !kept.includes(id))];
121
+ }, [draft, base]);
122
+ const shownRef = React.useRef(shown);
123
+ shownRef.current = shown;
124
+ const blocked = items.filter((i) => !isEligible(i));
125
+ const textOf = (id) => {
126
+ const item = byId.get(id);
127
+ if (!item)
128
+ return id;
129
+ if (item.textLabel)
130
+ return item.textLabel;
131
+ return typeof item.label === 'string' || typeof item.label === 'number' ? String(item.label) : id;
132
+ };
133
+ const clear = () => {
134
+ setDraft(null);
135
+ setActive(null);
136
+ };
137
+ const commit = (next, id, announceUnchanged = true) => {
138
+ const changed = next.some((x, n) => x !== base[n]);
139
+ clear();
140
+ if (changed || announceUnchanged)
141
+ setAnnounce(labels.dropped(textOf(id), next.indexOf(id) + 1, next.length));
142
+ if (changed)
143
+ onReorder(next);
144
+ };
145
+ const cancel = (id) => {
146
+ clear();
147
+ setAnnounce(labels.cancelled(textOf(id)));
148
+ };
149
+ const step = (id, delta) => {
150
+ const next = moveId(shown, id, delta);
151
+ reordering.current = true;
152
+ setDraft(next);
153
+ setAnnounce(labels.moved(textOf(id), next.indexOf(id) + 1, next.length));
154
+ };
155
+ // Keep the latest closures reachable from the window listeners below.
156
+ const latest = React.useRef({ commit, cancel });
157
+ latest.current = { commit, cancel };
158
+ // The grabbed item vanished (items changed) or the list got disabled
159
+ // mid-grab: drop the grab without emitting anything.
160
+ React.useEffect(() => {
161
+ if (active && (disabled || !base.includes(active)))
162
+ clear();
163
+ }, [active, disabled, base]);
164
+ // Moving the focused <li> blurs the handle in real browsers (happy-dom does
165
+ // not): put the focus back on the grabbed handle after every reorder.
166
+ React.useLayoutEffect(() => {
167
+ reordering.current = false;
168
+ if (active && mode.current === 'keyboard') {
169
+ const h = handles.current.get(active);
170
+ if (h && document.activeElement !== h)
171
+ h.focus({ preventScroll: true });
172
+ }
173
+ });
174
+ // Pointer drag: listen on window while dragging. Pointer capture on the
175
+ // handle would be lost whenever React moves its <li>, leaving the drag
176
+ // half done; window listeners survive any DOM reordering.
177
+ React.useEffect(() => {
178
+ if (!active || mode.current !== 'pointer')
179
+ return;
180
+ const id = active;
181
+ const onMove = (e) => {
182
+ const cur = shownRef.current;
183
+ const others = cur.filter((x) => x !== id);
184
+ const mids = others.map((x) => {
185
+ const r = rows.current.get(x)?.getBoundingClientRect();
186
+ return r ? r.top + r.height / 2 : 0;
187
+ });
188
+ const to = dropIndexFromPointer(e.clientY, mids);
189
+ const next = [...others.slice(0, to), id, ...others.slice(to)];
190
+ if (next.some((x, n) => x !== cur[n]))
191
+ setDraft(next);
192
+ };
193
+ const onUp = () => latest.current.commit(shownRef.current, id, false);
194
+ const onCancel = () => latest.current.cancel(id);
195
+ window.addEventListener('pointermove', onMove);
196
+ window.addEventListener('pointerup', onUp);
197
+ window.addEventListener('pointercancel', onCancel);
198
+ return () => {
199
+ window.removeEventListener('pointermove', onMove);
200
+ window.removeEventListener('pointerup', onUp);
201
+ window.removeEventListener('pointercancel', onCancel);
202
+ };
203
+ }, [active]);
204
+ const onKeyDown = (id) => (e) => {
205
+ if (disabled)
206
+ return;
207
+ const grabbed = active === id;
208
+ if (e.key === ' ' || e.key === 'Enter') {
209
+ e.preventDefault();
210
+ if (grabbed)
211
+ commit(shown, id);
212
+ else {
213
+ mode.current = 'keyboard';
214
+ setActive(id);
215
+ setDraft(base);
216
+ setAnnounce(labels.grabbed(textOf(id), base.indexOf(id) + 1, base.length));
217
+ }
218
+ }
219
+ else if (grabbed && (e.key === 'ArrowUp' || e.key === 'ArrowLeft')) {
220
+ e.preventDefault();
221
+ step(id, -1);
222
+ }
223
+ else if (grabbed && (e.key === 'ArrowDown' || e.key === 'ArrowRight')) {
224
+ e.preventDefault();
225
+ step(id, 1);
226
+ }
227
+ else if (grabbed && e.key === 'Escape') {
228
+ e.preventDefault();
229
+ cancel(id);
230
+ }
231
+ };
232
+ const onPointerDown = (id) => (e) => {
233
+ if (disabled || (e.button !== undefined && e.button !== 0))
234
+ return;
235
+ mode.current = 'pointer';
236
+ setActive(id);
237
+ setDraft(base);
238
+ };
239
+ const switches = (item) => onEnabledChange ? (_jsx("input", { type: "checkbox", role: "switch", disabled: disabled, checked: item.enabled !== false, "aria-label": labels.enable(textOf(item.id)), "data-enabled-switch": item.id, onChange: (e) => onEnabledChange(item.id, e.target.checked) })) : null;
240
+ return (_jsxs("div", { className: className, children: [onInheritedChange ? (_jsxs("label", { "data-testid": "provider-list-inherited", className: "mb-2 flex items-center gap-2 text-xs text-muted-foreground", children: [_jsx("input", { type: "checkbox", role: "switch", disabled: disabled, checked: !!inherited, onChange: (e) => onInheritedChange(e.target.checked) }), labels.inherited] })) : (inherited && (_jsx("p", { "data-testid": "provider-list-inherited", className: "mb-2 text-xs text-muted-foreground", children: labels.inherited }))), _jsx("span", { id: helpId, className: "sr-only", children: labels.instructions }), _jsx("ol", { "aria-label": ariaLabel, className: "space-y-1", children: shown.map((id, n) => {
241
+ const item = byId.get(id);
242
+ if (!item)
243
+ return null;
244
+ const grabbed = active === id;
245
+ return (_jsxs("li", { ref: (el) => {
246
+ if (el)
247
+ rows.current.set(id, el);
248
+ else
249
+ rows.current.delete(id);
250
+ }, "data-id": id, "data-grabbed": grabbed || undefined, className: cx('flex items-center gap-3 rounded-md border px-3 py-2', grabbed && 'bg-accent shadow-sm'), children: [_jsx("button", { type: "button", disabled: disabled, ref: (el) => {
251
+ if (el)
252
+ handles.current.set(id, el);
253
+ else
254
+ handles.current.delete(id);
255
+ }, "aria-label": labels.handle(textOf(id)), "aria-describedby": helpId, "aria-pressed": grabbed, "data-handle": id, className: "cursor-grab touch-none select-none px-1 text-muted-foreground", onKeyDown: onKeyDown(id), onPointerDown: onPointerDown(id), onBlur: () => {
256
+ if (active === id && mode.current === 'keyboard' && !reordering.current)
257
+ cancel(id);
258
+ }, children: _jsx("span", { "aria-hidden": "true", children: "\u22EE\u22EE" }) }), _jsx("span", { className: "w-5 text-xs tabular-nums text-muted-foreground", children: n + 1 }), _jsxs("span", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block truncate text-sm font-medium", children: item.label }), item.description && (_jsx("span", { className: "block truncate text-xs text-muted-foreground", children: item.description }))] }), item.actions, switches(item), _jsx(StatusBadge, { status: statusOf(item), labels: labels })] }, id));
259
+ }) }), blocked.length > 0 && (_jsx("ul", { "aria-label": labels.unavailableGroup, className: "mt-1 space-y-1", children: blocked.map((item) => (_jsxs("li", { "data-id": item.id, "data-ineligible": true, "aria-disabled": "true", className: "flex items-center gap-3 rounded-md border border-dashed px-3 py-2 opacity-70", children: [_jsxs("span", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block truncate text-sm font-medium", children: item.label }), item.description && (_jsx("span", { className: "block truncate text-xs text-muted-foreground", children: item.description }))] }), item.actions, switches(item), _jsx(StatusBadge, { status: statusOf(item), labels: labels })] }, item.id))) })), _jsx("div", { role: "status", "aria-live": "polite", "aria-atomic": "true", className: "sr-only", children: announce })] }));
260
+ }
261
+ function StatusBadge({ status, labels }) {
262
+ return (_jsx("span", { "data-status": status, className: cx('shrink-0 rounded-full px-2 py-0.5 text-xs font-medium', BADGE_TONE[status]), children: labels[status] }));
263
+ }
@@ -0,0 +1,10 @@
1
+ /** Move the item at `from` to index `to`; out-of-range or no-op returns the same array. */
2
+ export declare function moveItem<T>(list: readonly T[], from: number, to: number): T[];
3
+ /** Move `id` by `delta` positions within `order` (ids not in `order` are ignored). */
4
+ export declare function moveId(order: readonly string[], id: string, delta: number): string[];
5
+ /**
6
+ * Index where a dragged item should land given the pointer position and the
7
+ * vertical midpoints of the OTHER rows (document order): 0..midpoints.length.
8
+ */
9
+ export declare function dropIndexFromPointer(pointerY: number, midpoints: readonly number[]): number;
10
+ //# sourceMappingURL=reorder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reorder.d.ts","sourceRoot":"","sources":["../../src/capability-providers/reorder.ts"],"names":[],"mappings":"AAEA,2FAA2F;AAC3F,wBAAgB,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,CAAC,EAAE,CAQ7E;AAED,sFAAsF;AACtF,wBAAgB,MAAM,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAIpF;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAI3F"}