@axium/client 0.39.7 → 0.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/styles.css +11 -1
- package/dist/cli/cache.js +11 -4
- package/dist/cli/index.js +6 -9
- package/dist/locales.d.ts +1 -28
- package/dist/locales.js +3 -81
- package/dist/requests.d.ts +4 -0
- package/dist/requests.js +11 -1
- package/dist/socket.d.ts +5 -0
- package/dist/socket.js +17 -0
- package/dist/sync.d.ts +7 -1
- package/dist/sync.js +8 -1
- package/dist/uploads.js +2 -7
- package/dist/web/locales.js +5 -6
- package/lib/ConfirmDialog.svelte +25 -0
- package/lib/ZodForm.svelte +2 -2
- package/lib/ZodInput.svelte +122 -11
- package/lib/dialogs.ts +16 -0
- package/lib/reactive/sync.svelte.ts +8 -4
- package/package.json +3 -1
package/assets/styles.css
CHANGED
|
@@ -106,13 +106,23 @@ option:hover {
|
|
|
106
106
|
background-color: var(--bg-alt);
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
code,
|
|
110
109
|
pre {
|
|
111
110
|
background-color: var(--bg-menu);
|
|
112
111
|
padding: 1em;
|
|
113
112
|
border-radius: 0.5em;
|
|
114
113
|
}
|
|
115
114
|
|
|
115
|
+
code {
|
|
116
|
+
background-color: var(--bg-menu);
|
|
117
|
+
padding: 0.1em 0.35em;
|
|
118
|
+
border-radius: 0.3em;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
pre code {
|
|
122
|
+
padding: 0;
|
|
123
|
+
background-color: transparent;
|
|
124
|
+
}
|
|
125
|
+
|
|
116
126
|
details {
|
|
117
127
|
& > summary {
|
|
118
128
|
list-style: none;
|
package/dist/cli/cache.js
CHANGED
|
@@ -5,7 +5,7 @@ import { homedir } from 'node:os';
|
|
|
5
5
|
import { dirname, join, resolve } from 'node:path/posix';
|
|
6
6
|
import * as z from 'zod';
|
|
7
7
|
import { CacheData } from '../cache.js';
|
|
8
|
-
import { fetchAPI } from '../requests.js';
|
|
8
|
+
import { fetchAPI, NetworkError } from '../requests.js';
|
|
9
9
|
import { applyDiff, onSync } from '../sync.js';
|
|
10
10
|
import { apiUserCache, getCurrentSession } from '../user.js';
|
|
11
11
|
export const dir = join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'axium');
|
|
@@ -131,9 +131,16 @@ export function load() {
|
|
|
131
131
|
persistAPI(apiUserCache, 'users.json');
|
|
132
132
|
}
|
|
133
133
|
export async function update(force = false) {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
await handle.
|
|
134
|
+
try {
|
|
135
|
+
for (const handle of handles) {
|
|
136
|
+
if (force || !(await handle.isValid()))
|
|
137
|
+
await handle.update();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch (e) {
|
|
141
|
+
if (!(e instanceof NetworkError))
|
|
142
|
+
throw e;
|
|
143
|
+
io.warn(e.message + ', using cached data');
|
|
137
144
|
}
|
|
138
145
|
}
|
|
139
146
|
export function clear() {
|
package/dist/cli/index.js
CHANGED
|
@@ -13,7 +13,7 @@ import { bytes as formatBytes } from 'utilium/format';
|
|
|
13
13
|
import * as z from 'zod';
|
|
14
14
|
import $pkg from '../../package.json' with { type: 'json' };
|
|
15
15
|
import { prefix, useUserAgent } from '../requests.js';
|
|
16
|
-
import { connect as connectSocket } from '../socket.js';
|
|
16
|
+
import { connect as connectSocket, onConnect } from '../socket.js';
|
|
17
17
|
import { logout } from '../user.js';
|
|
18
18
|
import { clientUA, login } from './auth.js';
|
|
19
19
|
import * as cache from './cache.js';
|
|
@@ -78,15 +78,12 @@ program
|
|
|
78
78
|
.option('--no-socket', 'do not open a socket connection to the server')
|
|
79
79
|
.option('--insecure', 'allow connecting to a server with an untrusted (e.g. self-signed) TLS certificate', false)
|
|
80
80
|
.action(async (opt) => {
|
|
81
|
+
if (opt.socket && config.token) {
|
|
82
|
+
onConnect(() => void cache.sync.update().catch(e => io.error('Failed to update sync cache:', io.errorText(e))));
|
|
83
|
+
connectSocket({ rejectUnauthorized: !opt.insecure }).catch(e => io.warn('Could not connect to the server:', io.errorText(e)));
|
|
84
|
+
}
|
|
81
85
|
for (const plugin of plugins.values())
|
|
82
|
-
await plugin._client?.run?.();
|
|
83
|
-
if (!opt.socket || !config.token)
|
|
84
|
-
return;
|
|
85
|
-
// Hold a socket connection to the server for the lifetime of the daemon.
|
|
86
|
-
const socket = await connectSocket({ rejectUnauthorized: !opt.insecure });
|
|
87
|
-
const catchUp = () => cache.sync.update().catch(e => io.error('Failed to update sync cache:', io.errorText(e)));
|
|
88
|
-
await catchUp();
|
|
89
|
-
socket.io.on('reconnect', catchUp);
|
|
86
|
+
await (plugin._client?.daemon ?? plugin._client?.run)?.();
|
|
90
87
|
});
|
|
91
88
|
const axcPlugin = createPluginCommand('client', program, {
|
|
92
89
|
safe,
|
package/dist/locales.d.ts
CHANGED
|
@@ -1,28 +1 @@
|
|
|
1
|
-
|
|
2
|
-
/**
|
|
3
|
-
* Current locale
|
|
4
|
-
*/
|
|
5
|
-
export declare let currentLocale: string;
|
|
6
|
-
export declare function countryName(code: string): string | undefined;
|
|
7
|
-
export declare function dateField(name: string): string | undefined;
|
|
8
|
-
export declare function conjoin(list: Iterable<string>): string;
|
|
9
|
-
export declare function disjoin(list: Iterable<string>): string;
|
|
10
|
-
export declare let currentMonthNames: string[];
|
|
11
|
-
export interface ReplacementOptions {
|
|
12
|
-
$default?: string;
|
|
13
|
-
/** Whether to treat the replacement as HTML */
|
|
14
|
-
$html?: boolean;
|
|
15
|
-
}
|
|
16
|
-
type Replacements<K extends string> = ReplacementOptions & (K extends LocaleKey ? LocaleKeys[K & LocaleKey] : Record<string, LocaleValue>);
|
|
17
|
-
type ReplacementsArgs<K extends string> = {} extends Replacements<K> ? [replacements?: Replacements<K>] : [replacements: Replacements<K>];
|
|
18
|
-
export declare function useLocale(newLocale: string): void;
|
|
19
|
-
export declare function escape(text: string): string;
|
|
20
|
-
/**
|
|
21
|
-
* Get localized text for a given translation key
|
|
22
|
-
* @example
|
|
23
|
-
* ```ts
|
|
24
|
-
* text(`example.translation.key.${dynamicPart}`, { a: 1, b: 2 });
|
|
25
|
-
* ```
|
|
26
|
-
*/
|
|
27
|
-
export declare function text<const K extends string = LocaleKey>(key: K, ...args: ReplacementsArgs<K>): string;
|
|
28
|
-
export {};
|
|
1
|
+
export { conjoin, countryName, dateField, disjoin, escape, text, type ReplacementOptions } from '@james-pre/locales';
|
package/dist/locales.js
CHANGED
|
@@ -1,82 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { error, warn } from 'ioium';
|
|
1
|
+
import * as locales from '@james-pre/locales';
|
|
3
2
|
import en from '../locales/en.json' with { type: 'json' };
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
let currentLoaded;
|
|
7
|
-
/**
|
|
8
|
-
* Current locale
|
|
9
|
-
*/
|
|
10
|
-
export let currentLocale = 'en';
|
|
11
|
-
let currentRegionNames;
|
|
12
|
-
export function countryName(code) {
|
|
13
|
-
return currentRegionNames.of(code);
|
|
14
|
-
}
|
|
15
|
-
let currentDateFields;
|
|
16
|
-
export function dateField(name) {
|
|
17
|
-
return currentDateFields.of(name);
|
|
18
|
-
}
|
|
19
|
-
let currentConjunction;
|
|
20
|
-
export function conjoin(list) {
|
|
21
|
-
return currentConjunction.format(list);
|
|
22
|
-
}
|
|
23
|
-
let currentDisjunction;
|
|
24
|
-
export function disjoin(list) {
|
|
25
|
-
return currentDisjunction.format(list);
|
|
26
|
-
}
|
|
27
|
-
export let currentMonthNames;
|
|
28
|
-
export function useLocale(newLocale) {
|
|
29
|
-
if (!loadedLocales[newLocale])
|
|
30
|
-
throw new Error('Locale is not available: ' + newLocale);
|
|
31
|
-
currentLocale = newLocale;
|
|
32
|
-
currentLoaded = loadedLocales[newLocale];
|
|
33
|
-
currentRegionNames = new Intl.DisplayNames(newLocale, { type: 'region' });
|
|
34
|
-
currentDateFields = new Intl.DisplayNames(newLocale, { type: 'dateTimeField' });
|
|
35
|
-
currentConjunction = new Intl.ListFormat(newLocale, { style: 'long', type: 'conjunction' });
|
|
36
|
-
currentDisjunction = new Intl.ListFormat(newLocale, { style: 'long', type: 'disjunction' });
|
|
37
|
-
const formatter = new Intl.DateTimeFormat(newLocale, { month: 'long' });
|
|
38
|
-
currentMonthNames = Array.from({ length: 12 }, (_, monthIndex) => formatter.format(new Date(Date.UTC(2000, monthIndex + 1, 1))));
|
|
39
|
-
}
|
|
40
|
-
useLocale('en');
|
|
41
|
-
const localeReplacement = /\{(\w+)\}/g;
|
|
42
|
-
const escapePattern = /[&<>"']/g;
|
|
43
|
-
const escapes = {
|
|
44
|
-
'&': '&',
|
|
45
|
-
'<': '<',
|
|
46
|
-
'>': '>',
|
|
47
|
-
'"': '"',
|
|
48
|
-
"'": ''',
|
|
49
|
-
};
|
|
50
|
-
export function escape(text) {
|
|
51
|
-
return text.replaceAll(escapePattern, ch => escapes[ch]);
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Get localized text for a given translation key
|
|
55
|
-
* @example
|
|
56
|
-
* ```ts
|
|
57
|
-
* text(`example.translation.key.${dynamicPart}`, { a: 1, b: 2 });
|
|
58
|
-
* ```
|
|
59
|
-
*/
|
|
60
|
-
export function text(key, ...args) {
|
|
61
|
-
const values = Object.assign(Object.create(null), args[0]);
|
|
62
|
-
let text = getByString(currentLoaded, key) || values.$default;
|
|
63
|
-
if (!text && currentLocale != 'en') {
|
|
64
|
-
warn(`Missing translation in ${currentLocale}: ` + key);
|
|
65
|
-
text = getByString(en, key);
|
|
66
|
-
}
|
|
67
|
-
if (!text) {
|
|
68
|
-
error('Missing translation for key: ' + key);
|
|
69
|
-
text = `?${key}?`;
|
|
70
|
-
}
|
|
71
|
-
if (typeof text == 'object') {
|
|
72
|
-
error('Invalid translation key: ' + key);
|
|
73
|
-
text = values.$default || `!${key}!`;
|
|
74
|
-
}
|
|
75
|
-
return text.replaceAll(localeReplacement, (_, name) => {
|
|
76
|
-
if (!Object.hasOwn(values, name)) {
|
|
77
|
-
console.error(new Error(`Missing replacement value for ${key}: ${name}`));
|
|
78
|
-
values[name] = `<missing: ${name}>`;
|
|
79
|
-
}
|
|
80
|
-
return values.$html ? escape(String(values[name])) : String(values[name]);
|
|
81
|
-
});
|
|
82
|
-
}
|
|
3
|
+
locales.extend('en', en);
|
|
4
|
+
export { conjoin, countryName, dateField, disjoin, escape, text } from '@james-pre/locales';
|
package/dist/requests.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ export declare let token: string | null;
|
|
|
5
5
|
export declare function setToken(value: string | null): void;
|
|
6
6
|
export declare let prefix: string, origin: string;
|
|
7
7
|
export declare function setPrefix(value: string): void;
|
|
8
|
+
/** Thrown when a request gets no response, e.g. because the server is unreachable. */
|
|
9
|
+
export declare class NetworkError extends Error {
|
|
10
|
+
}
|
|
11
|
+
export declare function throwNetworkError(e: unknown): never;
|
|
8
12
|
export declare let userAgent: string | null;
|
|
9
13
|
/**
|
|
10
14
|
* Only for use on non-browser clients, e.g. Node.js
|
package/dist/requests.js
CHANGED
|
@@ -14,6 +14,16 @@ export function setPrefix(value) {
|
|
|
14
14
|
prefix = value;
|
|
15
15
|
origin = new URL(prefix, origin).origin;
|
|
16
16
|
}
|
|
17
|
+
/** Thrown when a request gets no response, e.g. because the server is unreachable. */
|
|
18
|
+
export class NetworkError extends Error {
|
|
19
|
+
}
|
|
20
|
+
export function throwNetworkError(e) {
|
|
21
|
+
if (!(e instanceof TypeError))
|
|
22
|
+
throw e;
|
|
23
|
+
const cause = e.cause;
|
|
24
|
+
const reason = (cause && (errorText(cause) || cause.code)) || e.message;
|
|
25
|
+
throw new NetworkError(`Could not reach ${origin}: ${reason}`, { cause: e });
|
|
26
|
+
}
|
|
17
27
|
export let userAgent = null;
|
|
18
28
|
/**
|
|
19
29
|
* Only for use on non-browser clients, e.g. Node.js
|
|
@@ -62,7 +72,7 @@ export async function fetchAPI(method, endpoint, data, ...params) {
|
|
|
62
72
|
}
|
|
63
73
|
url += '?' + search.toString();
|
|
64
74
|
}
|
|
65
|
-
const response = await fetch(url, options);
|
|
75
|
+
const response = await fetch(url, options).catch(throwNetworkError);
|
|
66
76
|
if (!response.headers.get('Content-Type')?.includes('application/json')) {
|
|
67
77
|
throw new Error(`Unexpected response type: ${response.headers.get('Content-Type')}`);
|
|
68
78
|
}
|
package/dist/socket.d.ts
CHANGED
|
@@ -4,6 +4,11 @@ import type { ManagerOptions, Socket as PlainSocket, SocketOptions } from 'socke
|
|
|
4
4
|
export interface Socket extends PlainSocket<ServerToClientEvents, ClientToServerEvents> {
|
|
5
5
|
}
|
|
6
6
|
export declare function addListener<T extends keyof ServerToClient & string>(event: T, listener: ServerToClientEvents[T]): void;
|
|
7
|
+
/**
|
|
8
|
+
* Run a listener whenever the socket connects, including reconnections.
|
|
9
|
+
* @returns a function that removes the listener
|
|
10
|
+
*/
|
|
11
|
+
export declare function onConnect(listener: () => void): () => void;
|
|
7
12
|
export interface ConnectOptions extends Partial<ManagerOptions & SocketOptions> {
|
|
8
13
|
}
|
|
9
14
|
export declare let socket: Socket | null;
|
package/dist/socket.js
CHANGED
|
@@ -11,6 +11,15 @@ export function addListener(event, listener) {
|
|
|
11
11
|
listeners.add(entry);
|
|
12
12
|
socket?.on(...entry);
|
|
13
13
|
}
|
|
14
|
+
const connectListeners = new Set();
|
|
15
|
+
/**
|
|
16
|
+
* Run a listener whenever the socket connects, including reconnections.
|
|
17
|
+
* @returns a function that removes the listener
|
|
18
|
+
*/
|
|
19
|
+
export function onConnect(listener) {
|
|
20
|
+
connectListeners.add(listener);
|
|
21
|
+
return () => connectListeners.delete(listener);
|
|
22
|
+
}
|
|
14
23
|
export let socket = null;
|
|
15
24
|
export function connect(opts) {
|
|
16
25
|
if (socket)
|
|
@@ -29,6 +38,14 @@ export function connect(opts) {
|
|
|
29
38
|
socket.on('connect', () => {
|
|
30
39
|
io.debug('socket: Connected as ' + socket.id);
|
|
31
40
|
resolve(socket);
|
|
41
|
+
for (const listener of connectListeners) {
|
|
42
|
+
try {
|
|
43
|
+
listener();
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
io.error('Socket connect listener failed: ' + io.errorText(e));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
32
49
|
});
|
|
33
50
|
socket.on('connect_error', err => {
|
|
34
51
|
if (!socket.active)
|
package/dist/sync.d.ts
CHANGED
|
@@ -6,6 +6,12 @@ export declare const schemas: Map<string, ZodObject<{
|
|
|
6
6
|
}, import("@axium/client").$strip>>;
|
|
7
7
|
/** Parse a synced object using the schema for its type. Objects without a schema are passed through. */
|
|
8
8
|
export declare function parseObject<T extends SyncDiffObject>(object: SyncDiffObject): T;
|
|
9
|
+
export interface ApplyDiffOptions<T> {
|
|
10
|
+
/** Only apply objects of this type */
|
|
11
|
+
type?: string;
|
|
12
|
+
/** Objects that don't match are removed instead of being added or updated */
|
|
13
|
+
filter?(this: void, object: T): boolean;
|
|
14
|
+
}
|
|
9
15
|
/**
|
|
10
16
|
* Apply a diff to some synced objects, updating them in place.
|
|
11
17
|
* Existing objects are updated in place, so bound references stay valid.
|
|
@@ -13,7 +19,7 @@ export declare function parseObject<T extends SyncDiffObject>(object: SyncDiffOb
|
|
|
13
19
|
export declare function applyDiff<T extends {
|
|
14
20
|
id: string;
|
|
15
21
|
$type?: string;
|
|
16
|
-
}>(objects: T[], diff: SyncDiff,
|
|
22
|
+
}>(objects: T[], diff: SyncDiff, options?: ApplyDiffOptions<T>): void;
|
|
17
23
|
/**
|
|
18
24
|
* Handle changes to synced objects pushed by the server.
|
|
19
25
|
* The socket must be connected for these to be received.
|
package/dist/sync.js
CHANGED
|
@@ -13,7 +13,8 @@ export function parseObject(object) {
|
|
|
13
13
|
* Apply a diff to some synced objects, updating them in place.
|
|
14
14
|
* Existing objects are updated in place, so bound references stay valid.
|
|
15
15
|
*/
|
|
16
|
-
export function applyDiff(objects, diff,
|
|
16
|
+
export function applyDiff(objects, diff, options = {}) {
|
|
17
|
+
const { type, filter } = options;
|
|
17
18
|
const deleted = new Set(diff.deleted);
|
|
18
19
|
for (let i = objects.length - 1; i >= 0; i--) {
|
|
19
20
|
if (deleted.has(objects[i].id))
|
|
@@ -32,6 +33,12 @@ export function applyDiff(objects, diff, type) {
|
|
|
32
33
|
continue;
|
|
33
34
|
}
|
|
34
35
|
const current = existing.get(incoming.id);
|
|
36
|
+
if (filter && !filter(object)) {
|
|
37
|
+
if (current)
|
|
38
|
+
objects.splice(objects.indexOf(current), 1);
|
|
39
|
+
existing.delete(incoming.id);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
35
42
|
if (!current) {
|
|
36
43
|
objects.push(object);
|
|
37
44
|
existing.set(object.id, object);
|
package/dist/uploads.js
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
import { warnOnce } from 'ioium';
|
|
2
|
-
import { token } from './requests.js';
|
|
3
|
-
function handleFetchFailed(e) {
|
|
4
|
-
if (!(e instanceof Error) || e.message != 'fetch failed')
|
|
5
|
-
throw e;
|
|
6
|
-
throw 'fetch failed: ' + String(e.cause);
|
|
7
|
-
}
|
|
2
|
+
import { throwNetworkError, token } from './requests.js';
|
|
8
3
|
async function handleError(response) {
|
|
9
4
|
if (response.headers.get('Content-Type')?.trim() != 'application/json')
|
|
10
5
|
throw await response.text();
|
|
@@ -112,7 +107,7 @@ export async function uploadChunked(options) {
|
|
|
112
107
|
body,
|
|
113
108
|
signal,
|
|
114
109
|
...init,
|
|
115
|
-
}).catch(
|
|
110
|
+
}).catch(throwNetworkError);
|
|
116
111
|
if (!response.ok)
|
|
117
112
|
await handleError(response);
|
|
118
113
|
if (offset + chunkSize != itemSize && response.status != 204)
|
package/dist/web/locales.js
CHANGED
|
@@ -1,21 +1,20 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as locales from '@james-pre/locales';
|
|
2
2
|
import { debug, warn } from 'ioium';
|
|
3
|
-
import { currentLocale, useLocale } from '../locales.js';
|
|
4
3
|
import { origin } from '../requests.js';
|
|
5
4
|
/**
|
|
6
5
|
* Fetch the translations the server has for a language and start using them.
|
|
7
6
|
* The server resolves the language, so for example asking for `en-US` may give you `en`.
|
|
8
7
|
* @returns the locale that is now in use
|
|
9
8
|
*/
|
|
10
|
-
export async function loadLocale(language = globalThis.navigator?.language ||
|
|
9
|
+
export async function loadLocale(language = globalThis.navigator?.language || locales.current) {
|
|
11
10
|
const response = await fetch(new URL('/locales/' + encodeURIComponent(language), origin));
|
|
12
11
|
if (!response.ok) {
|
|
13
12
|
warn(`No translations for ${language}:`, response.headers.get('content-type') == 'application/json' ? (await response.json()).message : response.statusText);
|
|
14
|
-
return
|
|
13
|
+
return locales.current;
|
|
15
14
|
}
|
|
16
15
|
const resolved = response.headers.get('Content-Language') || language;
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
locales.extend(resolved, await response.json());
|
|
17
|
+
locales.use(resolved);
|
|
19
18
|
debug('Using locale: ' + resolved);
|
|
20
19
|
return resolved;
|
|
21
20
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import { text } from '@axium/client';
|
|
3
|
+
import FormDialog from './FormDialog.svelte';
|
|
4
|
+
|
|
5
|
+
const {
|
|
6
|
+
message,
|
|
7
|
+
confirmText = text('generic.ok'),
|
|
8
|
+
danger = false,
|
|
9
|
+
onclose,
|
|
10
|
+
}: {
|
|
11
|
+
message: string;
|
|
12
|
+
confirmText?: string;
|
|
13
|
+
danger?: boolean;
|
|
14
|
+
onclose(confirmed: boolean): void;
|
|
15
|
+
} = $props();
|
|
16
|
+
|
|
17
|
+
let dialog = $state<HTMLDialogElement>()!;
|
|
18
|
+
let confirmed = false;
|
|
19
|
+
|
|
20
|
+
$effect(() => dialog.showModal());
|
|
21
|
+
</script>
|
|
22
|
+
|
|
23
|
+
<FormDialog bind:dialog submitText={confirmText} submitDanger={danger} submit={() => (confirmed = true)} cancel={() => onclose(confirmed)}>
|
|
24
|
+
<p>{message}</p>
|
|
25
|
+
</FormDialog>
|
package/lib/ZodForm.svelte
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { type ReplacementOptions, text } from '@axium/client/locales';
|
|
3
|
-
import
|
|
3
|
+
import * as locales from '@james-pre/locales';
|
|
4
4
|
import type { ZodObject } from 'zod';
|
|
5
5
|
import ZodInput from './ZodInput.svelte';
|
|
6
6
|
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
let { rootValue = $bindable(), schema, labels, updateValue, idPrefix }: Props = $props();
|
|
16
16
|
|
|
17
|
-
const localeInfo =
|
|
17
|
+
const localeInfo = locales.zod.get(schema);
|
|
18
18
|
|
|
19
19
|
function subText(name: string, replacements?: ReplacementOptions & Record<string, any>): string | undefined {
|
|
20
20
|
if (!localeInfo?.prefix) return replacements?.$default || labels?.[name] || name;
|
package/lib/ZodInput.svelte
CHANGED
|
@@ -2,16 +2,16 @@
|
|
|
2
2
|
import { text, type ReplacementOptions } from '@axium/client';
|
|
3
3
|
import type { ZodPref } from '@axium/core';
|
|
4
4
|
import feature from '@axium/core/features';
|
|
5
|
-
import
|
|
5
|
+
import * as locales from '@james-pre/locales';
|
|
6
6
|
import type { HTMLInputAttributes } from 'svelte/elements';
|
|
7
7
|
import { getByString, pick, setByString } from 'utilium';
|
|
8
|
-
import { prettifyError } from 'zod';
|
|
8
|
+
import { prettifyError, type z } from 'zod';
|
|
9
9
|
import Icon from './Icon.svelte';
|
|
10
10
|
import ZodInput from './ZodInput.svelte';
|
|
11
11
|
|
|
12
12
|
interface Props {
|
|
13
13
|
idPrefix?: string;
|
|
14
|
-
localeInfo?:
|
|
14
|
+
localeInfo?: locales.ZodInfo;
|
|
15
15
|
rootValue: any;
|
|
16
16
|
path: string;
|
|
17
17
|
label?: string;
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
idPrefix,
|
|
38
38
|
updateValue,
|
|
39
39
|
noLabel,
|
|
40
|
-
localeInfo =
|
|
40
|
+
localeInfo = locales.zod.get(schema),
|
|
41
41
|
} = props;
|
|
42
42
|
|
|
43
43
|
const id = (idPrefix ? idPrefix + ':' : '') + path.replaceAll(' ', '_');
|
|
@@ -107,6 +107,41 @@
|
|
|
107
107
|
|
|
108
108
|
const oninput = onchange;
|
|
109
109
|
|
|
110
|
+
function isSchemaPart(part: unknown): part is z.core.$ZodType {
|
|
111
|
+
return typeof part == 'object' && part !== null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Splits a template literal into the values of its parts, using defaults when it does not match. */
|
|
115
|
+
function splitTemplate(parts: readonly unknown[], template: unknown): string[] {
|
|
116
|
+
const sources = parts.map((part, i) =>
|
|
117
|
+
isSchemaPart(part)
|
|
118
|
+
? `(?<part${i}>${part._zod.pattern?.source.replace(/^\^|\$$/g, '') ?? '.*'})`
|
|
119
|
+
: String(part).replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
|
|
120
|
+
);
|
|
121
|
+
const groups = typeof template == 'string' ? new RegExp('^' + sources.join('') + '$').exec(template)?.groups : undefined;
|
|
122
|
+
|
|
123
|
+
return parts.map((part, i) => {
|
|
124
|
+
if (!isSchemaPart(part)) return String(part);
|
|
125
|
+
return groups?.[`part${i}`] ?? (part._zod.def.type == 'literal' ? String([...(part._zod.values ?? [])][0]) : '');
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function setTemplatePart(
|
|
130
|
+
parts: readonly unknown[],
|
|
131
|
+
index: number,
|
|
132
|
+
event: Event & { currentTarget: HTMLInputElement | HTMLSelectElement }
|
|
133
|
+
) {
|
|
134
|
+
const values = splitTemplate(parts, value);
|
|
135
|
+
values[index] = event.currentTarget.value;
|
|
136
|
+
value = values.join('');
|
|
137
|
+
onchange(event);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function partText(part: z.core.$ZodType, literal: string): string {
|
|
141
|
+
const prefix = locales.zod.get(part)?.prefix;
|
|
142
|
+
return prefix ? text(`${prefix}.${literal}`, { $default: literal }) : literal;
|
|
143
|
+
}
|
|
144
|
+
|
|
110
145
|
/** Localize text for a given field in the current schema. */
|
|
111
146
|
function subText(name: string, replacements?: ReplacementOptions & Record<string, any>): string | undefined {
|
|
112
147
|
if (!localeInfo?.prefix) return replacements?.$default;
|
|
@@ -117,11 +152,11 @@
|
|
|
117
152
|
const placeholder = noLabel == 'placeholder' ? labelText : undefined;
|
|
118
153
|
|
|
119
154
|
/** Array element types that indicate the array should put elements on their own lines */
|
|
120
|
-
const largeArrayTypes = ['object', 'array', 'record', 'tuple'];
|
|
155
|
+
const largeArrayTypes = ['object', 'array', 'record', 'tuple', 'template_literal'];
|
|
121
156
|
</script>
|
|
122
157
|
|
|
123
158
|
{#snippet _in(rest: HTMLInputAttributes)}
|
|
124
|
-
<div class=
|
|
159
|
+
<div class={['ZodInput', noLabel && 'no-label']}>
|
|
125
160
|
{#if !noLabel}<label for={id}>{labelText}</label>{/if}
|
|
126
161
|
{#if error}<span class="ZodInput-error">{error}</span>{/if}
|
|
127
162
|
<input
|
|
@@ -148,7 +183,7 @@
|
|
|
148
183
|
{:else if schema.type == 'bigint'}
|
|
149
184
|
{@render _in({ type: 'number', min: Number(schema.minValue), max: Number(schema.maxValue), step: 1 })}
|
|
150
185
|
{:else if schema.type == 'boolean'}
|
|
151
|
-
<div class=
|
|
186
|
+
<div class={['ZodInput', noLabel && 'no-label']}>
|
|
152
187
|
{#if !noLabel}<label for="{id}:checkbox">{labelText}</label>{/if}
|
|
153
188
|
<input bind:checked={value} id="{id}:checkbox" type="checkbox" {onchange} required={!optional} {placeholder} />
|
|
154
189
|
<label for="{id}:checkbox" {id} class="checkbox">
|
|
@@ -173,7 +208,42 @@
|
|
|
173
208
|
</select>
|
|
174
209
|
</div>
|
|
175
210
|
{:else if schema.type == 'template_literal'}
|
|
176
|
-
|
|
211
|
+
{const parts = splitTemplate(schema.def.parts, value)}
|
|
212
|
+
<div class={['ZodInput', noLabel && 'no-label']}>
|
|
213
|
+
{#if !noLabel}<label for={id}>{labelText}</label>{/if}
|
|
214
|
+
{#if error}<span class="ZodInput-error">{error}</span>{/if}
|
|
215
|
+
<div class={['ZodInput-template', error && 'error']}>
|
|
216
|
+
{#each schema.def.parts as part, i}
|
|
217
|
+
{#if !isSchemaPart(part)}
|
|
218
|
+
<span>{part}</span>
|
|
219
|
+
{:else if part._zod.def.type == 'literal' && part._zod.values?.size == 1}
|
|
220
|
+
<span>{partText(part, parts[i])}</span>
|
|
221
|
+
{:else if part._zod.def.type == 'literal'}
|
|
222
|
+
<select
|
|
223
|
+
id={i ? undefined : id}
|
|
224
|
+
value={parts[i]}
|
|
225
|
+
onchange={e => setTemplatePart(schema.def.parts, i, e)}
|
|
226
|
+
disabled={readonly}
|
|
227
|
+
required={!optional}
|
|
228
|
+
>
|
|
229
|
+
{#each part._zod.values ?? [] as literal}
|
|
230
|
+
<option value={literal}>{partText(part, String(literal))}</option>
|
|
231
|
+
{/each}
|
|
232
|
+
</select>
|
|
233
|
+
{:else}
|
|
234
|
+
<input
|
|
235
|
+
type="text"
|
|
236
|
+
id={i ? undefined : id}
|
|
237
|
+
value={parts[i]}
|
|
238
|
+
onchange={e => setTemplatePart(schema.def.parts, i, e)}
|
|
239
|
+
oninput={e => setTemplatePart(schema.def.parts, i, e)}
|
|
240
|
+
{readonly}
|
|
241
|
+
required={!optional}
|
|
242
|
+
/>
|
|
243
|
+
{/if}
|
|
244
|
+
{/each}
|
|
245
|
+
</div>
|
|
246
|
+
</div>
|
|
177
247
|
{:else if schema.type == 'readonly'}
|
|
178
248
|
<ZodInput bind:rootValue {...props} {localeInfo} label={labelText} schema={schema.def.innerType} readonly />
|
|
179
249
|
{:else if schema.type == 'default'}
|
|
@@ -191,13 +261,14 @@
|
|
|
191
261
|
{:else if schema.type == 'nonoptional'}
|
|
192
262
|
<ZodInput bind:rootValue {...props} {localeInfo} label={labelText} schema={schema.def.innerType} optional={false} />
|
|
193
263
|
{:else if schema.type == 'array'}
|
|
194
|
-
<div class=
|
|
264
|
+
<div class={['ZodInput', noLabel && 'no-label']}>
|
|
195
265
|
{#if !noLabel}<label for={id}>{labelText}</label>{/if}
|
|
196
266
|
<div class={['ZodInput-array', largeArrayTypes.includes(schema.element.type) && 'large']}>
|
|
197
267
|
{#each value, i}
|
|
198
268
|
<div class="ZodInput-element">
|
|
199
269
|
<ZodInput bind:rootValue {updateValue} {idPrefix} path="{path}.{i}" schema={schema.element} noLabel={noLabel || true} />
|
|
200
270
|
<button
|
|
271
|
+
type="button"
|
|
201
272
|
onclick={e => {
|
|
202
273
|
value.splice(i, 1);
|
|
203
274
|
onchange(e);
|
|
@@ -207,7 +278,7 @@
|
|
|
207
278
|
</button>
|
|
208
279
|
</div>
|
|
209
280
|
{/each}
|
|
210
|
-
<button class="icon-text" onclick={() => value.push('')}>
|
|
281
|
+
<button type="button" class="icon-text" onclick={() => value.push('')}>
|
|
211
282
|
<Icon i="plus" --size="16px" />
|
|
212
283
|
{#if noLabel == 'placeholder'}
|
|
213
284
|
<span>{labelText}</span>
|
|
@@ -237,7 +308,7 @@
|
|
|
237
308
|
{/each}
|
|
238
309
|
</div>
|
|
239
310
|
{:else if schema.type == 'enum'}
|
|
240
|
-
<div class=
|
|
311
|
+
<div class={['ZodInput', noLabel && 'no-label']}>
|
|
241
312
|
{#if !noLabel}<label for={id}>{labelText}</label>{/if}
|
|
242
313
|
{#if error}<span class="ZodInput-error">{error}</span>{/if}
|
|
243
314
|
<select {id} {onchange} bind:value required={!optional}>
|
|
@@ -279,6 +350,39 @@
|
|
|
279
350
|
}
|
|
280
351
|
}
|
|
281
352
|
|
|
353
|
+
.ZodInput.no-label {
|
|
354
|
+
grid-template-columns: minmax(0, 1fr);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
.ZodInput-template {
|
|
358
|
+
display: flex;
|
|
359
|
+
align-items: center;
|
|
360
|
+
border-radius: 0.5em;
|
|
361
|
+
padding: 0.15em;
|
|
362
|
+
border: var(--border-accent);
|
|
363
|
+
background-color: var(--bg-normal);
|
|
364
|
+
anchor-name: --zod-input;
|
|
365
|
+
|
|
366
|
+
&.error {
|
|
367
|
+
border-color: var(--fg-error);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
> :where(select, input, span) {
|
|
371
|
+
border: none;
|
|
372
|
+
border-radius: 0;
|
|
373
|
+
anchor-name: none;
|
|
374
|
+
|
|
375
|
+
&:not(:last-child) {
|
|
376
|
+
border-right: var(--border-elevated);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
> input {
|
|
381
|
+
flex: 1;
|
|
382
|
+
min-width: 0;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
282
386
|
.ZodInput-element {
|
|
283
387
|
display: flex;
|
|
284
388
|
gap: 0.5em;
|
|
@@ -292,6 +396,8 @@
|
|
|
292
396
|
gap: 0.25em;
|
|
293
397
|
display: flex;
|
|
294
398
|
flex-direction: column;
|
|
399
|
+
flex: 1;
|
|
400
|
+
min-width: 0;
|
|
295
401
|
}
|
|
296
402
|
}
|
|
297
403
|
|
|
@@ -302,6 +408,11 @@
|
|
|
302
408
|
|
|
303
409
|
&.large {
|
|
304
410
|
flex-direction: column;
|
|
411
|
+
align-items: stretch;
|
|
412
|
+
|
|
413
|
+
> button {
|
|
414
|
+
align-self: flex-start;
|
|
415
|
+
}
|
|
305
416
|
}
|
|
306
417
|
}
|
|
307
418
|
|
package/lib/dialogs.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { mount, unmount } from 'svelte';
|
|
2
|
+
import ConfirmDialog from './ConfirmDialog.svelte';
|
|
3
|
+
|
|
4
|
+
export interface ConfirmOptions {
|
|
5
|
+
confirmText?: string;
|
|
6
|
+
danger?: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Show a modal dialog asking the user to confirm `message`, resolving to whether they did.
|
|
11
|
+
*/
|
|
12
|
+
export function confirm(message: string, options: ConfirmOptions = {}): Promise<boolean> {
|
|
13
|
+
const { promise, resolve } = Promise.withResolvers<boolean>();
|
|
14
|
+
const dialog = mount(ConfirmDialog, { target: document.body, props: { ...options, message, onclose: resolve } });
|
|
15
|
+
return promise.finally(() => unmount(dialog));
|
|
16
|
+
}
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import type { SyncDiff, SyncDiffObject } from '@axium/core';
|
|
2
2
|
import { hasActiveInput } from '@axium/client/web/utils';
|
|
3
|
-
import { applyDiff, onSync } from '@axium/client/sync';
|
|
3
|
+
import { applyDiff, onSync, type ApplyDiffOptions } from '@axium/client/sync';
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Keep a list of objects up to date with changes from the server.
|
|
7
|
+
* Pass a function to get the list if it can be replaced.
|
|
8
|
+
*/
|
|
9
|
+
export function syncObjects<T extends { id: string }>(objects: T[] | (() => T[]), options: ApplyDiffOptions<T> = {}) {
|
|
6
10
|
let deferred: SyncDiffObject[] = [];
|
|
7
11
|
|
|
8
12
|
function applySync(diff: SyncDiff): void {
|
|
@@ -11,7 +15,7 @@ export function syncObjects<T extends { id: string }>(objects: T[], type?: strin
|
|
|
11
15
|
|
|
12
16
|
deferred = typing ? updated : [];
|
|
13
17
|
|
|
14
|
-
applyDiff(objects, { ...diff, updated: typing ? [] : updated },
|
|
18
|
+
applyDiff(typeof objects == 'function' ? objects() : objects, { ...diff, updated: typing ? [] : updated }, options);
|
|
15
19
|
}
|
|
16
20
|
|
|
17
21
|
$effect(() => onSync(applySync));
|
|
@@ -38,7 +42,7 @@ export function syncObject<T extends { id: string }>(object: T, onDelete?: () =>
|
|
|
38
42
|
|
|
39
43
|
deferred = typing ? updated : [];
|
|
40
44
|
|
|
41
|
-
applyDiff([object], { ...diff, created: [], updated: typing ? [] : updated }, type);
|
|
45
|
+
applyDiff([object], { ...diff, created: [], updated: typing ? [] : updated }, { type });
|
|
42
46
|
}
|
|
43
47
|
|
|
44
48
|
$effect(() => onSync(applySync));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@axium/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.40.1",
|
|
4
4
|
"author": "James Prevett <jp@jamespre.dev>",
|
|
5
5
|
"funding": {
|
|
6
6
|
"type": "individual",
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"./components": "./lib/index.js",
|
|
39
39
|
"./components/*": "./lib/*.svelte",
|
|
40
40
|
"./toast": "./lib/toast.js",
|
|
41
|
+
"./dialogs": "./lib/dialogs.js",
|
|
41
42
|
"./attachments": "./lib/attachments/index.js",
|
|
42
43
|
"./reactive": "./lib/reactive/index.svelte.js",
|
|
43
44
|
"./styles/*": {
|
|
@@ -50,6 +51,7 @@
|
|
|
50
51
|
},
|
|
51
52
|
"peerDependencies": {
|
|
52
53
|
"@axium/core": ">=0.41.3",
|
|
54
|
+
"@james-pre/locales": "^1.0.0",
|
|
53
55
|
"ioium": "^1.7.0",
|
|
54
56
|
"semver": "^7.7.4",
|
|
55
57
|
"svelte": "^5.36.0",
|