@axium/client 0.42.1 → 0.43.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/assets/styles.css CHANGED
@@ -63,6 +63,10 @@ button:where(.reset) {
63
63
  &:hover {
64
64
  background-color: unset;
65
65
  }
66
+
67
+ &:disabled {
68
+ border: none;
69
+ }
66
70
  }
67
71
 
68
72
  input,
@@ -256,6 +260,7 @@ div.success {
256
260
  }
257
261
 
258
262
  :disabled,
263
+ :disabled + label.checkbox,
259
264
  .disabled {
260
265
  cursor: not-allowed;
261
266
  color: var(--fg-disabled);
package/dist/cache.js CHANGED
@@ -11,6 +11,15 @@ function isThenable(value) {
11
11
  return !!(value && typeof value == 'object' && 'then' in value && typeof value.then == 'function');
12
12
  }
13
13
  const kTimestamp = Symbol('kTimestamp');
14
+ function withTimestamp(value, timestamp = Date.now()) {
15
+ Object.defineProperty(value, kTimestamp, {
16
+ value: timestamp,
17
+ enumerable: false,
18
+ configurable: false,
19
+ writable: false,
20
+ });
21
+ return value;
22
+ }
14
23
  /**
15
24
  * Cache some arbitrary operation.
16
25
  * This is primarily intended for de-duplicating API requests
@@ -52,7 +61,7 @@ export class Cache {
52
61
  const [key] = this.items.entries().next().value;
53
62
  this.items.delete(key);
54
63
  }
55
- this.items.set(key, Object.assign(value, { [kTimestamp]: Date.now() }));
64
+ this.items.set(key, withTimestamp(value));
56
65
  this.onWrite?.(this.toJSON());
57
66
  }
58
67
  get(...keys) {
@@ -89,7 +98,7 @@ export class Cache {
89
98
  if (!this.valid($timestamp))
90
99
  continue;
91
100
  delete value.$timestamp;
92
- this.items.set(key, Object.assign(value, { [kTimestamp]: $timestamp }));
101
+ this.items.set(key, withTimestamp(value, $timestamp));
93
102
  }
94
103
  }
95
104
  toJSON() {
@@ -31,6 +31,7 @@ export declare const meta: Handle<z.ZodObject<{
31
31
  expires: z.ZodCoercedDate<unknown>;
32
32
  created: z.ZodCoercedDate<unknown>;
33
33
  elevated: z.ZodBoolean;
34
+ timezone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
34
35
  user: z.ZodObject<{
35
36
  id: z.ZodUUID;
36
37
  name: z.ZodString;
@@ -40,6 +41,7 @@ export declare const meta: Handle<z.ZodObject<{
40
41
  preferences: z.ZodLazy<z.ZodObject<{
41
42
  debug: z.ZodDefault<z.ZodBoolean>;
42
43
  theme: z.ZodDefault<z.ZodLiteral<"default" | "light" | "forest" | "midnight" | "beach" | "cherry" | "volcano">>;
44
+ time_zone: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<string>, z.ZodString]>>;
43
45
  }, z.core.$strip>>;
44
46
  roles: z.ZodArray<z.ZodString>;
45
47
  tags: z.ZodArray<z.ZodString>;
@@ -39,6 +39,7 @@ export declare function session(): {
39
39
  preferences: {
40
40
  debug: boolean;
41
41
  theme: "default" | "light" | "forest" | "midnight" | "beach" | "cherry" | "volcano";
42
+ time_zone?: string | undefined;
42
43
  };
43
44
  roles: string[];
44
45
  tags: string[];
@@ -49,4 +50,5 @@ export declare function session(): {
49
50
  emailVerified?: Date | null | undefined;
50
51
  };
51
52
  name?: string | null | undefined;
53
+ timezone?: string | null | undefined;
52
54
  };
@@ -1,6 +1,6 @@
1
1
  import type { APIParameters, Endpoint, RequestBody, Result } from '@axium/core/api';
2
2
  import { $API } from '@axium/core/api';
3
- import type { RequestMethod } from '@axium/core/requests';
3
+ import { type RequestMethod } from '@axium/core/requests';
4
4
  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;
@@ -14,4 +14,6 @@ export declare let userAgent: string | null;
14
14
  * Only for use on non-browser clients, e.g. Node.js
15
15
  */
16
16
  export declare function useUserAgent(ua: string | null): void;
17
+ /** Logs the warnings the server sent about a request */
18
+ export declare function logWarnings(response: Response): void;
17
19
  export declare function fetchAPI<const E extends Endpoint, const M extends keyof $API[E] & RequestMethod>(method: M, endpoint: E, data?: RequestBody<M, E>, ...params: APIParameters<E>): Promise<Result<M, E>>;
package/dist/requests.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { $API } from '@axium/core/api';
2
2
  import { errorText } from 'ioium';
3
+ import { decodeWarnings, warningsHeader } from '@axium/core/requests';
3
4
  import { prettifyError } from 'zod';
4
5
  // @ts-expect-error 2339
5
6
  BigInt.prototype.toJSON = function () {
@@ -31,6 +32,11 @@ export let userAgent = null;
31
32
  export function useUserAgent(ua) {
32
33
  userAgent = ua;
33
34
  }
35
+ /** Logs the warnings the server sent about a request */
36
+ export function logWarnings(response) {
37
+ for (const warning of decodeWarnings(response.headers.get(warningsHeader)))
38
+ console.warn('[API]', warning);
39
+ }
34
40
  export async function fetchAPI(method, endpoint, data, ...params) {
35
41
  const options = {
36
42
  method,
@@ -77,13 +83,9 @@ export async function fetchAPI(method, endpoint, data, ...params) {
77
83
  throw new Error(`Unexpected response type: ${response.headers.get('Content-Type')}`);
78
84
  }
79
85
  const json = await response.json().catch(() => ({ message: 'Unknown server error (invalid JSON response)' }));
86
+ logWarnings(response);
80
87
  if (!response.ok)
81
88
  throw Object.assign(new Error(json.message), { status: response.status });
82
- if (typeof json == 'object' && json != null && '_warnings' in json) {
83
- for (const warning of json._warnings)
84
- console.warn('[API]', warning);
85
- delete json._warnings;
86
- }
87
89
  if (!schema)
88
90
  return json;
89
91
  const Output = Array.isArray(schema) ? schema[1] : schema;
package/dist/socket.js CHANGED
@@ -7,7 +7,8 @@ export function addListener(event, listener) {
7
7
  const schema = ServerToClient[event];
8
8
  if (!schema)
9
9
  io.warn(`Attaching a listener to the '${event}' socket event without schema`);
10
- const entry = [event, schema ? schema.implement(listener) : listener];
10
+ const run = (...args) => void listener(...args);
11
+ const entry = [event, schema ? schema.implement(run) : listener];
11
12
  listeners.add(entry);
12
13
  socket?.on(...entry);
13
14
  }
package/dist/user.js CHANGED
@@ -28,14 +28,18 @@ export async function loginWithAutofill() {
28
28
  return await fetchAPI('POST', 'login', response);
29
29
  }
30
30
  let _currentSession = null;
31
+ /** Fetches the current session, reporting this device's time zone */
32
+ function fetchSession() {
33
+ return fetchAPI('POST', 'session', { timezone: Intl.DateTimeFormat().resolvedOptions().timeZone });
34
+ }
31
35
  export async function getCurrentSession() {
32
- _currentSession ||= await fetchAPI('GET', 'session');
36
+ _currentSession ||= await fetchSession();
33
37
  return _currentSession;
34
38
  }
35
39
  /** Get the current session, or `null` if there isn't a valid one (e.g. missing or expired) */
36
40
  export async function currentSession() {
37
41
  try {
38
- _currentSession ||= await fetchAPI('GET', 'session');
42
+ _currentSession ||= await fetchSession();
39
43
  return _currentSession;
40
44
  }
41
45
  catch (e) {
@@ -3,7 +3,7 @@
3
3
  import { preferences as uap } from '@axium/client';
4
4
  import { structurallyEqual } from 'utilium';
5
5
  import type { ZodObject } from 'zod';
6
- import ZodInput from './ZodInput.svelte';
6
+ import ZodForm from './ZodForm.svelte';
7
7
  import { toast } from './toast.js';
8
8
 
9
9
  const {
@@ -11,7 +11,14 @@
11
11
  appId,
12
12
  schema,
13
13
  _parentDialog,
14
- }: { userId: string; appId: string; schema: ZodObject; _parentDialog?: HTMLDialogElement } = $props();
14
+ onsave,
15
+ }: {
16
+ userId: string;
17
+ appId: string;
18
+ schema: ZodObject;
19
+ _parentDialog?: HTMLDialogElement;
20
+ onsave?(preferences: object): void;
21
+ } = $props();
15
22
 
16
23
  let initialValue = $state(await uap.get(userId, appId));
17
24
  let currentValue = $state({ ...initialValue });
@@ -23,6 +30,7 @@
23
30
 
24
31
  async function save() {
25
32
  initialValue = await uap.set(userId, appId, currentValue);
33
+ onsave?.(initialValue);
26
34
  if (!_parentDialog) return;
27
35
  _parentDialog.close();
28
36
  toast('success', text('AppPreferences.toast_saved'));
@@ -31,7 +39,7 @@
31
39
 
32
40
  <h2>{text('AppPreferences.title', { name: text(`app_name.${appId}`) })}</h2>
33
41
 
34
- <ZodInput {schema} updateValue={() => {}} bind:rootValue={currentValue} path="" />
42
+ <ZodForm {schema} updateValue={() => {}} bind:rootValue={currentValue} />
35
43
 
36
44
  <div class="actions">
37
45
  <button onclick={cancel}>{text('generic.cancel')}</button>
@@ -4,7 +4,8 @@
4
4
  import Icon from './Icon.svelte';
5
5
  import { text } from '@axium/client';
6
6
 
7
- const { userId, appId, schema }: { userId: string; appId: string; schema: ZodObject } = $props();
7
+ const { userId, appId, schema, onsave }: { userId: string; appId: string; schema: ZodObject; onsave?(preferences: object): void } =
8
+ $props();
8
9
 
9
10
  const id = 'AppPreferencesDialog:' + appId;
10
11
 
@@ -17,5 +18,5 @@
17
18
  </button>
18
19
 
19
20
  <dialog bind:this={_parentDialog} {id}>
20
- <AppPreferences {userId} {appId} {schema} {_parentDialog} />
21
+ <AppPreferences {userId} {appId} {schema} {_parentDialog} {onsave} />
21
22
  </dialog>
package/lib/Icon.svelte CHANGED
@@ -1,11 +1,12 @@
1
1
  <script lang="ts">
2
2
  import type { SVGAttributes } from 'svelte/elements';
3
- const { i, ...rest }: { i: string } & SVGAttributes<SVGSVGElement> = $props();
3
+ const { i, title, ...rest }: { i: string; title?: string } & SVGAttributes<SVGSVGElement> = $props();
4
4
  const [style, id] = $derived(i.includes('/') ? i.split('/') : ['solid', i]);
5
5
  const href = $derived(`/icons/${style}.svg#${id}`);
6
6
  </script>
7
7
 
8
8
  <svg {...rest} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="1em" height="1em" class={['Icon', rest.class]}>
9
+ {#if title}<title>{title}</title>{/if}
9
10
  <use {href} />
10
11
  </svg>
11
12
 
@@ -0,0 +1,46 @@
1
+ <script lang="ts">
2
+ /** From 0 to 1. Without a finite number, the bar shows activity instead. */
3
+ const { value }: { value?: number | null } = $props();
4
+
5
+ const measured = $derived(typeof value == 'number' && Number.isFinite(value));
6
+ </script>
7
+
8
+ <div
9
+ class={['ProgressBar', !measured && 'indeterminate']}
10
+ role="progressbar"
11
+ aria-valuenow={measured ? Math.round(value! * 100) : undefined}
12
+ aria-valuemin={0}
13
+ aria-valuemax={100}
14
+ >
15
+ <div class="fill" style:width={measured ? `${value! * 100}%` : undefined}></div>
16
+ </div>
17
+
18
+ <style>
19
+ .ProgressBar {
20
+ height: 3px;
21
+ border-radius: 2px;
22
+ background-color: var(--bg-strong);
23
+ overflow: hidden;
24
+
25
+ .fill {
26
+ height: 100%;
27
+ background-color: var(--fg-accent);
28
+ transition: width 0.5s;
29
+ }
30
+ }
31
+
32
+ .indeterminate .fill {
33
+ width: 30%;
34
+ animation: slide 1.5s ease-in-out infinite;
35
+ }
36
+
37
+ @keyframes slide {
38
+ from {
39
+ translate: -100%;
40
+ }
41
+
42
+ to {
43
+ translate: 340%;
44
+ }
45
+ }
46
+ </style>
@@ -1,38 +1,218 @@
1
- <script lang="ts">
2
- import { type ReplacementOptions, text } from '@axium/client/locales';
1
+ <script lang="ts" module>
2
+ import type { ZodPref } from '@axium/core';
3
+ import feature from '@axium/core/features';
3
4
  import * as locales from '@james-pre/locales';
4
- import type { ZodObject } from 'zod';
5
+
6
+ /** The schema a modifier or composite is rendered as */
7
+ function inner(schema: ZodPref): ZodPref | undefined {
8
+ switch (schema.type) {
9
+ case 'readonly':
10
+ case 'default':
11
+ case 'nullable':
12
+ case 'optional':
13
+ case 'nonoptional':
14
+ case 'success':
15
+ return schema.def.innerType;
16
+ case 'pipe':
17
+ return schema.def.in;
18
+ case 'union':
19
+ return schema.def.options[0];
20
+ case 'intersection':
21
+ return schema.def.left;
22
+ }
23
+ }
24
+
25
+ function unwrap(schema: ZodPref): ZodPref {
26
+ const next = inner(schema);
27
+ return next ? unwrap(next) : schema;
28
+ }
29
+
30
+ /** The outermost translation metadata registered on a schema or the schemas it wraps */
31
+ function infoOf(schema: ZodPref): locales.ZodInfo | undefined {
32
+ const next = inner(schema);
33
+ return locales.zod.get(schema) ?? (next && infoOf(next));
34
+ }
35
+
36
+ function isAvailable(schema: ZodPref): boolean {
37
+ const flag = infoOf(schema)?.feature;
38
+ if (flag && !feature(flag)) return false;
39
+ const base = unwrap(schema);
40
+ return base.type != 'object' || Object.values<ZodPref>(base.shape).some(isAvailable);
41
+ }
42
+
43
+ function isSection(schema: ZodPref): boolean {
44
+ const { type } = unwrap(schema);
45
+ return type == 'object' || type == 'record';
46
+ }
47
+ </script>
48
+
49
+ <script lang="ts">
50
+ import { text } from '@axium/client';
51
+ import { getByString } from 'utilium';
52
+ import Icon from './Icon.svelte';
5
53
  import ZodInput from './ZodInput.svelte';
6
54
 
7
55
  interface Props {
8
56
  rootValue: any;
9
- schema: ZodObject;
10
- labels?: Record<string, string>;
57
+ schema: Extract<ZodPref, { type: 'object' | 'record' }>;
11
58
  updateValue(value: any): void;
12
59
  idPrefix?: string;
60
+ /** Where the value is in `rootValue`, which renders the form as a section when set */
61
+ path?: string;
62
+ label?: string;
63
+ localeInfo?: locales.ZodInfo;
64
+ /** Whether fields are ordered by key instead of by the schema */
65
+ sort?: boolean;
66
+ }
67
+
68
+ let {
69
+ rootValue = $bindable(),
70
+ schema,
71
+ updateValue,
72
+ idPrefix,
73
+ path = '',
74
+ label,
75
+ localeInfo = locales.zod.get(schema),
76
+ sort,
77
+ }: Props = $props();
78
+
79
+ /** A section's `enabled` field, which disables the rest of the section when false */
80
+ const toggle = $derived.by((): ZodPref | undefined => {
81
+ if (!path || schema.type != 'object') return;
82
+ const field: ZodPref | undefined = schema.shape.enabled;
83
+ if (field && unwrap(field).type == 'boolean') return field;
84
+ });
85
+
86
+ function valueAt(root: any): Record<string, unknown> {
87
+ return { ...(path ? getByString(root, path) : root) };
13
88
  }
14
89
 
15
- let { rootValue = $bindable(), schema, labels, updateValue, idPrefix }: Props = $props();
90
+ /** A copy of this object's value, replaced when a field changes since `rootValue` may not be deeply reactive */
91
+ let value = $derived(valueAt(rootValue));
16
92
 
17
- const localeInfo = locales.zod.get(schema);
93
+ function update(root: any) {
94
+ value = valueAt(root);
95
+ updateValue(root);
96
+ }
97
+
98
+ /** Whether each sibling field named in `requires` has one of the values it lists */
99
+ function meets(requires: Record<string, readonly unknown[]>): boolean {
100
+ if (schema.type != 'object') return true;
101
+ return Object.entries(requires).every(([key, allowed]) => {
102
+ const field: ZodPref | undefined = schema.shape[key];
103
+ return !field || allowed.includes(field.safeParse(value[key]).data);
104
+ });
105
+ }
106
+
107
+ const entries = $derived.by((): [string, ZodPref][] => {
108
+ if (schema.type == 'record') return Object.keys(value).map(key => [key, schema.valueType]);
109
+
110
+ const visible = Object.entries<ZodPref>(schema.shape).filter(([key, child]) => !(toggle && key == 'enabled') && isAvailable(child));
111
+ if (sort) visible.sort(([a], [b]) => a.localeCompare(b));
112
+ return [...visible.filter(([, child]) => !isSection(child)), ...visible.filter(([, child]) => isSection(child))];
113
+ });
18
114
 
19
- function subText(name: string, replacements?: ReplacementOptions & Record<string, any>): string | undefined {
20
- if (!localeInfo?.prefix) return replacements?.$default || labels?.[name] || name;
21
- return text(`${localeInfo.prefix}.${name}`, replacements);
115
+ /** A field's translation metadata, where sections without their own prefix nest under this form's prefix */
116
+ function childInfo(key: string, child: ZodPref): locales.ZodInfo | undefined {
117
+ const info = infoOf(child);
118
+ if (schema.type == 'record' || !isSection(child) || info?.prefix || !localeInfo?.prefix) return info;
119
+ return { ...info, prefix: `${localeInfo.prefix}.${key}` };
120
+ }
121
+
122
+ /** Sections are titled by the `$title` key under their prefix, or by their key when it is missing */
123
+ function childLabel(key: string, child: ZodPref, info?: locales.ZodInfo): string | undefined {
124
+ if (schema.type == 'record') return key;
125
+ if (info?.key) return;
126
+ if (info?.prefix && isSection(child)) return text(`${info.prefix}.$title`, { $default: key });
127
+ return localeInfo?.prefix ? text(`${localeInfo.prefix}.${key}`) : key;
22
128
  }
23
129
  </script>
24
130
 
25
- <div class="ZodForm">
26
- {#each Object.keys(schema.shape).sort((a, b) => a.localeCompare(b)) as path}
27
- <ZodInput bind:rootValue {updateValue} {idPrefix} {path} schema={schema.shape[path]} label={subText(path)} />
131
+ {#snippet field(key: string, child: ZodPref)}
132
+ {const info = childInfo(key, child)}
133
+ <ZodInput
134
+ bind:rootValue
135
+ updateValue={update}
136
+ {idPrefix}
137
+ path={path ? `${path}.${key}` : key}
138
+ schema={child}
139
+ localeInfo={info}
140
+ label={childLabel(key, child, info)}
141
+ />
142
+ {/snippet}
143
+
144
+ {#snippet fields()}
145
+ {#each entries as [key, child] (key)}
146
+ {const requires = infoOf(child)?.requires}
147
+ {#if requires}
148
+ <fieldset class="ZodForm-requires" disabled={!meets(requires)}>{@render field(key, child)}</fieldset>
149
+ {:else}
150
+ {@render field(key, child)}
151
+ {/if}
28
152
  {/each}
29
- </div>
153
+ {/snippet}
154
+
155
+ {#if !path}
156
+ <div class="ZodForm">{@render fields()}</div>
157
+ {:else if toggle || entries.length}
158
+ <fieldset class="ZodForm" disabled={toggle && !meets({ enabled: [true] })}>
159
+ <legend>
160
+ {#if toggle}
161
+ <ZodInput bind:rootValue updateValue={update} {idPrefix} path="{path}.enabled" schema={toggle} {label} />
162
+ {:else}
163
+ {label}
164
+ {/if}
165
+ {#if localeInfo?.experimental}<Icon
166
+ i="regular/flask"
167
+ class="ZodInput-experimental"
168
+ title={text('ZodInput.experimental')}
169
+ />{/if}
170
+ </legend>
171
+ {@render fields()}
172
+ </fieldset>
173
+ {/if}
30
174
 
31
175
  <style>
32
176
  .ZodForm {
177
+ display: grid;
178
+ grid-template-columns: fit-content(50%) minmax(0, 30em);
179
+ align-items: center;
180
+ gap: 0.75em 1.5em;
181
+ }
182
+
183
+ fieldset.ZodForm {
184
+ grid-column: 1 / -1;
185
+ grid-template-columns: subgrid;
186
+ margin: 0.75em 0 0;
187
+ padding: 0;
188
+ border: none;
189
+ min-width: 0;
190
+
191
+ &:disabled {
192
+ color: inherit;
193
+ cursor: auto;
194
+
195
+ > :not(legend) {
196
+ color: var(--fg-disabled);
197
+ }
198
+ }
199
+ }
200
+
201
+ .ZodForm-requires {
202
+ display: contents;
203
+ }
204
+
205
+ legend {
33
206
  display: flex;
34
- flex-direction: column;
35
- align-items: stretch;
36
- gap: 1em;
207
+ align-items: center;
208
+ padding: 0 0 0.75em;
209
+ font-weight: bold;
210
+
211
+ > :global(.ZodInput) {
212
+ display: flex;
213
+ flex-direction: row-reverse;
214
+ align-items: center;
215
+ gap: 0.5em;
216
+ }
37
217
  }
38
218
  </style>
@@ -7,6 +7,7 @@
7
7
  import { getByString, pick, setByString } from 'utilium';
8
8
  import { prettifyError, type z } from 'zod';
9
9
  import Icon from './Icon.svelte';
10
+ import ZodForm from './ZodForm.svelte';
10
11
  import ZodInput from './ZodInput.svelte';
11
12
 
12
13
  interface Props {
@@ -155,9 +156,21 @@
155
156
  const largeArrayTypes = ['object', 'array', 'record', 'tuple', 'template_literal'];
156
157
  </script>
157
158
 
159
+ {#snippet labelFor(target: string)}
160
+ {#if !noLabel}
161
+ <label for={target}>
162
+ {labelText}{#if localeInfo?.experimental}<Icon
163
+ i="regular/flask"
164
+ class="ZodInput-experimental"
165
+ title={text('ZodInput.experimental')}
166
+ />{/if}
167
+ </label>
168
+ {/if}
169
+ {/snippet}
170
+
158
171
  {#snippet _in(rest: HTMLInputAttributes)}
159
172
  <div class={['ZodInput', noLabel && 'no-label']}>
160
- {#if !noLabel}<label for={id}>{labelText}</label>{/if}
173
+ {@render labelFor(id)}
161
174
  {#if error}<span class="ZodInput-error">{error}</span>{/if}
162
175
  <input
163
176
  {id}
@@ -176,6 +189,22 @@
176
189
 
177
190
  {#if localeInfo?.feature && !feature(localeInfo.feature)}
178
191
  <meta data-feature={localeInfo.feature} />
192
+ {:else if schema.type == 'string' && localeInfo?.multiline}
193
+ <div class={['ZodInput', 'multiline', noLabel && 'no-label']}>
194
+ {@render labelFor(id)}
195
+ {#if error}<span class="ZodInput-error">{error}</span>{/if}
196
+ <textarea
197
+ {id}
198
+ bind:value
199
+ {onchange}
200
+ {oninput}
201
+ required={!optional}
202
+ minlength={schema.minLength}
203
+ maxlength={schema.maxLength}
204
+ {placeholder}
205
+ {readonly}
206
+ class={[error && 'error']}></textarea>
207
+ </div>
179
208
  {:else if schema.type == 'string'}
180
209
  {@render _in({ type: schema.format == 'email' ? 'email' : 'text', ...pick(schema, 'minLength', 'maxLength') })}
181
210
  {:else if schema.type == 'number'}
@@ -183,13 +212,13 @@
183
212
  {:else if schema.type == 'bigint'}
184
213
  {@render _in({ type: 'number', min: Number(schema.minValue), max: Number(schema.maxValue), step: 1 })}
185
214
  {:else if schema.type == 'boolean'}
186
- <div class={['ZodInput', noLabel && 'no-label']}>
187
- {#if !noLabel}<label for="{id}:checkbox">{labelText}</label>{/if}
215
+ <span class={['ZodInput', noLabel && 'no-label']}>
216
+ {@render labelFor(`${id}:checkbox`)}
188
217
  <input bind:checked={value} id="{id}:checkbox" type="checkbox" {onchange} required={!optional} {placeholder} />
189
218
  <label for="{id}:checkbox" {id} class="checkbox">
190
219
  {#if value}<Icon i="check" --size="1.3em" />{/if}
191
220
  </label>
192
- </div>
221
+ </span>
193
222
  {:else if schema.type == 'date'}
194
223
  {@render _in({
195
224
  type: 'date',
@@ -200,7 +229,7 @@
200
229
  <!-- todo -->
201
230
  {:else if schema.type == 'literal'}
202
231
  <div class="ZodInput">
203
- <label for={id}>{labelText}</label>
232
+ {@render labelFor(id)}
204
233
  <select bind:value {id} {onchange} required={!optional}>
205
234
  {#each schema.values as literal}
206
235
  <option value={literal} selected={value === literal}>{subText(String(literal), { $default: String(literal) })}</option>
@@ -210,7 +239,7 @@
210
239
  {:else if schema.type == 'template_literal'}
211
240
  {const parts = splitTemplate(schema.def.parts, value)}
212
241
  <div class={['ZodInput', noLabel && 'no-label']}>
213
- {#if !noLabel}<label for={id}>{labelText}</label>{/if}
242
+ {@render labelFor(id)}
214
243
  {#if error}<span class="ZodInput-error">{error}</span>{/if}
215
244
  <div class={['ZodInput-template', error && 'error']}>
216
245
  {#each schema.def.parts as part, i}
@@ -262,7 +291,7 @@
262
291
  <ZodInput bind:rootValue {...props} {localeInfo} label={labelText} schema={schema.def.innerType} optional={false} />
263
292
  {:else if schema.type == 'array'}
264
293
  <div class={['ZodInput', noLabel && 'no-label']}>
265
- {#if !noLabel}<label for={id}>{labelText}</label>{/if}
294
+ {@render labelFor(id)}
266
295
  <div class={['ZodInput-array', largeArrayTypes.includes(schema.element.type) && 'large']}>
267
296
  {#each value, i}
268
297
  <div class="ZodInput-element">
@@ -286,21 +315,18 @@
286
315
  </button>
287
316
  </div>
288
317
  </div>
318
+ {:else if (schema.type == 'record' || schema.type == 'object') && !noLabel}
319
+ <ZodForm bind:rootValue {updateValue} {idPrefix} {path} {schema} {localeInfo} label={labelText} />
289
320
  {:else if schema.type == 'record'}
290
321
  <div class="ZodInput-record">
291
322
  {#each Object.keys(value) as key}
292
- <div class="ZodInput-record-entry">
293
- {#if !noLabel}<label for={id}>{key}</label>{/if}
294
- <ZodInput bind:rootValue {updateValue} {idPrefix} {noLabel} path="{path}.{key}" schema={schema.valueType} />
295
- </div>
323
+ <ZodInput bind:rootValue {updateValue} {idPrefix} {noLabel} path="{path}.{key}" schema={schema.valueType} />
296
324
  {/each}
297
325
  </div>
298
326
  {:else if schema.type == 'object'}
299
- <!-- <div class="ZodInput-object"> -->
300
327
  {#each Object.entries(schema.shape) as [key, value]}
301
328
  <ZodInput bind:rootValue {updateValue} {idPrefix} {noLabel} path="{path}.{key}" schema={value} label={subText(key)} />
302
329
  {/each}
303
- <!-- </div> -->
304
330
  {:else if schema.type == 'tuple'}
305
331
  <div class="ZodInput-tuple" data-rest={schema.def.rest}>
306
332
  {#each schema.def.items as item, i}
@@ -309,7 +335,7 @@
309
335
  </div>
310
336
  {:else if schema.type == 'enum'}
311
337
  <div class={['ZodInput', noLabel && 'no-label']}>
312
- {#if !noLabel}<label for={id}>{labelText}</label>{/if}
338
+ {@render labelFor(id)}
313
339
  {#if error}<span class="ZodInput-error">{error}</span>{/if}
314
340
  <select {id} {onchange} bind:value required={!optional}>
315
341
  {#each Object.entries(schema.enum) as [name, enumValue]}
@@ -318,19 +344,24 @@
318
344
  </select>
319
345
  </div>
320
346
  {:else if schema.type == 'success'}
321
- <ZodInput bind:rootValue {...props} label={labelText} schema={schema.def.innerType} {_parseSchema} />
347
+ <ZodInput bind:rootValue {...props} {localeInfo} label={labelText} schema={schema.def.innerType} {_parseSchema} />
322
348
  {:else if schema.type == 'pipe'}
323
- <ZodInput bind:rootValue {...props} label={labelText} schema={schema.def.in} {_parseSchema} />
349
+ <ZodInput bind:rootValue {...props} {localeInfo} label={labelText} schema={schema.def.in} {_parseSchema} />
324
350
  {:else if schema.type == 'union'}
325
- <ZodInput bind:rootValue {...props} label={labelText} schema={schema.def.options[0]} {_parseSchema} />
351
+ <ZodInput bind:rootValue {...props} {localeInfo} label={labelText} schema={schema.def.options[0]} {_parseSchema} />
326
352
  {:else if schema.type == 'intersection'}
327
- <ZodInput bind:rootValue {...props} label={labelText} schema={schema.def.left} {_parseSchema} />
353
+ <ZodInput bind:rootValue {...props} {localeInfo} label={labelText} schema={schema.def.left} {_parseSchema} />
328
354
  {:else}
329
355
  <!-- No idea how to render this -->
330
356
  <i class="error">{text('ZodInput.invalid_type', { type: JSON.stringify((schema as ZodPref)?.def?.type) })}</i>
331
357
  {/if}
332
358
 
333
359
  <style>
360
+ :global(.ZodInput-experimental) {
361
+ margin-left: 0.4em;
362
+ vertical-align: -0.1em;
363
+ }
364
+
334
365
  .ZodInput-error {
335
366
  position: fixed;
336
367
  position-anchor: --zod-input;
@@ -345,11 +376,24 @@
345
376
  gap: 1em;
346
377
  anchor-scope: --zod-input;
347
378
 
348
- input {
379
+ input,
380
+ textarea {
349
381
  anchor-name: --zod-input;
350
382
  }
351
383
  }
352
384
 
385
+ .ZodInput.multiline {
386
+ grid-template-columns: minmax(0, 1fr);
387
+ gap: 0.5em;
388
+
389
+ textarea {
390
+ field-sizing: content;
391
+ resize: none;
392
+ min-height: 4lh;
393
+ max-height: 20lh;
394
+ }
395
+ }
396
+
353
397
  .ZodInput.no-label {
354
398
  grid-template-columns: minmax(0, 1fr);
355
399
  }
@@ -416,7 +460,6 @@
416
460
  }
417
461
  }
418
462
 
419
- .ZodInput-object,
420
463
  .ZodInput-record,
421
464
  .ZodInput-tuple {
422
465
  display: flex;
@@ -424,4 +467,20 @@
424
467
  align-items: stretch;
425
468
  gap: 0.25em;
426
469
  }
470
+
471
+ :global(.ZodForm) > .ZodInput,
472
+ :global(.ZodForm-requires) > .ZodInput {
473
+ grid-column: 1 / -1;
474
+ grid-template-columns: subgrid;
475
+ column-gap: normal;
476
+ align-items: center;
477
+
478
+ &.multiline > :not(.ZodInput-error) {
479
+ grid-column: 1 / -1;
480
+ }
481
+
482
+ > label.checkbox {
483
+ justify-self: start;
484
+ }
485
+ }
427
486
  </style>
@@ -2,47 +2,7 @@
2
2
  * Svelte attachments
3
3
  * @see https://svelte.dev/docs/svelte/@attach
4
4
  */
5
- import type { Attachment } from 'svelte/attachments';
6
-
7
5
  export * from './context-menu.js';
8
6
  export * as drag from './drag-and-drop.js';
9
7
  export * from './gestures.js';
10
8
  export * from './selection.js';
11
-
12
- /**
13
- * Dynamically resize `<textarea>`s based on content.
14
- * @todo Remove this once `field-sizing` works everywhere
15
- */
16
- export function dynamicRows(max: number = 40, min: number = 3): Attachment<HTMLTextAreaElement> {
17
- return function _attachDynamicRows(element: HTMLTextAreaElement) {
18
- element.style.resize = 'none';
19
- element.style.fieldSizing = 'content';
20
- element.style.height = 'max-content';
21
- element.style.overflowY = 'auto';
22
-
23
- /** Counts wrapped lines as well as explicit ones. */
24
- function update() {
25
- element.rows = 2;
26
- const twoRows = element.clientHeight;
27
- element.rows = 1;
28
- const oneRow = element.clientHeight;
29
- const lines = 1 + Math.round((element.scrollHeight - oneRow) / (twoRows - oneRow));
30
- element.rows = Math.max(Math.min(lines, max), min);
31
- }
32
-
33
- if (CSS.supports('field-sizing', 'content')) return;
34
- update();
35
- element.addEventListener('input', update);
36
- let width = element.clientWidth;
37
- const resize = new ResizeObserver(() => {
38
- if (element.clientWidth == width) return;
39
- width = element.clientWidth;
40
- update();
41
- });
42
- resize.observe(element);
43
- return () => {
44
- element.removeEventListener('input', update);
45
- resize.disconnect();
46
- };
47
- };
48
- }
package/lib/index.ts CHANGED
@@ -18,6 +18,7 @@ export { default as Logout } from './Logout.svelte';
18
18
  export { default as MediaControls } from './MediaControls.svelte';
19
19
  export { default as NumberBar } from './NumberBar.svelte';
20
20
  export { default as Popover } from './Popover.svelte';
21
+ export { default as ProgressBar } from './ProgressBar.svelte';
21
22
  export { default as ProgressRing } from './ProgressRing.svelte';
22
23
  export { default as PWAIndicator } from './PWAIndicator.svelte';
23
24
  export { default as Register } from './Register.svelte';
package/locales/en.json CHANGED
@@ -66,6 +66,7 @@
66
66
  "upgrade": "<span class=\"version\">{latest}</span> available"
67
67
  },
68
68
  "ZodInput": {
69
+ "experimental": "Experimental",
69
70
  "invalid_type": "Invalid input type: {type}"
70
71
  },
71
72
  "error": {
@@ -278,7 +279,13 @@
278
279
  "audit_severity": ["Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Info", "Debug"],
279
280
  "preference": {
280
281
  "debug": "Debug mode",
281
- "theme": "Theme"
282
+ "theme": "Theme",
283
+ "time_zone": "Home time zone"
284
+ },
285
+ "upload_config": {
286
+ "$title": "Uploads",
287
+ "temp_dir": "Temporary directory",
288
+ "timeout": "Idle timeout (minutes)"
282
289
  },
283
290
  "themes": {
284
291
  "default": "Default",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axium/client",
3
- "version": "0.42.1",
3
+ "version": "0.43.0",
4
4
  "author": "James Prevett <jp@jamespre.dev>",
5
5
  "funding": {
6
6
  "type": "individual",
@@ -50,7 +50,7 @@
50
50
  "build": "tsc"
51
51
  },
52
52
  "peerDependencies": {
53
- "@axium/core": ">=0.43.0",
53
+ "@axium/core": ">=0.45.0",
54
54
  "@james-pre/locales": "^1.0.0",
55
55
  "ioium": "^1.7.0",
56
56
  "semver": "^7.7.4",