@svadmin/core 0.66.3 → 0.69.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@svadmin/core",
3
- "version": "0.66.3",
3
+ "version": "0.69.2",
4
4
  "author": "zuohuadong",
5
5
  "repository": {
6
6
  "type": "git",
@@ -134,6 +134,10 @@
134
134
  "./admin-tool": {
135
135
  "types": "./src/admin-tool.ts",
136
136
  "default": "./src/admin-tool.ts"
137
+ },
138
+ "./contracts": {
139
+ "types": "./src/contracts.ts",
140
+ "default": "./src/contracts.ts"
137
141
  }
138
142
  },
139
143
  "bugs": {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Ably LiveProvider adapter.
3
+ *
4
+ * Pass an Ably Realtime client (or a compatible shape) so svadmin does not take
5
+ * a dependency on `ably`. One channel is opened per resource.
6
+ */
7
+ import type { LiveEvent, LiveProvider } from '../live.svelte';
8
+ import { createLiveSubscribers } from '../live-transport';
9
+ import { liveEventFrom } from './live-event';
10
+
11
+ export interface AblyMessage {
12
+ name?: string;
13
+ data?: unknown;
14
+ }
15
+
16
+ export interface AblyChannelLike {
17
+ subscribe(callback: (message: AblyMessage) => void): unknown;
18
+ unsubscribe?(callback: (message: AblyMessage) => void): void;
19
+ publish?(name: string, data: unknown): unknown;
20
+ }
21
+
22
+ export interface AblyClientLike {
23
+ channels: { get(name: string): AblyChannelLike };
24
+ }
25
+
26
+ export interface AblyAdapterOptions {
27
+ /** Channel name; defaults to the svadmin resource. */
28
+ channel?: (resource: string) => string;
29
+ }
30
+
31
+ export function createAblyLiveProvider(client: AblyClientLike, options: AblyAdapterOptions = {}): LiveProvider {
32
+ if (typeof client !== 'object' || client === null || typeof client.channels?.get !== 'function') {
33
+ throw new TypeError('Ably adapter requires a client with channels.get()');
34
+ }
35
+ const subscribers = createLiveSubscribers();
36
+ const channelName = options.channel ?? ((resource: string) => resource);
37
+
38
+ return {
39
+ subscribe: ({ resource, callback }) => {
40
+ const name = channelName(resource);
41
+ const channel = client.channels.get(name);
42
+ const entry = subscribers.add({ resource, callback });
43
+ const listener = (message: AblyMessage) => {
44
+ const event = liveEventFrom(message.data, resource, message.name);
45
+ if (event) subscribers.notify(event, () => true);
46
+ };
47
+ void channel.subscribe(listener);
48
+ return () => {
49
+ entry.remove();
50
+ channel.unsubscribe?.(listener);
51
+ };
52
+ },
53
+ publish: (event: LiveEvent) => {
54
+ const name = channelName(event.resource);
55
+ void client.channels.get(name).publish?.(event.type, event.payload);
56
+ },
57
+ };
58
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Cerbos PDP adapter for svadmin AccessControlProvider.
3
+ *
4
+ * Uses the Cerbos REST API (`POST /api/check/resources`). Browser checks remain
5
+ * UI hints; the backend must still enforce the same policy.
6
+ */
7
+ import type { AccessControlProvider, CanParams } from '../permissions.svelte';
8
+ import { definedOptions } from '../defined-options';
9
+ import { accessControlFailure, decodeCanResult, snapshotCanParams } from '../access-control-contract';
10
+
11
+ export interface CerbosPrincipal {
12
+ id: string;
13
+ roles?: string[];
14
+ attributes?: Record<string, unknown>;
15
+ }
16
+
17
+ export interface CerbosAdapterOptions {
18
+ /** Cerbos PDP origin, for example `https://cerbos.internal:3592`. */
19
+ endpoint: string;
20
+ principal: () => CerbosPrincipal | Promise<CerbosPrincipal>;
21
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
22
+ /** Defaults to the svadmin resource name. */
23
+ resourceKind?: (params: CanParams) => string;
24
+ /** Defaults to `params.params.id` or `*`. */
25
+ resourceId?: (params: CanParams) => string;
26
+ fetch?: typeof fetch;
27
+ providerOptions?: AccessControlProvider['options'];
28
+ }
29
+
30
+ interface CerbosResponse {
31
+ results?: Array<{
32
+ actions?: Record<string, string>;
33
+ isAllowed?: boolean;
34
+ meta?: { effectivePolicies?: unknown };
35
+ }>;
36
+ }
37
+
38
+ export function createCerbosAccessControl(options: CerbosAdapterOptions): AccessControlProvider {
39
+ const request = options.fetch ?? globalThis.fetch;
40
+ if (typeof request !== 'function') throw new TypeError('Cerbos adapter requires fetch');
41
+ const endpoint = options.endpoint.replace(/\/+$/, '');
42
+ if (!endpoint) throw new TypeError('Cerbos adapter requires an endpoint');
43
+
44
+ return {
45
+ can: async (input) => {
46
+ try {
47
+ const params = snapshotCanParams(input);
48
+ const principal = await options.principal();
49
+ const id = options.resourceId?.(params) ?? String(params.params?.id ?? '*');
50
+ const kind = options.resourceKind?.(params) ?? params.resource;
51
+ const headers: Record<string, string> = {
52
+ 'content-type': 'application/json',
53
+ ...(typeof options.headers === 'function' ? await options.headers() : options.headers ?? {}),
54
+ };
55
+ const response = await request(`${endpoint}/api/check/resources`, {
56
+ method: 'POST',
57
+ headers,
58
+ body: JSON.stringify({
59
+ requestId: typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : String(Date.now()),
60
+ principal: {
61
+ id: principal.id,
62
+ ...(principal.roles === undefined ? {} : { roles: principal.roles }),
63
+ ...(principal.attributes === undefined ? {} : { attr: principal.attributes }),
64
+ },
65
+ resources: [{
66
+ resource: {
67
+ kind,
68
+ id,
69
+ ...(params.meta === undefined ? {} : { attr: params.meta }),
70
+ },
71
+ actions: [params.action],
72
+ }],
73
+ }),
74
+ });
75
+ if (!response.ok) throw new Error(`Cerbos responded ${response.status}`);
76
+ const body = await response.json() as CerbosResponse;
77
+ const result = body.results?.[0];
78
+ if (!result) throw new Error('Cerbos returned no result');
79
+ const allowed = result.isAllowed === true || result.actions?.[params.action] === 'EFFECT_ALLOW';
80
+ return decodeCanResult({
81
+ can: allowed,
82
+ ...definedOptions({ reason: allowed ? undefined : `Cerbos denied ${params.action} on ${kind}` }),
83
+ });
84
+ } catch (cause) {
85
+ throw accessControlFailure(cause);
86
+ }
87
+ },
88
+ ...definedOptions({ options: options.providerOptions }),
89
+ };
90
+ }
91
+
92
+ export type CerbosOptions = CerbosAdapterOptions;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Firebase Realtime Database / Firestore LiveProvider adapter.
3
+ *
4
+ * Pass a transport that resolves a path and registers a listener, so svadmin
5
+ * does not depend on the Firebase SDK. Values are expected to look like
6
+ * `{ type: 'created' | 'updated' | 'deleted', payload }`.
7
+ */
8
+ import type { LiveEvent, LiveProvider } from '../live.svelte';
9
+ import { createLiveSubscribers } from '../live-transport';
10
+ import { liveEventFrom } from './live-event';
11
+
12
+ export interface FirebaseLiveTransport {
13
+ subscribe(path: string, callback: (value: unknown) => void, onError?: (error: unknown) => void): () => void;
14
+ publish?(path: string, value: unknown): unknown;
15
+ }
16
+
17
+ export interface FirebaseAdapterOptions {
18
+ /** Database path per resource; defaults to the resource name. */
19
+ path?: (resource: string) => string;
20
+ }
21
+
22
+ export function createFirebaseLiveProvider(transport: FirebaseLiveTransport, options: FirebaseAdapterOptions = {}): LiveProvider {
23
+ if (typeof transport !== 'object' || transport === null || typeof transport.subscribe !== 'function') {
24
+ throw new TypeError('Firebase adapter requires a subscribe() transport');
25
+ }
26
+ const subscribers = createLiveSubscribers();
27
+ const pathFor = options.path ?? ((resource: string) => resource);
28
+
29
+ return {
30
+ subscribe: ({ resource, callback, liveParams }) => {
31
+ const path = pathFor(resource);
32
+ const entry = subscribers.add({ resource, callback, ...(liveParams === undefined ? {} : { liveParams }) });
33
+ const dispose = transport.subscribe(path, (value) => {
34
+ const event = liveEventFrom(value, resource);
35
+ if (event) subscribers.notify(event, () => true);
36
+ });
37
+ return () => {
38
+ entry.remove();
39
+ dispose();
40
+ };
41
+ },
42
+ ...(typeof transport.publish === 'function' ? {
43
+ publish: (event: LiveEvent) => { void transport.publish?.(pathFor(event.resource), event); },
44
+ } : {}),
45
+ };
46
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * GraphQL subscriptions LiveProvider adapter.
3
+ *
4
+ * Pass a `subscribe` function backed by graphql-ws, Apollo, or urql; svadmin
5
+ * keeps the transport seam and validates every delivered event.
6
+ */
7
+ import type { LiveEvent, LiveProvider } from '../live.svelte';
8
+ import { createLiveSubscribers } from '../live-transport';
9
+ import { liveEventFrom } from './live-event';
10
+
11
+ export interface GraphQLSubscriptionTransport {
12
+ subscribe(
13
+ params: { resource: string; liveParams?: Record<string, unknown> },
14
+ callback: (value: unknown) => void,
15
+ onError?: (error: unknown) => void,
16
+ ): () => void;
17
+ publish?(event: LiveEvent): unknown;
18
+ }
19
+
20
+ export function createGraphQLSubscriptionLiveProvider(transport: GraphQLSubscriptionTransport): LiveProvider {
21
+ if (typeof transport !== 'object' || transport === null || typeof transport.subscribe !== 'function') {
22
+ throw new TypeError('GraphQL subscriptions adapter requires a subscribe() transport');
23
+ }
24
+ const subscribers = createLiveSubscribers();
25
+
26
+ return {
27
+ subscribe: ({ resource, callback, liveParams }) => {
28
+ const entry = subscribers.add({ resource, callback, ...(liveParams === undefined ? {} : { liveParams }) });
29
+ const dispose = transport.subscribe(
30
+ { resource, ...(liveParams === undefined ? {} : { liveParams }) },
31
+ (value) => {
32
+ const event = liveEventFrom(value, resource);
33
+ if (event) subscribers.notify(event, () => true);
34
+ },
35
+ );
36
+ return () => {
37
+ entry.remove();
38
+ dispose();
39
+ };
40
+ },
41
+ ...(typeof transport.publish === 'function' ? {
42
+ publish: (event: LiveEvent) => { void transport.publish?.(event); },
43
+ } : {}),
44
+ };
45
+ }
@@ -0,0 +1,21 @@
1
+ import { snapshotLiveEvent, type LiveEvent } from '../live-transport';
2
+
3
+ const types: Record<string, LiveEvent['type']> = {
4
+ created: 'INSERT', updated: 'UPDATE', deleted: 'DELETE',
5
+ insert: 'INSERT', update: 'UPDATE', delete: 'DELETE',
6
+ INSERT: 'INSERT', UPDATE: 'UPDATE', DELETE: 'DELETE',
7
+ };
8
+
9
+ export function isRecord(value: unknown): value is Record<string, unknown> {
10
+ return typeof value === 'object' && value !== null;
11
+ }
12
+
13
+ /** Normalize provider payloads that carry a type name and a payload object. */
14
+ export function liveEventFrom(value: unknown, resource: string, typeHint?: string): LiveEvent | undefined {
15
+ const hinted = typeHint ?? (isRecord(value) && typeof value['type'] === 'string' ? value['type'] : undefined);
16
+ const type = hinted === undefined ? undefined : types[hinted];
17
+ if (!type) return undefined;
18
+ const payload = isRecord(value) && 'payload' in value ? value['payload'] : value;
19
+ const target = isRecord(value) && typeof value['resource'] === 'string' ? value['resource'] : resource;
20
+ return snapshotLiveEvent({ type, resource: target, payload: isRecord(payload) ? payload : {} });
21
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Permit.io PDP adapter for svadmin AccessControlProvider.
3
+ *
4
+ * Uses Permit's v2 enforcement endpoint. Verify the response contract against
5
+ * your Permit deployment; browser checks are never authorization evidence.
6
+ */
7
+ import type { AccessControlProvider, CanParams } from '../permissions.svelte';
8
+ import { definedOptions } from '../defined-options';
9
+ import { accessControlFailure, decodeCanResult, snapshotCanParams } from '../access-control-contract';
10
+
11
+ export interface PermitAdapterOptions {
12
+ /** Permit API origin; defaults to `https://api.permit.io`. */
13
+ endpoint?: string;
14
+ token: string;
15
+ /** Permit user key for the signed-in subject. */
16
+ user: (params: CanParams) => string | Promise<string>;
17
+ /** Permit resource type; defaults to the svadmin resource name. */
18
+ resourceType?: (params: CanParams) => string;
19
+ /** Permit resource instance key; defaults to `params.params.id` when present. */
20
+ resourceKey?: (params: CanParams) => string | undefined;
21
+ /** Permit action; defaults to the svadmin action. */
22
+ action?: (params: CanParams) => string;
23
+ context?: (params: CanParams) => Record<string, unknown> | undefined;
24
+ tenant?: string;
25
+ fetch?: typeof fetch;
26
+ providerOptions?: AccessControlProvider['options'];
27
+ }
28
+
29
+ interface PermitResponse {
30
+ allow?: boolean;
31
+ result?: boolean;
32
+ reason?: string;
33
+ }
34
+
35
+ export function createPermitAccessControl(options: PermitAdapterOptions): AccessControlProvider {
36
+ const request = options.fetch ?? globalThis.fetch;
37
+ if (typeof request !== 'function') throw new TypeError('Permit adapter requires fetch');
38
+ if (!options.token) throw new TypeError('Permit adapter requires a token');
39
+ const endpoint = (options.endpoint ?? 'https://api.permit.io').replace(/\/+$/, '');
40
+
41
+ return {
42
+ can: async (input) => {
43
+ try {
44
+ const params = snapshotCanParams(input);
45
+ const type = options.resourceType?.(params) ?? params.resource;
46
+ const key = options.resourceKey?.(params) ?? (params.params?.id === undefined ? undefined : String(params.params.id));
47
+ const action = options.action?.(params) ?? params.action;
48
+ const context = options.context?.(params);
49
+ const response = await request(`${endpoint}/api/v2/enforcement/check`, {
50
+ method: 'POST',
51
+ headers: {
52
+ 'content-type': 'application/json',
53
+ authorization: `Bearer ${options.token}`,
54
+ },
55
+ body: JSON.stringify({
56
+ user: { key: await options.user(params) },
57
+ action,
58
+ resource: { type, ...(key === undefined ? {} : { key }) },
59
+ ...(context === undefined ? {} : { context }),
60
+ ...(options.tenant === undefined ? {} : { tenant: options.tenant }),
61
+ }),
62
+ });
63
+ if (!response.ok) throw new Error(`Permit responded ${response.status}`);
64
+ const body = await response.json() as PermitResponse;
65
+ const allowed = body.allow === true || body.result === true;
66
+ return decodeCanResult({
67
+ can: allowed,
68
+ ...definedOptions({ reason: body.reason ?? (allowed ? undefined : `Permit denied ${action} on ${type}`) }),
69
+ });
70
+ } catch (cause) {
71
+ throw accessControlFailure(cause);
72
+ }
73
+ },
74
+ ...definedOptions({ options: options.providerOptions }),
75
+ };
76
+ }
77
+
78
+ export type PermitOptions = PermitAdapterOptions;
@@ -0,0 +1,119 @@
1
+ import { createQuery } from '@tanstack/svelte-query';
2
+ import { captureAdminContext } from './context.svelte';
3
+ import { captureAuthLiveScope } from './auth-hooks.svelte';
4
+ import { auditWithProvider, writeAuditEntry, type AuditDraft, type AuditEntry } from './audit';
5
+ import type { AuditQueryParams } from './audit-contract';
6
+ import { definedOptions } from './defined-options';
7
+ import { HttpError } from './types';
8
+
9
+ export interface UseLogOptions {
10
+ /** 为 false 时不写入 provider,只调用本地 audit handler。 */
11
+ enabled?: boolean;
12
+ }
13
+
14
+ export interface UseLogMutation {
15
+ log: (params: AuditDraft) => Promise<void>;
16
+ logAsync: (params: AuditDraft) => Promise<void>;
17
+ mutate: (params: AuditDraft, options?: { onSuccess?: () => void; onError?: (error: unknown) => void }) => void;
18
+ mutateAsync: (params: AuditDraft) => Promise<void>;
19
+ readonly isLoading: boolean;
20
+ readonly isError: boolean;
21
+ readonly error: unknown;
22
+ }
23
+
24
+ /**
25
+ * 写一条自定义审计记录。
26
+ *
27
+ * 有 `auditLogProvider` 时等待 provider 回执;没有时退化为本地 handler,
28
+ * 与框架内部 mutation 审计保持同一份输入校验。
29
+ */
30
+ export function useLog(options: UseLogOptions = {}): UseLogMutation {
31
+ const context = captureAdminContext();
32
+ let pending = $state(0);
33
+ let error = $state<unknown>(null);
34
+
35
+ async function log(params: AuditDraft): Promise<void> {
36
+ if (options.enabled === false) return;
37
+ const provider = context.auditLogProvider;
38
+ pending++;
39
+ error = null;
40
+ try {
41
+ if (provider) await writeAuditEntry(params, provider);
42
+ else auditWithProvider(params, null);
43
+ } catch (cause) {
44
+ error = cause;
45
+ throw cause;
46
+ } finally {
47
+ pending--;
48
+ }
49
+ }
50
+
51
+ return {
52
+ log,
53
+ logAsync: log,
54
+ mutate(params, callbacks) {
55
+ void log(params).then(
56
+ () => callbacks?.onSuccess?.(),
57
+ (cause) => callbacks?.onError?.(cause),
58
+ );
59
+ },
60
+ mutateAsync: log,
61
+ get isLoading() { return pending > 0; },
62
+ get isError() { return error !== null; },
63
+ get error() { return error; },
64
+ };
65
+ }
66
+
67
+ export interface UseLogListOptions {
68
+ resource?: string;
69
+ action?: string;
70
+ meta?: Record<string, unknown>;
71
+ queryOptions?: { enabled?: boolean; staleTime?: number };
72
+ }
73
+
74
+ export interface UseLogListResult {
75
+ readonly data: AuditEntry[];
76
+ readonly isLoading: boolean;
77
+ readonly isError: boolean;
78
+ readonly error: unknown;
79
+ refetch: () => Promise<unknown>;
80
+ }
81
+
82
+ /**
83
+ * 读取审计记录列表。审计是追加写模型;查询结果不缓存跨租户/会话。
84
+ */
85
+ export function useLogList(options: UseLogListOptions = {}): UseLogListResult {
86
+ const context = captureAdminContext();
87
+ const authScope = captureAuthLiveScope(context.authProvider);
88
+ const tenant = context.tenantCacheKey?.__svadminTenant;
89
+ const enabled = options.queryOptions?.enabled !== false && context.auditLogProvider !== null;
90
+
91
+ const query = createQuery<AuditEntry[], unknown>(() => ({
92
+ queryKey: ['svadmin-audit-log-list', {
93
+ resource: options.resource ?? null,
94
+ action: options.action ?? null,
95
+ meta: options.meta ?? null,
96
+ tenant: tenant ?? null,
97
+ auth: authScope.cacheKey,
98
+ provider: context.auditLogProvider !== null,
99
+ }],
100
+ queryFn: async () => {
101
+ const provider = context.auditLogProvider;
102
+ if (!provider) throw new HttpError('Audit log provider unavailable', 400, undefined, { code: 'AUDIT_PROVIDER_REQUIRED' });
103
+ const params: AuditQueryParams = {
104
+ ...definedOptions({ resource: options.resource, action: options.action, meta: options.meta }),
105
+ };
106
+ return provider.get(params);
107
+ },
108
+ enabled,
109
+ staleTime: options.queryOptions?.staleTime ?? 0,
110
+ }));
111
+
112
+ return {
113
+ get data() { return query.data ?? []; },
114
+ get isLoading() { return query.isPending && enabled; },
115
+ get isError() { return query.isError; },
116
+ get error() { return query.error; },
117
+ refetch: () => query.refetch(),
118
+ };
119
+ }
@@ -27,6 +27,20 @@ type Redirect = 'list' | 'edit' | 'show' | false;
27
27
  type Values<S extends ContractSchemas, A extends ContractFormAction> = ContractFormValues<S, A>;
28
28
  type Draft<S extends ContractSchemas, A extends ContractFormAction> = ContractFormDraft<S, A>;
29
29
  type Field<S extends ContractSchemas, A extends ContractFormAction> = Extract<keyof Values<S, A>, string>;
30
+ export interface AutoSaveOptions {
31
+ enabled: boolean;
32
+ /** 停止输入后的等待时间,默认 1000ms。 */
33
+ debounce?: number;
34
+ }
35
+
36
+ export type AutoSaveStatus = 'idle' | 'saving' | 'saved' | 'error';
37
+
38
+ export interface AutoSaveState {
39
+ status: AutoSaveStatus;
40
+ data: ContractRecord<ContractSchemas> | null;
41
+ error: HttpError | null;
42
+ }
43
+
30
44
  interface FormOptions<S extends ContractSchemas, A extends ContractFormAction> {
31
45
  resource: ResourceContract<S>;
32
46
  action: A;
@@ -42,6 +56,8 @@ interface FormOptions<S extends ContractSchemas, A extends ContractFormAction> {
42
56
  /** 为 false 时不弹默认失败 toast。调用方已有表单内提示时使用。 */
43
57
  errorNotification?: NotificationConfig;
44
58
  warnWhenUnsavedChanges?: boolean;
59
+ /** 脏字段停止输入后自动保存;保存失败保留在 autoSave.error。 */
60
+ autoSave?: AutoSaveOptions;
45
61
  }
46
62
  export type ContractFormOptions<S extends ContractSchemas, A extends ContractFormAction> =
47
63
  FormOptions<S, A> & ([Values<NoInfer<S>, NoInfer<A>>] extends [never] ? never : unknown) &
@@ -122,6 +138,11 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
122
138
  let tainted = $state<Record<string, boolean>>({});
123
139
  let error = $state<HttpError | null>(null);
124
140
  let submitting = $state(false);
141
+ let autoSaveStatus = $state<AutoSaveStatus>('idle');
142
+ let autoSaveData = $state<ContractRecord<S> | null>(null);
143
+ let autoSaveError = $state<HttpError | null>(null);
144
+ let autoSaveRevision = 0;
145
+ let autoSaveFailedSignature: string | undefined;
125
146
  let hydratedKey = $state<string | undefined>();
126
147
  let active: { token: object; scope: Scope; promise: Promise<{ data: ContractRecord<S> }>; wasDispatched: () => boolean } | undefined;
127
148
  let latest: object | undefined;
@@ -245,6 +266,10 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
245
266
  error = null;
246
267
  errors = {};
247
268
  tainted = {};
269
+ autoSaveRevision++;
270
+ autoSaveStatus = 'idle';
271
+ autoSaveData = null;
272
+ autoSaveError = null;
248
273
  hydratedKey = undefined;
249
274
  values = snapshotContractFormDraft(options.resource, options.action, options.defaultValues ?? {});
250
275
  initial = snapshotContractFormDraft(options.resource, options.action, values);
@@ -290,12 +315,20 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
290
315
  if (settings.taint !== false) tainted = { ...tainted, ...Object.fromEntries(changed.map(key => [key, true])) };
291
316
  errors = Object.fromEntries(Object.entries(errors).filter(([key]) => !changed.includes(key)));
292
317
  error = null;
318
+ if (options.autoSave?.enabled) {
319
+ autoSaveFailedSignature = undefined;
320
+ if (autoSaveStatus !== 'saving') autoSaveStatus = 'idle';
321
+ }
293
322
  }
294
323
  function reset() {
295
324
  draftRevision = {};
325
+ autoSaveRevision++;
296
326
  active = undefined;
297
327
  latest = undefined;
298
328
  submitting = false;
329
+ autoSaveStatus = 'idle';
330
+ autoSaveData = null;
331
+ autoSaveError = null;
299
332
  if (!state.ok || !ready()) return;
300
333
  values = draft(state.scope, initial);
301
334
  tainted = {};
@@ -363,7 +396,12 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
363
396
  if (current() && !isTainted()) return context.navigate(path);
364
397
  }, undefined);
365
398
  }
366
- function submit(overrides: { redirect?: Redirect } = {}): Promise<{ data: ContractRecord<S> }> {
399
+ function submit(overrides: { redirect?: Redirect } = {}, internal: { autoSave?: boolean } = {}): Promise<{ data: ContractRecord<S> }> {
400
+ const autoSaving = internal.autoSave === true;
401
+ if (autoSaving) {
402
+ autoSaveStatus = 'saving';
403
+ autoSaveError = null;
404
+ }
367
405
  function joined(operation: NonNullable<typeof active>) {
368
406
  const current = () => isCurrent(operation.scope) && latest === operation.token;
369
407
  return operation.promise.then(result => {
@@ -388,6 +426,13 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
388
426
  const rejected = failure(cause);
389
427
  if (!active) latest = undefined;
390
428
  error = rejected;
429
+ if (autoSaving) {
430
+ autoSaveStatus = 'error';
431
+ autoSaveError = rejected;
432
+ autoSaveRevision++;
433
+ }
434
+ if (!autoSaving) notify(() => fireErrorNotification({ config: options.errorNotification, defaultMessage: i18n.t('common.operationFailed'), error: copyFailure(rejected),
435
+ resource: options.resource.name, ...definedOptions({ provider: context.notificationProvider }) }), undefined);
391
436
  notify(options.onMutationError, copyFailure(rejected));
392
437
  if (origin && !isCurrent(origin)) return Promise.reject(cancelled());
393
438
  return Promise.reject(copyFailure(rejected));
@@ -479,7 +524,11 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
479
524
  () => targetCurrent(target) && latest === token,
480
525
  () => clearAuthQueries(client, target.authProvider), target.authScope,
481
526
  () => mounted && latest !== token); }, undefined);
482
- if (current()) notify(() => fireErrorNotification({ config: options.errorNotification, defaultMessage: i18n.t('common.operationFailed'), error: copyFailure(failed.error),
527
+ if (current() && autoSaving) {
528
+ autoSaveStatus = 'error';
529
+ autoSaveError = failed.error;
530
+ }
531
+ if (current() && !autoSaving) notify(() => fireErrorNotification({ config: options.errorNotification, defaultMessage: i18n.t('common.operationFailed'), error: copyFailure(failed.error),
483
532
  resource: target.contract.name, ...definedOptions({ provider: target.notificationProvider }) }), undefined);
484
533
  if (current()) notify(onError, copyFailure(failed.error));
485
534
  throw failed.error;
@@ -497,10 +546,16 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
497
546
  values = draft(target, reconciled);
498
547
  initial = draft(target, persisted);
499
548
  tainted = Object.fromEntries(changed.map(key => [key, true]));
500
- notify(() => fireSuccessNotification({ config: undefined, defaultMessage: i18n.t(target.action === 'edit' ? 'common.updateSuccess' : 'common.createSuccess'),
501
- resource: target.contract.name, ...definedOptions({ provider: target.notificationProvider }) }), undefined);
549
+ if (autoSaving) {
550
+ autoSaveStatus = 'saved';
551
+ autoSaveData = record;
552
+ autoSaveError = null;
553
+ } else {
554
+ notify(() => fireSuccessNotification({ config: undefined, defaultMessage: i18n.t(target.action === 'edit' ? 'common.updateSuccess' : 'common.createSuccess'),
555
+ resource: target.contract.name, ...definedOptions({ provider: target.notificationProvider }) }), undefined);
556
+ }
502
557
  if (current()) notify(onSuccess, { data: parseContractRecord(target.contract, record) });
503
- if (current()) redirect(target, destination, resultId, current);
558
+ if (current() && !autoSaving) redirect(target, destination, resultId, current);
504
559
  if (!current()) throw cancelled(dispatched);
505
560
  return { data: parseContractRecord(target.contract, record) };
506
561
  }).finally(() => {
@@ -509,6 +564,34 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
509
564
  active = { token, scope: target, promise, wasDispatched: () => dispatched };
510
565
  return joined(active);
511
566
  }
567
+ $effect(() => {
568
+ const config = options.autoSave;
569
+ if (!config?.enabled) return;
570
+ // Track draft, submission and hydration without starting a write before the form is usable.
571
+ void values;
572
+ void tainted;
573
+ void submitting;
574
+ // Auto-save requires an existing record; create forms would keep creating duplicates.
575
+ if (!state.ok || !ready() || submitting || !isTainted() || state.scope.action !== 'edit') return;
576
+ const signature = JSON.stringify([values, tainted]);
577
+ if (autoSaveFailedSignature === signature) return;
578
+ const delay = config.debounce ?? 1000;
579
+ if (!Number.isFinite(delay) || delay < 0) return;
580
+ const revision = ++autoSaveRevision;
581
+ const timer = setTimeout(() => {
582
+ if (revision !== autoSaveRevision || autoSaveFailedSignature === signature ||
583
+ !state.ok || !ready() || submitting || !isTainted()) return;
584
+ void submit({ redirect: false }, { autoSave: true }).catch(() => { autoSaveFailedSignature = signature; });
585
+ }, delay);
586
+ return () => clearTimeout(timer);
587
+ });
588
+ function triggerAutoSave(): void {
589
+ if (!options.autoSave?.enabled || !state.ok || !ready() || submitting || !isTainted() || state.scope.action !== 'edit') return;
590
+ const signature = JSON.stringify([values, tainted]);
591
+ autoSaveFailedSignature = undefined;
592
+ autoSaveRevision++;
593
+ void submit({ redirect: false }, { autoSave: true }).catch(() => { autoSaveFailedSignature = signature; });
594
+ }
512
595
  $effect(() => {
513
596
  if (!(options.warnWhenUnsavedChanges ?? adminOptions.warnWhenUnsavedChanges) || !isTainted() || !enabled() || typeof window === 'undefined') return;
514
597
  const scope = state.ok ? state.scope : undefined;
@@ -524,7 +607,14 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
524
607
  return state.ok && isCurrent(state.scope) && hydratedKey === state.scope.key
525
608
  ? draft(state.scope, values) : snapshotContractFormDraft(options.resource, options.action, {});
526
609
  },
527
- setValues, setFieldValue, reset, submit, validateFields,
610
+ setValues, setFieldValue, reset, submit, validateFields, triggerAutoSave,
611
+ get autoSave(): AutoSaveState {
612
+ return {
613
+ status: options.autoSave?.enabled ? autoSaveStatus : 'idle',
614
+ data: autoSaveStatus === 'saved' ? (autoSaveData as ContractRecord<ContractSchemas> | null) : null,
615
+ error: autoSaveStatus === 'error' && autoSaveError ? copyFailure(autoSaveError) : null,
616
+ };
617
+ },
528
618
  get errors(): Readonly<Record<string, string>> { return ready() ? { ...errors } : {}; },
529
619
  setFieldError(field: Field<S, A> | '_root', message: string) {
530
620
  if (!ready()) return;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Runtime contract decoders shared with adapters.
3
+ *
4
+ * This subpath intentionally avoids the runes-backed core entry so adapters and
5
+ * non-Svelte tooling can validate provider results without loading app state.
6
+ */
7
+ export { decodeAuthAction, AuthMutationError } from './auth-mutation-contract';
8
+ export { decodeAuthCheck, decodeAuthErrorResult, decodeIdentity, AuthQueryError } from './auth-query-contract';
9
+ export { decodeCanResult, decodeCanResults } from './access-control-contract';
10
+ export { snapshotLiveEvent, decodeLiveMessage } from './live-transport';
11
+ export { decodeAuditEntry, decodeAuditEntries } from './audit-contract';
@@ -44,6 +44,40 @@ export function useOvertime(options?: OvertimeOptions) {
44
44
  };
45
45
  }
46
46
 
47
+ /**
48
+ * Refine-compatible alias for query-heavy callers.
49
+ *
50
+ * Accepts a query-like object or a loading getter and reports elapsed time while
51
+ * loading. `useOvertime` keeps the manual start/stop form for custom work.
52
+ */
53
+ export function useLoadingOvertime(
54
+ source?: (() => boolean) | { isLoading?: boolean; isPending?: boolean; isFetching?: boolean },
55
+ options?: OvertimeOptions,
56
+ ) {
57
+ const tracker=createOvertimeTracker(() => typeof source === 'function'
58
+ ? source()
59
+ : source?.isLoading === true || source?.isPending === true || source?.isFetching === true, options);
60
+ return {
61
+ get elapsedTime() { return tracker.elapsedTime; },
62
+ get overtime() { return tracker.elapsedTime; },
63
+ };
64
+ }
65
+
66
+ /** Set `document.title` for the lifetime of the calling component. */
67
+ export function useTitle(value: string | (() => string) | undefined, options?: { append?: string }) {
68
+ let previous: string | undefined;
69
+ $effect(() => {
70
+ if (typeof document === 'undefined') return;
71
+ const title = typeof value === 'function' ? value() : value;
72
+ if (title === undefined) return;
73
+ if (previous === undefined) previous = document.title;
74
+ document.title = options?.append === undefined ? title : `${title}${options.append}`;
75
+ return () => {
76
+ if (previous !== undefined) document.title = previous;
77
+ };
78
+ });
79
+ }
80
+
47
81
  // ─── useDataProvider ────────────────────────────────────────────────
48
82
 
49
83
  export function useDataProvider(): (dataProviderName?: string) => DataProvider {
@@ -513,6 +513,7 @@ const baseLocales: Record<string, Record<string, string>> = {
513
513
  'settings.accent.rose': '玫瑰色',
514
514
  'settings.accent.orange': '橙色',
515
515
  'settings.accent.violet': '紫罗兰色',
516
+ 'settings.accent.default': '默认',
516
517
  'settings.accent.stripe': '条纹',
517
518
  'settings.language': '语言',
518
519
  'settings.interface': '界面',
@@ -757,6 +758,7 @@ const baseLocales: Record<string, Record<string, string>> = {
757
758
  'task.invalidJson': '任务负载必须是合法 JSON',
758
759
  'task.submitSuccess': '任务提交成功',
759
760
  'task.submitFailed': '任务提交失败',
761
+ 'task.submitUnconfirmed': '提交结果未知,请刷新任务列表确认后再试。',
760
762
  'task.fetchFailed': '加载任务失败',
761
763
  'task.fetchListFailed': '加载任务列表失败',
762
764
  'task.actionFailed': '无法确认任务操作结果,请核对任务状态后再试。',
@@ -1433,6 +1435,7 @@ const baseLocales: Record<string, Record<string, string>> = {
1433
1435
  'settings.accent.rose': 'Rose',
1434
1436
  'settings.accent.orange': 'Orange',
1435
1437
  'settings.accent.violet': 'Violet',
1438
+ 'settings.accent.default': 'Default',
1436
1439
  'settings.accent.stripe': 'Stripe',
1437
1440
  'settings.language': 'Language',
1438
1441
  'settings.interface': 'Interface',
@@ -1677,6 +1680,7 @@ const baseLocales: Record<string, Record<string, string>> = {
1677
1680
  'task.invalidJson': 'Task payload must be valid JSON',
1678
1681
  'task.submitSuccess': 'Task submitted successfully',
1679
1682
  'task.submitFailed': 'Task submission failed',
1683
+ 'task.submitUnconfirmed': 'Submission result is unconfirmed. Refresh the task list before trying again.',
1680
1684
  'task.fetchFailed': 'Fetch task failed',
1681
1685
  'task.fetchListFailed': 'Fetch tasks failed',
1682
1686
  'task.actionFailed': 'Unable to confirm the task action. Check the task status before trying again.',
@@ -1848,9 +1852,10 @@ const baseLocales: Record<string, Record<string, string>> = {
1848
1852
  let locales = $state(structuredClone(baseLocales));
1849
1853
  const initialLocales = structuredClone(baseLocales);
1850
1854
 
1851
- /** Detect best locale from browser language */
1855
+ /** Detect best locale from browser language; server rendering always starts in English. */
1852
1856
  function detectLocale(): string {
1853
- if (typeof navigator === 'undefined') return 'en';
1857
+ // Node 22+ exposes a global navigator, so gate SSR on the browser window instead.
1858
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') return 'en';
1854
1859
  const browserLang = navigator.language || navigator.languages?.[0] || 'zh-CN';
1855
1860
  if (locales[browserLang]) return browserLang;
1856
1861
  const [prefix = browserLang] = browserLang.split('-');
package/src/index.ts CHANGED
@@ -56,8 +56,9 @@ export {
56
56
  useNavigation, useGo, useBack,
57
57
  useGetToPath, useLink,
58
58
  useResource,
59
- useModal,
60
- useOvertime,
59
+ useModal, useDrawer,
60
+ useOvertime, useLoadingOvertime,
61
+ useTitle,
61
62
  useNotification,
62
63
  useMenu, useBreadcrumb, useThemedLayoutContext,
63
64
  resetSidebarCollapsed,
@@ -110,6 +111,7 @@ export type { ContractUpdateParams as UseUpdateMutateParams } from './update-con
110
111
  export type { ContractDeleteOptions as UseDeleteOptions } from './delete-hooks.svelte';
111
112
  export type { ContractDeleteParams as UseDeleteMutateParams } from './delete-contract';
112
113
  export type { ContractFormAction, ContractFormDraft, ContractFormValues } from './resource-contract';
114
+ export type { AutoSaveOptions, AutoSaveState, AutoSaveStatus } from './contract-form.svelte';
113
115
  export type { ContractProjectionOptions } from './resource-contract';
114
116
  export type { ResourceContract, ContractSchemas, ContractRecord, ContractId, ContractInput } from './resource-contract';
115
117
  export type { ContractFilter, ContractSort } from './strict-hooks.svelte';
@@ -140,6 +142,12 @@ export type {
140
142
  PermissionSnapshot,
141
143
  } from './permission-catalog';
142
144
  export { useLive, useSubscription, usePublish } from './live.svelte';
145
+ export { createAblyLiveProvider } from './adapters/ably';
146
+ export type { AblyAdapterOptions, AblyChannelLike, AblyClientLike, AblyMessage } from './adapters/ably';
147
+ export { createFirebaseLiveProvider } from './adapters/firebase';
148
+ export type { FirebaseAdapterOptions, FirebaseLiveTransport } from './adapters/firebase';
149
+ export { createGraphQLSubscriptionLiveProvider } from './adapters/graphql-subscription';
150
+ export type { GraphQLSubscriptionTransport } from './adapters/graphql-subscription';
143
151
  export { toast, getToastQueue, consumeToastQueue, getPromiseQueue, consumePromiseQueue, getToasts, removeToast, resetToast } from './toast.svelte';
144
152
  export {
145
153
  notify,
@@ -158,6 +166,8 @@ export type { DateTimeValueMode, DateTimeDisambiguation } from './date-time';
158
166
  export { validateGantt, GANTT_LIMITS } from './gantt';
159
167
  export type { GanttTaskShape, GanttValidationError } from './gantt';
160
168
  export { audit, auditWithProvider, writeAuditEntry, recordMutationRollback, setAuditHandler, setAuditLogProvider, getAuditLogProvider, withValidatedAuditProvider, AuditError } from './audit';
169
+ export { useLog, useLogList } from './audit-hooks.svelte';
170
+ export type { UseLogOptions, UseLogMutation, UseLogListOptions, UseLogListResult } from './audit-hooks.svelte';
161
171
  export type { AuditLogProvider, AuditLogTransport, AuditCreateParams, AuditQueryParams, AuditDraft } from './audit';
162
172
  export { TaskError } from './task-contract';
163
173
  export { withValidatedTaskProvider } from './task-provider';
@@ -242,6 +252,10 @@ export { useCan } from './useCan';
242
252
  export type { UseCanOptions, UseCanResult } from './useCan';
243
253
  export { createCaslAccessControl } from './adapters/casl';
244
254
  export { createCasbinAccessControl } from './adapters/casbin';
255
+ export { createCerbosAccessControl } from './adapters/cerbos';
256
+ export type { CerbosAdapterOptions, CerbosOptions, CerbosPrincipal } from './adapters/cerbos';
257
+ export { createPermitAccessControl } from './adapters/permit';
258
+ export type { PermitAdapterOptions, PermitOptions } from './adapters/permit';
245
259
  export type { CasbinAdapterOptions } from './adapters/casbin';
246
260
  export { downloadData, toCsv, toJson, toXlsx, parseCSV } from './data-transfer.svelte';
247
261
  export { parseSpreadsheetClipboard, serializeSpreadsheetClipboard } from './spreadsheet-clipboard';
@@ -276,9 +290,11 @@ export {
276
290
  captureAuthLiveScope as captureAuthSession,
277
291
  } from './auth-hooks.svelte';
278
292
  export type { AuthNotificationOptions } from './auth-hooks.svelte';
279
- export { AuthQueryError, AuthErrorHandlingError } from './auth-query-contract';
280
- export type { AuthErrorHandlingResult } from './auth-query-contract';
281
- export { AuthMutationError } from './auth-mutation-contract';
293
+ export { AuthQueryError, AuthErrorHandlingError, decodeAuthCheck, decodeAuthErrorResult, decodeIdentity } from './auth-query-contract';
294
+ export type { AuthErrorHandlingResult, AuthErrorResult } from './auth-query-contract';
295
+ export { AuthMutationError, decodeAuthAction } from './auth-mutation-contract';
296
+ export { decodeCanResult } from './access-control-contract';
297
+ export { snapshotLiveEvent } from './live-transport';
282
298
  export { useResourceContract } from './resource-binding.svelte';
283
299
  export { PermissionHintsError } from './permission-hints-contract';
284
300
  export type { PermissionHints } from './permission-hints-contract';
@@ -99,6 +99,7 @@ export function useSubmitTask(options: UseSubmitTaskOptions={}) {
99
99
  const failureScopes = new WeakMap<Error, SubmissionScope>();
100
100
 
101
101
  const mutation=createMutation<TaskHandle,Error,UseSubmitTaskMutateParams>(() => ({
102
+ retry: false,
102
103
  mutationFn: async (params) => {
103
104
  const authProvider = adminContext.authProvider;
104
105
  const auth = captureAuthLiveScope(authProvider);
@@ -6,7 +6,7 @@ import { definedOptions } from './defined-options';
6
6
  // - 'dark-first': adds 'light' class for light mode (dark-first)
7
7
 
8
8
  export type ThemeMode='light'|'dark'|'system';
9
- export type ColorTheme='blue'|'green'|'rose'|'orange'|'violet'|'neutral'|'indigo'|'stripe';
9
+ export type ColorTheme='default'|'blue'|'green'|'rose'|'orange'|'violet'|'neutral'|'indigo'|'stripe';
10
10
 
11
11
  /** Controls how the theme class is applied to <html> */
12
12
  export type ThemeStrategy='standard'|'dark-first';
@@ -190,6 +190,29 @@ export const builtinPresets: Record<string,ColorPreset>=$state({
190
190
  '--chart-1': 'oklch(0.65 0.25 293)',
191
191
  },
192
192
  },
193
+ default: {
194
+ name: 'default',
195
+ label: 'Default',
196
+ color: '#165DFF',
197
+ light: {
198
+ '--primary': '#165DFF',
199
+ '--primary-foreground': '#FFFFFF',
200
+ '--ring': '#165DFF',
201
+ '--sidebar-primary': '#165DFF',
202
+ '--sidebar-primary-foreground': '#FFFFFF',
203
+ '--sidebar-ring': '#165DFF',
204
+ '--chart-1': '#165DFF',
205
+ },
206
+ dark: {
207
+ '--primary': '#3C7EFF',
208
+ '--primary-foreground': '#FFFFFF',
209
+ '--ring': '#3C7EFF',
210
+ '--sidebar-primary': '#3C7EFF',
211
+ '--sidebar-primary-foreground': '#FFFFFF',
212
+ '--sidebar-ring': '#3C7EFF',
213
+ '--chart-1': '#3C7EFF',
214
+ },
215
+ },
193
216
  stripe: {
194
217
  name: 'stripe',
195
218
  label: 'Stripe',
@@ -325,8 +348,8 @@ function readStoredTheme(): ThemeMode|undefined {
325
348
 
326
349
  function readStoredColorTheme(): ColorTheme {
327
350
  const stored=getStorage()?.getItem(COLOR_STORAGE_KEY);
328
- // Stripe is the product default; an existing persisted preset remains authoritative.
329
- return stored&&builtinPresets[stored]? stored as ColorTheme:'stripe';
351
+ // The built-in preset is the product default; an existing persisted preset remains authoritative.
352
+ return stored&&builtinPresets[stored]? stored as ColorTheme:'default';
330
353
  }
331
354
 
332
355
  function persistSelection(key: string,value: string): void {
@@ -422,11 +445,13 @@ function applyEffectiveTheme(): void {
422
445
  const configuredPreset=!colorSelectionOverridesConfig&&nextConfig.colorPreset
423
446
  ? resolvePreset(nextConfig.colorPreset)
424
447
  :undefined;
425
- const preset=configuredPreset??builtinPresets[selectedColorTheme];
448
+ // Unknown or retired preset ids normalize to the default preset so a stale
449
+ // persisted value never leaves the document with an unstyled theme id.
450
+ const preset=configuredPreset??builtinPresets[selectedColorTheme]??builtinPresets['default'];
426
451
 
427
452
  themeConfig=nextConfig;
428
453
  mode=nextMode;
429
- colorTheme=(preset?.name??selectedColorTheme) as ColorTheme;
454
+ colorTheme=(preset?.name??'default') as ColorTheme;
430
455
 
431
456
  if(typeof document==='undefined') return;
432
457
  clearAppliedArtifacts();
@@ -9,16 +9,79 @@ import { toast } from './toast.svelte';
9
9
  import { createSelectQuery as useSelectImpl, type UseSelectOptions } from './select-query.svelte';
10
10
  import { decodeBaseRecord } from './record-decoder';
11
11
 
12
- // ─── useModal ─────────────────────────────────────────────────
13
- export function useModal(options?: { defaultVisible?: boolean }) {
14
- let visible=$state(options?.defaultVisible??false);
12
+ // ─── Disclosure (useModal / useDrawer) ────────────────────────
13
+
14
+ export interface DisclosureOptions {
15
+ defaultVisible?: boolean;
16
+ /** 把可见状态同步到当前 URL 查询参数,便于刷新和前进/后退恢复。 */
17
+ syncWithLocation?: boolean;
18
+ /** URL 参数名;默认按 modal/drawer 区分。 */
19
+ param?: string;
20
+ }
21
+
22
+ function readDisclosureParam(param: string): boolean {
23
+ if (typeof window === 'undefined') return false;
24
+ const search = new URLSearchParams(window.location.search).get(param);
25
+ if (search !== null) return search === '1';
26
+ const hash = window.location.hash;
27
+ const query = hash.includes('?') ? hash.slice(hash.indexOf('?') + 1) : '';
28
+ return new URLSearchParams(query).get(param) === '1';
29
+ }
30
+
31
+ function writeDisclosureParam(param: string, visible: boolean): void {
32
+ if (typeof window === 'undefined') return;
33
+ const url = new URL(window.location.href);
34
+ const hash = url.hash;
35
+ const separator = hash.indexOf('?');
36
+ if (separator >= 0) {
37
+ const params = new URLSearchParams(hash.slice(separator + 1));
38
+ if (visible) params.set(param, '1'); else params.delete(param);
39
+ const query = params.toString();
40
+ url.hash = query ? `${hash.slice(0, separator)}?${query}` : hash.slice(0, separator);
41
+ } else {
42
+ if (visible) url.searchParams.set(param, '1'); else url.searchParams.delete(param);
43
+ }
44
+ window.history.replaceState(window.history.state, '', url.toString());
45
+ }
46
+
47
+ function useDisclosure(kind: 'modal' | 'drawer', options: DisclosureOptions = {}) {
48
+ const param = options.param ?? kind;
49
+ const sync = options.syncWithLocation === true;
50
+ let visible = $state(options.defaultVisible ?? (sync ? readDisclosureParam(param) : false));
51
+
52
+ if (sync && typeof window !== 'undefined') {
53
+ const update = () => { visible = readDisclosureParam(param); };
54
+ $effect(() => {
55
+ window.addEventListener('popstate', update);
56
+ window.addEventListener('hashchange', update);
57
+ return () => {
58
+ window.removeEventListener('popstate', update);
59
+ window.removeEventListener('hashchange', update);
60
+ };
61
+ });
62
+ }
63
+
64
+ function setVisible(next: boolean): void {
65
+ visible = next;
66
+ if (sync) writeDisclosureParam(param, next);
67
+ }
68
+
15
69
  return {
16
70
  get visible() { return visible; },
17
- show() { visible=true; },
18
- close() { visible=false; },
71
+ show() { setVisible(true); },
72
+ close() { setVisible(false); },
73
+ toggle() { setVisible(!visible); },
19
74
  };
20
75
  }
21
76
 
77
+ export function useModal(options?: DisclosureOptions) {
78
+ return useDisclosure('modal', options);
79
+ }
80
+
81
+ export function useDrawer(options?: DisclosureOptions) {
82
+ return useDisclosure('drawer', options);
83
+ }
84
+
22
85
  // ─── useMenu ──────────────────────────────────────────────────
23
86
 
24
87
  export interface MenuConfig {