@svgrid/enterprise 1.2.0 → 2.0.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.
- package/dist/cdn/svgrid-enterprise.svelte-external.js +26039 -805
- package/dist/designer/assets/index-Dp44bTid.js +939 -0
- package/dist/designer/assets/index-RJp6x8tw.css +1 -0
- package/dist/designer/assets/jszip.min-CjMo-QGg.js +2 -0
- package/dist/designer/index.html +13 -0
- package/dist/node/studio.js +22554 -0
- package/package.json +10 -3
- package/src/SvAuthGate.svelte +115 -0
- package/src/SvBoard.dom.test.ts +67 -0
- package/src/SvBoard.svelte +192 -0
- package/src/SvExportMenu.svelte +553 -0
- package/src/SvFileInput.svelte +113 -0
- package/src/SvGridEditPanel.dom.test.ts +146 -0
- package/src/SvGridEditPanel.svelte +793 -0
- package/src/SvGridMasterDetail.svelte +95 -0
- package/src/SvImportDialog.svelte +1020 -0
- package/src/SvLookupInput.svelte +180 -0
- package/src/SvRecordDetail.dom.test.ts +137 -0
- package/src/SvRecordDetail.svelte +288 -0
- package/src/SvSchedule.dom.test.ts +57 -0
- package/src/SvSchedule.svelte +156 -0
- package/src/SvSchemaChart.svelte +233 -0
- package/src/SvSchemaDashboard.svelte +130 -0
- package/src/ai-export-pdf.test.ts +74 -0
- package/src/ai-export-xlsx.test.ts +87 -0
- package/src/ai-export.test.ts +110 -0
- package/src/ai.ts +1188 -782
- package/src/edit-panel.test.ts +213 -0
- package/src/edit-panel.ts +228 -0
- package/src/export-conditional.test.ts +60 -0
- package/src/export-conditional.ts +94 -0
- package/src/export-ooxml.test.ts +152 -0
- package/src/export-ooxml.ts +485 -0
- package/src/export-pdf.test.ts +138 -0
- package/src/export-pdf.ts +245 -0
- package/src/export-print.test.ts +66 -0
- package/src/export-print.ts +132 -0
- package/src/export-serialize.test.ts +56 -0
- package/src/export-serialize.ts +24 -0
- package/src/export-xls.ts +196 -0
- package/src/export-xlsx-roundtrip.test.ts +120 -0
- package/src/export-xlsx.test.ts +150 -0
- package/src/export.test.ts +349 -0
- package/src/export.ts +1452 -549
- package/src/import-automap.test.ts +131 -0
- package/src/import-hardening.test.ts +158 -0
- package/src/import.ts +1042 -648
- package/src/index.ts +282 -0
- package/src/install.ts +134 -114
- package/src/license-core.test.ts +23 -0
- package/src/license-core.ts +35 -0
- package/src/license.ts +103 -90
- package/src/master-detail.test.ts +61 -0
- package/src/master-detail.ts +42 -0
- package/src/print.ts +107 -127
- package/src/schema-designer.test.ts +121 -0
- package/src/schema-designer.ts +142 -0
- package/src/schema.test.ts +268 -0
- package/src/schema.ts +499 -0
- package/src/smart-shim.ts +107 -105
- package/src/sources/aggregate.test.ts +79 -0
- package/src/sources/aggregate.ts +102 -0
- package/src/sources/auth-supabase.test.ts +80 -0
- package/src/sources/auth-supabase.ts +87 -0
- package/src/sources/dashboard.kpi.test.ts +50 -0
- package/src/sources/dashboard.test.ts +61 -0
- package/src/sources/dashboard.ts +136 -0
- package/src/sources/field-inference.test.ts +60 -0
- package/src/sources/field-inference.ts +63 -0
- package/src/sources/filters.test.ts +58 -0
- package/src/sources/filters.ts +64 -0
- package/src/sources/index.ts +67 -0
- package/src/sources/introspect-supabase.test.ts +100 -0
- package/src/sources/introspect-supabase.ts +119 -0
- package/src/sources/realtime-supabase.test.ts +93 -0
- package/src/sources/realtime-supabase.ts +99 -0
- package/src/sources/relation-lookup.test.ts +99 -0
- package/src/sources/relation-lookup.ts +128 -0
- package/src/sources/rest-adapters.test.ts +95 -0
- package/src/sources/rest-adapters.ts +120 -0
- package/src/sources/rest.test.ts +104 -0
- package/src/sources/rest.ts +129 -0
- package/src/sources/schema-from-columns.test.ts +106 -0
- package/src/sources/schema-from-columns.ts +88 -0
- package/src/sources/supabase.test.ts +110 -0
- package/src/sources/supabase.ts +99 -0
- package/src/sources/with-entity-rules.test.ts +104 -0
- package/src/sources/with-entity-rules.ts +78 -0
- package/src/sources/with-relation-labels.test.ts +75 -0
- package/src/sources/with-relation-labels.ts +73 -0
- package/src/studio/bug-report.test.ts +101 -0
- package/src/studio/bug-report.ts +165 -0
- package/src/studio/cli.test.ts +187 -0
- package/src/studio/cli.ts +112 -0
- package/src/studio/csv.test.ts +90 -0
- package/src/studio/csv.ts +165 -0
- package/src/studio/db-connect-string.test.ts +94 -0
- package/src/studio/db-connect-string.ts +128 -0
- package/src/studio/emit-project.test.ts +923 -0
- package/src/studio/emit-project.ts +1273 -0
- package/src/studio/emit-schema.test.ts +94 -0
- package/src/studio/emit-schema.ts +920 -0
- package/src/studio/index.ts +195 -0
- package/src/studio/introspect-db.test.ts +186 -0
- package/src/studio/introspect-db.ts +312 -0
- package/src/studio/introspect-prisma.test.ts +99 -0
- package/src/studio/introspect-prisma.ts +175 -0
- package/src/studio/introspect.test.ts +172 -0
- package/src/studio/introspect.ts +310 -0
- package/src/studio/pipeline.test.ts +42 -0
- package/src/studio/project-robust.test.ts +157 -0
- package/src/studio/project.test.ts +473 -0
- package/src/studio/project.ts +916 -0
- package/src/studio/sample-data.test.ts +58 -0
- package/src/studio/sample-data.ts +200 -0
- package/src/studio/samples/ats.ts +202 -0
- package/src/studio/samples/clinic.ts +177 -0
- package/src/studio/samples/crm.ts +250 -0
- package/src/studio/samples/ecommerce.ts +187 -0
- package/src/studio/samples/events.ts +199 -0
- package/src/studio/samples/fleet.ts +184 -0
- package/src/studio/samples/gym.ts +213 -0
- package/src/studio/samples/hr.ts +193 -0
- package/src/studio/samples/index.ts +55 -0
- package/src/studio/samples/insurance.ts +195 -0
- package/src/studio/samples/inventory.ts +182 -0
- package/src/studio/samples/invoicing.ts +162 -0
- package/src/studio/samples/library.ts +180 -0
- package/src/studio/samples/live-data.test.ts +98 -0
- package/src/studio/samples/live-data.ts +308 -0
- package/src/studio/samples/projects.ts +190 -0
- package/src/studio/samples/realestate.ts +196 -0
- package/src/studio/samples/restaurant.ts +187 -0
- package/src/studio/samples/samples.test.ts +208 -0
- package/src/studio/samples/school.ts +197 -0
- package/src/studio/samples/seed-floor.test.ts +25 -0
- package/src/studio/samples/shared.ts +305 -0
- package/src/studio/samples/subscriptions.ts +183 -0
- package/src/studio/samples/support.ts +182 -0
- package/src/studio/scaffold-app.test.ts +91 -0
- package/src/studio/scaffold-app.ts +161 -0
- package/src/studio/scaffold.test.ts +178 -0
- package/src/studio/scaffold.ts +374 -0
- package/src/studio/themes.ts +172 -0
- package/src/studio/verify.test.ts +47 -0
- package/src/studio/verify.ts +79 -0
- package/src/sveltekit/in-memory.test.ts +104 -0
- package/src/sveltekit/in-memory.ts +129 -0
- package/src/sveltekit/index.ts +23 -0
- package/src/sveltekit/query-plan.test.ts +109 -0
- package/src/sveltekit/query-plan.ts +125 -0
- package/src/sveltekit/sql-source.test.ts +185 -0
- package/src/sveltekit/sql-source.ts +166 -0
- package/src/sveltekit/sql.test.ts +80 -0
- package/src/sveltekit/sql.ts +131 -0
- package/src/sveltekit/transport.test.ts +175 -0
- package/src/sveltekit/transport.ts +254 -0
- package/src/sveltekit/types.ts +11 -0
- package/src/upgrade-prompt.ts +149 -148
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { createSupabaseRealtime } from './realtime-supabase'
|
|
3
|
+
|
|
4
|
+
/** A supabase-js-like realtime client that captures the wiring and can fire payloads. */
|
|
5
|
+
function makeClient() {
|
|
6
|
+
const state: {
|
|
7
|
+
name?: string
|
|
8
|
+
filter?: Record<string, unknown>
|
|
9
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
10
|
+
cb?: (payload: any) => void
|
|
11
|
+
status?: (s: string) => void
|
|
12
|
+
removed: unknown[]
|
|
13
|
+
} = { removed: [] }
|
|
14
|
+
|
|
15
|
+
const channel: any = {
|
|
16
|
+
on(_type: string, filter: Record<string, unknown>, cb: (p: unknown) => void) {
|
|
17
|
+
state.filter = filter
|
|
18
|
+
state.cb = cb
|
|
19
|
+
return channel
|
|
20
|
+
},
|
|
21
|
+
subscribe(cb?: (s: string) => void) {
|
|
22
|
+
state.status = cb
|
|
23
|
+
return channel
|
|
24
|
+
},
|
|
25
|
+
}
|
|
26
|
+
const client = {
|
|
27
|
+
channel(name: string) { state.name = name; return channel },
|
|
28
|
+
removeChannel(ch: unknown) { state.removed.push(ch) },
|
|
29
|
+
}
|
|
30
|
+
return { client, channel, state }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
afterEach(() => vi.useRealTimers())
|
|
34
|
+
|
|
35
|
+
describe('createSupabaseRealtime', () => {
|
|
36
|
+
it('subscribes to postgres_changes for the table with defaults', () => {
|
|
37
|
+
const { client, state } = makeClient()
|
|
38
|
+
createSupabaseRealtime({ client, table: 'customers', onChange: () => {} })
|
|
39
|
+
expect(state.name).toBe('svgrid:public:customers')
|
|
40
|
+
expect(state.filter).toEqual({ event: '*', schema: 'public', table: 'customers' })
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('honors schema, event, filter, and channelName', () => {
|
|
44
|
+
const { client, state } = makeClient()
|
|
45
|
+
createSupabaseRealtime({
|
|
46
|
+
client, table: 't', schema: 'app', event: 'INSERT', filter: 'tier=eq.pro', channelName: 'c', onChange: () => {},
|
|
47
|
+
})
|
|
48
|
+
expect(state.name).toBe('c')
|
|
49
|
+
expect(state.filter).toEqual({ event: 'INSERT', schema: 'app', table: 't', filter: 'tier=eq.pro' })
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('normalizes a change payload', () => {
|
|
53
|
+
const { client, state } = makeClient()
|
|
54
|
+
const onChange = vi.fn()
|
|
55
|
+
createSupabaseRealtime({ client, table: 't', onChange })
|
|
56
|
+
state.cb!({ eventType: 'UPDATE', new: { id: 1, name: 'X' }, old: { id: 1 } })
|
|
57
|
+
expect(onChange).toHaveBeenCalledWith({ type: 'UPDATE', new: { id: 1, name: 'X' }, old: { id: 1 } })
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('passes status through', () => {
|
|
61
|
+
const { client, state } = makeClient()
|
|
62
|
+
const onStatus = vi.fn()
|
|
63
|
+
createSupabaseRealtime({ client, table: 't', onChange: () => {}, onStatus })
|
|
64
|
+
state.status!('SUBSCRIBED')
|
|
65
|
+
expect(onStatus).toHaveBeenCalledWith('SUBSCRIBED')
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('coalesces a burst into one call when debounced', () => {
|
|
69
|
+
vi.useFakeTimers()
|
|
70
|
+
const { client, state } = makeClient()
|
|
71
|
+
const onChange = vi.fn()
|
|
72
|
+
createSupabaseRealtime({ client, table: 't', debounceMs: 200, onChange })
|
|
73
|
+
state.cb!({ eventType: 'INSERT', new: { id: 1 } })
|
|
74
|
+
state.cb!({ eventType: 'INSERT', new: { id: 2 } })
|
|
75
|
+
state.cb!({ eventType: 'INSERT', new: { id: 3 } })
|
|
76
|
+
expect(onChange).not.toHaveBeenCalled()
|
|
77
|
+
vi.advanceTimersByTime(200)
|
|
78
|
+
expect(onChange).toHaveBeenCalledTimes(1)
|
|
79
|
+
expect(onChange).toHaveBeenCalledWith({ type: 'INSERT', new: { id: 3 }, old: null })
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('unsubscribe removes the channel and cancels a pending debounce', () => {
|
|
83
|
+
vi.useFakeTimers()
|
|
84
|
+
const { client, state, channel } = makeClient()
|
|
85
|
+
const onChange = vi.fn()
|
|
86
|
+
const live = createSupabaseRealtime({ client, table: 't', debounceMs: 200, onChange })
|
|
87
|
+
state.cb!({ eventType: 'DELETE', old: { id: 9 } })
|
|
88
|
+
live.unsubscribe()
|
|
89
|
+
vi.advanceTimersByTime(500)
|
|
90
|
+
expect(onChange).not.toHaveBeenCalled()
|
|
91
|
+
expect(state.removed).toEqual([channel])
|
|
92
|
+
})
|
|
93
|
+
})
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createSupabaseRealtime - live updates for a Studio screen via Supabase
|
|
3
|
+
* Realtime (Postgres change streams). Subscribe to a table's INSERT / UPDATE /
|
|
4
|
+
* DELETE events and react - typically by refreshing the current page so the grid
|
|
5
|
+
* stays in sync with the database, no polling.
|
|
6
|
+
*
|
|
7
|
+
* const live = createSupabaseRealtime({
|
|
8
|
+
* client, table: 'customers',
|
|
9
|
+
* debounceMs: 200,
|
|
10
|
+
* onChange: () => controller.refresh(), // re-fetch the current page
|
|
11
|
+
* })
|
|
12
|
+
* // later: live.unsubscribe()
|
|
13
|
+
*
|
|
14
|
+
* You bring the same `supabase-js` client used for reads (BYO, no dependency).
|
|
15
|
+
* Because the server model is paged, the correct default is to `refresh()` on a
|
|
16
|
+
* change - that respects the active sort / filter / page. Use `debounceMs` to
|
|
17
|
+
* coalesce bursts into a single refetch. For per-row effects (e.g. flashing a
|
|
18
|
+
* changed row) read the normalized event passed to `onChange`.
|
|
19
|
+
*/
|
|
20
|
+
import { nudgeEnterprise } from '../license'
|
|
21
|
+
|
|
22
|
+
/** A normalized change event. `new` is the row after the change (INSERT/UPDATE); `old` its prior identity (UPDATE/DELETE). */
|
|
23
|
+
export type RealtimeChange<TData> = {
|
|
24
|
+
type: 'INSERT' | 'UPDATE' | 'DELETE'
|
|
25
|
+
new: TData | null
|
|
26
|
+
old: Partial<TData> | null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The slice of a `supabase-js` client + channel this needs. */
|
|
30
|
+
export type RealtimeChannelLike = {
|
|
31
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
32
|
+
on(type: 'postgres_changes', filter: Record<string, unknown>, cb: (payload: any) => void): RealtimeChannelLike
|
|
33
|
+
subscribe(cb?: (status: string) => void): RealtimeChannelLike
|
|
34
|
+
}
|
|
35
|
+
export type SupabaseRealtimeClientLike = {
|
|
36
|
+
channel(name: string): RealtimeChannelLike
|
|
37
|
+
removeChannel(channel: RealtimeChannelLike): void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type SupabaseRealtimeConfig<TData> = {
|
|
41
|
+
client: SupabaseRealtimeClientLike
|
|
42
|
+
table: string
|
|
43
|
+
/** Postgres schema. Default `'public'`. */
|
|
44
|
+
schema?: string
|
|
45
|
+
/** Only these events. Default `'*'` (all). */
|
|
46
|
+
event?: 'INSERT' | 'UPDATE' | 'DELETE' | '*'
|
|
47
|
+
/** PostgREST-style row filter, e.g. `'tier=eq.pro'`. */
|
|
48
|
+
filter?: string
|
|
49
|
+
/** Unique channel name. Default `svgrid:{schema}:{table}`. */
|
|
50
|
+
channelName?: string
|
|
51
|
+
/** Coalesce bursts: call `onChange` at most once per this window (trailing). */
|
|
52
|
+
debounceMs?: number
|
|
53
|
+
/** Called for each change (or the last of a debounced burst). */
|
|
54
|
+
onChange: (change: RealtimeChange<TData>) => void
|
|
55
|
+
/** Subscription status callback (`SUBSCRIBED`, `CHANNEL_ERROR`, ...). */
|
|
56
|
+
onStatus?: (status: string) => void
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type SupabaseRealtimeHandle = { unsubscribe(): void }
|
|
60
|
+
|
|
61
|
+
export function createSupabaseRealtime<TData = Record<string, unknown>>(
|
|
62
|
+
config: SupabaseRealtimeConfig<TData>,
|
|
63
|
+
): SupabaseRealtimeHandle {
|
|
64
|
+
nudgeEnterprise('Studio') // soft-gate; never blocks
|
|
65
|
+
const schema = config.schema ?? 'public'
|
|
66
|
+
const channelName = config.channelName ?? `svgrid:${schema}:${config.table}`
|
|
67
|
+
|
|
68
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
69
|
+
const emit = (change: RealtimeChange<TData>) => {
|
|
70
|
+
if (!config.debounceMs) {
|
|
71
|
+
config.onChange(change)
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
if (timer) clearTimeout(timer)
|
|
75
|
+
timer = setTimeout(() => config.onChange(change), config.debounceMs)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const channel = config.client
|
|
79
|
+
.channel(channelName)
|
|
80
|
+
.on(
|
|
81
|
+
'postgres_changes',
|
|
82
|
+
{ event: config.event ?? '*', schema, table: config.table, ...(config.filter ? { filter: config.filter } : {}) },
|
|
83
|
+
(payload) => {
|
|
84
|
+
emit({
|
|
85
|
+
type: payload.eventType,
|
|
86
|
+
new: (payload.new ?? null) as TData | null,
|
|
87
|
+
old: (payload.old ?? null) as Partial<TData> | null,
|
|
88
|
+
})
|
|
89
|
+
},
|
|
90
|
+
)
|
|
91
|
+
.subscribe(config.onStatus)
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
unsubscribe() {
|
|
95
|
+
if (timer) clearTimeout(timer)
|
|
96
|
+
config.client.removeChannel(channel)
|
|
97
|
+
},
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import type { ServerRequest } from '@svgrid/grid'
|
|
3
|
+
import type { EntitySchema } from '../schema'
|
|
4
|
+
import { createRelationLookup } from './relation-lookup'
|
|
5
|
+
|
|
6
|
+
type Company = { id: number; name: string }
|
|
7
|
+
|
|
8
|
+
const companies: Company[] = [
|
|
9
|
+
{ id: 1, name: 'Acme Inc' },
|
|
10
|
+
{ id: 2, name: 'Globex' },
|
|
11
|
+
{ id: 3, name: 'Initech' },
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
const schema: EntitySchema<Company> = {
|
|
15
|
+
name: 'companies',
|
|
16
|
+
idField: 'id',
|
|
17
|
+
fields: [
|
|
18
|
+
{ field: 'id', type: 'number', primaryKey: true },
|
|
19
|
+
{ field: 'name', type: 'text' },
|
|
20
|
+
],
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Minimal getRows over the array: honors global search + an equals filter on id. */
|
|
24
|
+
function source() {
|
|
25
|
+
const getRows = vi.fn(async (req: ServerRequest) => {
|
|
26
|
+
let rows = companies
|
|
27
|
+
const g = req.filterModel.global?.toLowerCase()
|
|
28
|
+
if (g) rows = rows.filter((c) => c.name.toLowerCase().includes(g))
|
|
29
|
+
const idCol = req.filterModel.columns?.id
|
|
30
|
+
if (idCol?.selectedValues) rows = rows.filter((c) => idCol.selectedValues!.includes(String(c.id)))
|
|
31
|
+
else if (idCol) rows = rows.filter((c) => String(c.id) === idCol.value)
|
|
32
|
+
return { rows: rows.slice(req.startRow, req.endRow), rowCount: rows.length }
|
|
33
|
+
})
|
|
34
|
+
return { getRows }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
describe('createRelationLookup', () => {
|
|
38
|
+
it('searches and maps rows to { value, label }', async () => {
|
|
39
|
+
const lookup = createRelationLookup({ source: source(), schema, labelField: 'name' })
|
|
40
|
+
expect(await lookup.search('in')).toEqual([
|
|
41
|
+
{ value: '1', label: 'Acme Inc', row: { id: 1, name: 'Acme Inc' } },
|
|
42
|
+
{ value: '3', label: 'Initech', row: { id: 3, name: 'Initech' } },
|
|
43
|
+
])
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('returns a full page for an empty query', async () => {
|
|
47
|
+
const lookup = createRelationLookup({ source: source(), schema, labelField: 'name' })
|
|
48
|
+
expect((await lookup.search('')).map((o) => o.label)).toEqual(['Acme Inc', 'Globex', 'Initech'])
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('resolves a stored key to its label', async () => {
|
|
52
|
+
const lookup = createRelationLookup({ source: source(), schema, labelField: 'name' })
|
|
53
|
+
expect(await lookup.labelFor(2)).toBe('Globex')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('caches labels seen during search (no extra getRows for labelFor)', async () => {
|
|
57
|
+
const src = source()
|
|
58
|
+
const lookup = createRelationLookup({ source: src, schema, labelField: 'name' })
|
|
59
|
+
await lookup.search('acme') // caches value 1 -> Acme Inc
|
|
60
|
+
src.getRows.mockClear()
|
|
61
|
+
expect(await lookup.labelFor(1)).toBe('Acme Inc')
|
|
62
|
+
expect(src.getRows).not.toHaveBeenCalled()
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('returns null for an empty value and the key itself when unresolved', async () => {
|
|
66
|
+
const lookup = createRelationLookup({ source: source(), schema, labelField: 'name' })
|
|
67
|
+
expect(await lookup.labelFor('')).toBeNull()
|
|
68
|
+
expect(await lookup.labelFor(999)).toBe('999')
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('honors an explicit valueField over the schema id', async () => {
|
|
72
|
+
const lookup = createRelationLookup({ source: source(), labelField: 'name', valueField: 'name' })
|
|
73
|
+
const opts = await lookup.search('glob')
|
|
74
|
+
expect(opts[0]).toMatchObject({ value: 'Globex', label: 'Globex' })
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
describe('labelsFor (batch)', () => {
|
|
78
|
+
it('resolves many keys in a single request (no N+1), deduping', async () => {
|
|
79
|
+
const src = source()
|
|
80
|
+
const lookup = createRelationLookup({ source: src, schema, labelField: 'name' })
|
|
81
|
+
const map = await lookup.labelsFor([1, 2, 2, 3, null, ''])
|
|
82
|
+
expect(map.get('1')).toBe('Acme Inc')
|
|
83
|
+
expect(map.get('2')).toBe('Globex')
|
|
84
|
+
expect(map.get('3')).toBe('Initech')
|
|
85
|
+
expect(src.getRows).toHaveBeenCalledTimes(1) // one query for all misses
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('serves cached keys without a request, and maps unresolved keys to themselves', async () => {
|
|
89
|
+
const src = source()
|
|
90
|
+
const lookup = createRelationLookup({ source: src, schema, labelField: 'name' })
|
|
91
|
+
await lookup.labelsFor([1]) // warm the cache
|
|
92
|
+
src.getRows.mockClear()
|
|
93
|
+
const map = await lookup.labelsFor([1, 999])
|
|
94
|
+
expect(map.get('1')).toBe('Acme Inc') // cached
|
|
95
|
+
expect(map.get('999')).toBe('999') // unresolved -> itself
|
|
96
|
+
expect(src.getRows).toHaveBeenCalledTimes(1) // only the miss (999)
|
|
97
|
+
})
|
|
98
|
+
})
|
|
99
|
+
})
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createRelationLookup - powers a foreign-key "lookup" field: search the related
|
|
3
|
+
* entity for options, and resolve a stored key back to its human label. It runs
|
|
4
|
+
* over the SAME `ServerDataSource` contract as everything else, so the related
|
|
5
|
+
* options can come from Supabase, REST, SQL, or in-memory - whatever backs the
|
|
6
|
+
* related table.
|
|
7
|
+
*
|
|
8
|
+
* const companyLookup = createRelationLookup({
|
|
9
|
+
* source: companiesSource, // the related entity's ServerDataSource
|
|
10
|
+
* schema: companiesSchema, // resolves the related primary key
|
|
11
|
+
* labelField: 'name', // what the user sees
|
|
12
|
+
* })
|
|
13
|
+
* await companyLookup.search('acme') // -> [{ value: '12', label: 'Acme Inc' }, ...]
|
|
14
|
+
* await companyLookup.labelFor('12') // -> 'Acme Inc'
|
|
15
|
+
*
|
|
16
|
+
* Pass it to `<SvGridEditPanel lookups={{ companyId: companyLookup }} />` and the
|
|
17
|
+
* `companyId` relation field renders a searchable picker instead of a raw input.
|
|
18
|
+
*/
|
|
19
|
+
import type { RowData, ServerDataSource, ServerRequest } from '@svgrid/grid'
|
|
20
|
+
import { resolveIdField, type EntitySchema } from '../schema'
|
|
21
|
+
|
|
22
|
+
export type RelationOption = { value: string; label: string; row: RowData }
|
|
23
|
+
|
|
24
|
+
export type RelationLookup = {
|
|
25
|
+
/** Search the related entity (global search); returns a page of options. */
|
|
26
|
+
search(query: string): Promise<RelationOption[]>
|
|
27
|
+
/** Resolve a stored key to its label (cached). Returns the key itself if not found. */
|
|
28
|
+
labelFor(value: unknown): Promise<string | null>
|
|
29
|
+
/**
|
|
30
|
+
* Resolve many keys at once (cached), fetching only the misses in a SINGLE
|
|
31
|
+
* request (a set / `IN` filter) - avoids the N+1 of calling `labelFor` per
|
|
32
|
+
* row. Returns a `value -> label` map (unresolved keys map to themselves).
|
|
33
|
+
*/
|
|
34
|
+
labelsFor(values: ReadonlyArray<unknown>): Promise<Map<string, string>>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type RelationLookupConfig<TRelated extends RowData> = {
|
|
38
|
+
/** The related entity's read source (only `getRows` is used). */
|
|
39
|
+
source: Pick<ServerDataSource<TRelated>, 'getRows'>
|
|
40
|
+
/** Field on the related row shown to the user. */
|
|
41
|
+
labelField: string
|
|
42
|
+
/** Related primary-key field. Default: resolved from `schema`, else `'id'`. */
|
|
43
|
+
valueField?: string
|
|
44
|
+
/** Related schema, used to resolve the key when `valueField` is omitted. */
|
|
45
|
+
schema?: EntitySchema<TRelated>
|
|
46
|
+
/** Options fetched per search. Default 20. */
|
|
47
|
+
pageSize?: number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createRelationLookup<TRelated extends RowData>(
|
|
51
|
+
config: RelationLookupConfig<TRelated>,
|
|
52
|
+
): RelationLookup {
|
|
53
|
+
const pageSize = config.pageSize ?? 20
|
|
54
|
+
const valueField = config.valueField ?? (config.schema ? resolveIdField(config.schema) : 'id')
|
|
55
|
+
const { labelField, source } = config
|
|
56
|
+
const cache = new Map<string, string>() // value -> label
|
|
57
|
+
|
|
58
|
+
const toOption = (row: RowData): RelationOption => {
|
|
59
|
+
const value = String(row[valueField] ?? '')
|
|
60
|
+
const label = String(row[labelField] ?? value)
|
|
61
|
+
cache.set(value, label)
|
|
62
|
+
return { value, label, row }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const request = (over: Partial<ServerRequest>): ServerRequest => ({
|
|
66
|
+
startRow: 0,
|
|
67
|
+
endRow: pageSize,
|
|
68
|
+
pageIndex: 0,
|
|
69
|
+
pageSize,
|
|
70
|
+
sortModel: [],
|
|
71
|
+
filterModel: {},
|
|
72
|
+
...over,
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
async search(query: string): Promise<RelationOption[]> {
|
|
77
|
+
const term = query.trim()
|
|
78
|
+
const { rows } = await source.getRows(request({ filterModel: term ? { global: term } : {} }))
|
|
79
|
+
return rows.map((r) => toOption(r as RowData))
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
async labelFor(value: unknown): Promise<string | null> {
|
|
83
|
+
if (value == null || value === '') return null
|
|
84
|
+
const key = String(value)
|
|
85
|
+
const cached = cache.get(key)
|
|
86
|
+
if (cached != null) return cached
|
|
87
|
+
const { rows } = await source.getRows(
|
|
88
|
+
request({
|
|
89
|
+
endRow: 1,
|
|
90
|
+
pageSize: 1,
|
|
91
|
+
filterModel: { columns: { [valueField]: { operator: 'equals', value: key } } },
|
|
92
|
+
}),
|
|
93
|
+
)
|
|
94
|
+
const row = rows[0] as RowData | undefined
|
|
95
|
+
return row ? toOption(row).label : key
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
async labelsFor(values: ReadonlyArray<unknown>): Promise<Map<string, string>> {
|
|
99
|
+
const result = new Map<string, string>()
|
|
100
|
+
const missing: string[] = []
|
|
101
|
+
for (const v of values) {
|
|
102
|
+
if (v == null || v === '') continue
|
|
103
|
+
const key = String(v)
|
|
104
|
+
if (result.has(key)) continue
|
|
105
|
+
const cached = cache.get(key)
|
|
106
|
+
if (cached != null) result.set(key, cached)
|
|
107
|
+
else if (!missing.includes(key)) missing.push(key)
|
|
108
|
+
}
|
|
109
|
+
if (missing.length > 0) {
|
|
110
|
+
// One request for every miss: a set (`IN`) filter on the key field.
|
|
111
|
+
const { rows } = await source.getRows(
|
|
112
|
+
request({
|
|
113
|
+
endRow: missing.length,
|
|
114
|
+
pageSize: missing.length,
|
|
115
|
+
filterModel: { columns: { [valueField]: { operator: 'in', value: '', selectedValues: missing } } },
|
|
116
|
+
}),
|
|
117
|
+
)
|
|
118
|
+
for (const row of rows) {
|
|
119
|
+
const opt = toOption(row as RowData)
|
|
120
|
+
result.set(opt.value, opt.label)
|
|
121
|
+
}
|
|
122
|
+
// Anything still unresolved maps to the key itself.
|
|
123
|
+
for (const key of missing) if (!result.has(key)) result.set(key, key)
|
|
124
|
+
}
|
|
125
|
+
return result
|
|
126
|
+
},
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import type { ServerRequest } from '@svgrid/grid'
|
|
3
|
+
import { createRestDataSource } from './rest'
|
|
4
|
+
import { offsetLimitAdapter, dummyJsonAdapter, jsonServerAdapter } from './rest-adapters'
|
|
5
|
+
|
|
6
|
+
type Row = { id: string; name: string }
|
|
7
|
+
|
|
8
|
+
function jsonResponse(body: unknown, opts: { status?: number; headers?: Record<string, string> } = {}) {
|
|
9
|
+
const status = opts.status ?? 200
|
|
10
|
+
const headers = opts.headers ?? {}
|
|
11
|
+
return {
|
|
12
|
+
ok: status >= 200 && status < 300,
|
|
13
|
+
status,
|
|
14
|
+
statusText: 'OK',
|
|
15
|
+
headers: { get: (k: string) => headers[k.toLowerCase()] ?? null },
|
|
16
|
+
json: async () => body,
|
|
17
|
+
} as unknown as Response
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function mockFetch(handler: (url: string) => Response) {
|
|
21
|
+
const calls: string[] = []
|
|
22
|
+
const fetch = (async (url: string | URL) => {
|
|
23
|
+
calls.push(String(url))
|
|
24
|
+
return handler(String(url))
|
|
25
|
+
}) as unknown as typeof globalThis.fetch
|
|
26
|
+
return { fetch, calls }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const req = (p: Partial<ServerRequest>): ServerRequest => ({
|
|
30
|
+
startRow: 0, endRow: 10, pageIndex: 0, pageSize: 10, sortModel: [], filterModel: {}, ...p,
|
|
31
|
+
})
|
|
32
|
+
const paramsOf = (url: string) => new URLSearchParams(url.split('?')[1])
|
|
33
|
+
|
|
34
|
+
describe('dummyJsonAdapter', () => {
|
|
35
|
+
it('maps paging to skip/limit, sort to sortBy/order, and reads products/total', async () => {
|
|
36
|
+
const { fetch, calls } = mockFetch(() =>
|
|
37
|
+
jsonResponse({ products: [{ id: '1', name: 'Phone' }], total: 194, skip: 20, limit: 10 }),
|
|
38
|
+
)
|
|
39
|
+
const src = createRestDataSource<Row>({ url: 'https://dummyjson.com/products', fetch, ...dummyJsonAdapter<Row>() })
|
|
40
|
+
const out = await src.getRows(req({ startRow: 20, endRow: 30, sortModel: [{ id: 'price', desc: true }] }))
|
|
41
|
+
const p = paramsOf(calls[0]!)
|
|
42
|
+
expect(p.get('skip')).toBe('20')
|
|
43
|
+
expect(p.get('limit')).toBe('10')
|
|
44
|
+
expect(p.get('sortBy')).toBe('price')
|
|
45
|
+
expect(p.get('order')).toBe('desc')
|
|
46
|
+
expect(out).toEqual({ rows: [{ id: '1', name: 'Phone' }], rowCount: 194 })
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('reads a non-default collection key (e.g. users)', async () => {
|
|
50
|
+
const { fetch } = mockFetch(() => jsonResponse({ users: [{ id: '7', name: 'Ada' }], total: 30 }))
|
|
51
|
+
const src = createRestDataSource<Row>({ url: 'https://dummyjson.com/users', fetch, ...dummyJsonAdapter<Row>('users') })
|
|
52
|
+
expect(await src.getRows(req({}))).toEqual({ rows: [{ id: '7', name: 'Ada' }], rowCount: 30 })
|
|
53
|
+
})
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
describe('jsonServerAdapter', () => {
|
|
57
|
+
it('maps paging to _start/_limit, multi-sort to _sort/_order, total from X-Total-Count', async () => {
|
|
58
|
+
const { fetch, calls } = mockFetch(() =>
|
|
59
|
+
jsonResponse([{ id: '1', name: 'Ada' }], { headers: { 'x-total-count': '240' } }),
|
|
60
|
+
)
|
|
61
|
+
const src = createRestDataSource<Row>({ url: 'https://x.test/posts', fetch, ...jsonServerAdapter<Row>() })
|
|
62
|
+
const out = await src.getRows(
|
|
63
|
+
req({ startRow: 0, endRow: 25, sortModel: [{ id: 'title', desc: false }, { id: 'views', desc: true }] }),
|
|
64
|
+
)
|
|
65
|
+
const p = paramsOf(calls[0]!)
|
|
66
|
+
expect(p.get('_start')).toBe('0')
|
|
67
|
+
expect(p.get('_limit')).toBe('25')
|
|
68
|
+
expect(p.get('_sort')).toBe('title,views')
|
|
69
|
+
expect(p.get('_order')).toBe('asc,desc')
|
|
70
|
+
expect(out).toEqual({ rows: [{ id: '1', name: 'Ada' }], rowCount: 240 })
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('falls back to array length when no X-Total-Count header', async () => {
|
|
74
|
+
const { fetch } = mockFetch(() => jsonResponse([{ id: '1', name: 'A' }, { id: '2', name: 'B' }]))
|
|
75
|
+
const src = createRestDataSource<Row>({ url: 'https://x.test/posts', fetch, ...jsonServerAdapter<Row>() })
|
|
76
|
+
expect((await src.getRows(req({}))).rowCount).toBe(2)
|
|
77
|
+
})
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
describe('offsetLimitAdapter', () => {
|
|
81
|
+
it('is fully configurable and sends the search term under the named param', async () => {
|
|
82
|
+
const { fetch, calls } = mockFetch(() => jsonResponse({ data: [{ id: '1', name: 'x' }], count: 3 }))
|
|
83
|
+
const src = createRestDataSource<Row>({
|
|
84
|
+
url: 'https://x.test/items',
|
|
85
|
+
fetch,
|
|
86
|
+
...offsetLimitAdapter<Row>({ offsetParam: 'from', limitParam: 'size', searchParam: 'q', rowsKey: 'data', totalKey: 'count' }),
|
|
87
|
+
})
|
|
88
|
+
const out = await src.getRows(req({ startRow: 5, endRow: 15, filterModel: { global: 'ada', columns: {} } }))
|
|
89
|
+
const p = paramsOf(calls[0]!)
|
|
90
|
+
expect(p.get('from')).toBe('5')
|
|
91
|
+
expect(p.get('size')).toBe('10')
|
|
92
|
+
expect(p.get('q')).toBe('ada')
|
|
93
|
+
expect(out).toEqual({ rows: [{ id: '1', name: 'x' }], rowCount: 3 })
|
|
94
|
+
})
|
|
95
|
+
})
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire-format adapters for `createRestDataSource`. A public / third-party API
|
|
3
|
+
* rarely speaks our default `offset&limit&sort` dialect - it uses `skip`, or
|
|
4
|
+
* `page`, or `_start`, and wraps its rows under `products` / `data` / a bare
|
|
5
|
+
* array with an `X-Total-Count` header. An adapter is just the `{ buildQuery,
|
|
6
|
+
* parse }` pair that teaches the REST source that dialect:
|
|
7
|
+
*
|
|
8
|
+
* createRestDataSource({ url: 'https://dummyjson.com/products',
|
|
9
|
+
* ...dummyJsonAdapter() })
|
|
10
|
+
*
|
|
11
|
+
* `offsetLimitAdapter` is the configurable base; `dummyJsonAdapter` and
|
|
12
|
+
* `jsonServerAdapter` are ready-made presets for two very common shapes.
|
|
13
|
+
*/
|
|
14
|
+
import type { RowData, ServerRequest, ServerResult } from '@svgrid/grid'
|
|
15
|
+
import type { RestDataSourceConfig } from './rest'
|
|
16
|
+
import { normalizeFilters } from './filters'
|
|
17
|
+
|
|
18
|
+
/** The parts of a REST config that describe a backend's wire format. */
|
|
19
|
+
export type RestAdapter<TData extends RowData> = Required<
|
|
20
|
+
Pick<RestDataSourceConfig<TData>, 'buildQuery' | 'parse'>
|
|
21
|
+
>
|
|
22
|
+
|
|
23
|
+
const pick = (body: unknown, keys: string[]): unknown => {
|
|
24
|
+
const b = (body ?? {}) as Record<string, unknown>
|
|
25
|
+
for (const k of keys) if (b[k] != null) return b[k]
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type OffsetLimitOptions = {
|
|
30
|
+
/** Query param for the first-row offset (default `offset`). */
|
|
31
|
+
offsetParam?: string
|
|
32
|
+
/** Query param for the page size (default `limit`). */
|
|
33
|
+
limitParam?: string
|
|
34
|
+
/** If set, single-column sort emits `<sortByParam>=<col>` + `<orderParam>=asc|desc`. */
|
|
35
|
+
sortByParam?: string
|
|
36
|
+
orderParam?: string
|
|
37
|
+
/** If set, the global search term is sent as `<searchParam>=<term>`. */
|
|
38
|
+
searchParam?: string
|
|
39
|
+
/** Response key holding the row array (tried in order; falls back to `data`/`rows`/`items`). */
|
|
40
|
+
rowsKey?: string
|
|
41
|
+
/** Response key holding the total count (tried in order; falls back to `total`/`count`). */
|
|
42
|
+
totalKey?: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The `?offset=..&limit=..` family (Supabase-ish REST, DummyJSON with `skip`,
|
|
47
|
+
* many hand-rolled APIs). Configure the param names + response keys once.
|
|
48
|
+
*/
|
|
49
|
+
export function offsetLimitAdapter<TData extends RowData>(opts: OffsetLimitOptions = {}): RestAdapter<TData> {
|
|
50
|
+
const offsetParam = opts.offsetParam ?? 'offset'
|
|
51
|
+
const limitParam = opts.limitParam ?? 'limit'
|
|
52
|
+
const rowsKeys = [opts.rowsKey, 'data', 'rows', 'items'].filter(Boolean) as string[]
|
|
53
|
+
const totalKeys = [opts.totalKey, 'total', 'count', 'rowCount'].filter(Boolean) as string[]
|
|
54
|
+
return {
|
|
55
|
+
buildQuery(request: ServerRequest): Record<string, string> {
|
|
56
|
+
const params: Record<string, string> = {
|
|
57
|
+
[offsetParam]: String(request.startRow),
|
|
58
|
+
[limitParam]: String(request.endRow - request.startRow),
|
|
59
|
+
}
|
|
60
|
+
const first = request.sortModel[0]
|
|
61
|
+
if (opts.sortByParam && first) {
|
|
62
|
+
params[opts.sortByParam] = first.id
|
|
63
|
+
if (opts.orderParam) params[opts.orderParam] = first.desc ? 'desc' : 'asc'
|
|
64
|
+
}
|
|
65
|
+
if (opts.searchParam) {
|
|
66
|
+
const { search } = normalizeFilters(request.filterModel)
|
|
67
|
+
if (search) params[opts.searchParam] = search
|
|
68
|
+
}
|
|
69
|
+
return params
|
|
70
|
+
},
|
|
71
|
+
parse(body: unknown): ServerResult<TData> {
|
|
72
|
+
const rows = (pick(body, rowsKeys) ?? []) as TData[]
|
|
73
|
+
const total = pick(body, totalKeys)
|
|
74
|
+
return { rows, rowCount: total != null ? Number(total) : rows.length }
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* DummyJSON (`https://dummyjson.com/<collection>`): `skip`/`limit` paging,
|
|
81
|
+
* `sortBy`/`order` sort, rows under `products`* + a `total` field.
|
|
82
|
+
* (*`rowsKey` defaults to `products`; pass one for `users`, `posts`, etc.)
|
|
83
|
+
*/
|
|
84
|
+
export function dummyJsonAdapter<TData extends RowData>(rowsKey = 'products'): RestAdapter<TData> {
|
|
85
|
+
return offsetLimitAdapter<TData>({
|
|
86
|
+
offsetParam: 'skip',
|
|
87
|
+
limitParam: 'limit',
|
|
88
|
+
sortByParam: 'sortBy',
|
|
89
|
+
orderParam: 'order',
|
|
90
|
+
rowsKey,
|
|
91
|
+
totalKey: 'total',
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* `json-server` / JSONPlaceholder: `_start`/`_limit` paging, `_sort`/`_order`
|
|
97
|
+
* multi-column sort, a bare JSON array with the total in `X-Total-Count`.
|
|
98
|
+
*/
|
|
99
|
+
export function jsonServerAdapter<TData extends RowData>(): RestAdapter<TData> {
|
|
100
|
+
return {
|
|
101
|
+
buildQuery(request: ServerRequest): Record<string, string> {
|
|
102
|
+
const params: Record<string, string> = {
|
|
103
|
+
_start: String(request.startRow),
|
|
104
|
+
_limit: String(request.endRow - request.startRow),
|
|
105
|
+
}
|
|
106
|
+
if (request.sortModel.length) {
|
|
107
|
+
params._sort = request.sortModel.map((s) => s.id).join(',')
|
|
108
|
+
params._order = request.sortModel.map((s) => (s.desc ? 'desc' : 'asc')).join(',')
|
|
109
|
+
}
|
|
110
|
+
const { search } = normalizeFilters(request.filterModel)
|
|
111
|
+
if (search) params.q = search
|
|
112
|
+
return params
|
|
113
|
+
},
|
|
114
|
+
parse(body: unknown, response: Response): ServerResult<TData> {
|
|
115
|
+
const rows = Array.isArray(body) ? (body as TData[]) : []
|
|
116
|
+
const header = response.headers.get('x-total-count')
|
|
117
|
+
return { rows, rowCount: header != null ? Number(header) : rows.length }
|
|
118
|
+
},
|
|
119
|
+
}
|
|
120
|
+
}
|