refactor: centralize form and record helpers

This commit is contained in:
2026-06-24 13:40:01 +01:00
parent 8b346acadc
commit 1ea8ce2135
25 changed files with 1390 additions and 1557 deletions
+47 -64
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import GalleryVerticalEndIcon from '@lucide/svelte/icons/gallery-vertical-end';
import { toast } from 'svelte-sonner';
import { Field as FormField, Control, FieldErrors } from 'formsnap';
import * as Form from '$lib/components/ui/form/index.js';
import * as Field from '$lib/components/ui/field/index.js';
import { superForm, type SuperValidated } from 'sveltekit-superforms';
import { zod4Client } from 'sveltekit-superforms/adapters';
@@ -9,6 +9,7 @@
import { Button } from '$lib/components/ui/button/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { cn, type WithElementRef } from '$lib/utils.js';
import { firstFormError } from '$lib/form-feedback';
import { firstAdminSchema, type FirstAdminSchema } from '$lib/schemas/auth';
let {
@@ -27,7 +28,7 @@
resetForm: false,
onUpdated: ({ form }) => {
if (!form.valid) {
toast.error(form.message ?? firstError(form.errors), {
toast.error(form.message ?? firstFormError(form.errors), {
id: 'first-admin-error',
position: 'top-center'
});
@@ -42,16 +43,6 @@
});
const { form: formData, enhance } = firstAdminForm;
function firstError(errors: Record<string, unknown>) {
for (const value of Object.values(errors)) {
if (Array.isArray(value) && typeof value[0] === 'string') {
return value[0];
}
}
return 'Check the highlighted fields.';
}
</script>
<div class={cn('flex flex-col gap-6', className)} bind:this={ref} {...restProps}>
@@ -71,58 +62,50 @@
Set up the initial Better Auth admin account for this workspace.
</Field.Description>
</div>
<FormField form={firstAdminForm} name="name">
<Field.Field>
<Control id="name-{id}">
{#snippet children({ props })}
<Field.Label>Name</Field.Label>
<Input
{...props}
autocomplete="name"
placeholder="Administrator"
bind:value={$formData.name}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<FormField form={firstAdminForm} name="email">
<Field.Field>
<Control id="email-{id}">
{#snippet children({ props })}
<Field.Label>Email</Field.Label>
<Input
{...props}
type="email"
autocomplete="email"
placeholder="admin@example.com"
bind:value={$formData.email}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<FormField form={firstAdminForm} name="password">
<Field.Field>
<Control id="password-{id}">
{#snippet children({ props })}
<Field.Label>Password</Field.Label>
<Input
{...props}
type="password"
autocomplete="new-password"
bind:value={$formData.password}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<Field.Field>
<Button type="submit" class="w-full">Create admin</Button>
</Field.Field>
<Form.Field form={firstAdminForm} name="name">
<Form.Control id="name-{id}">
{#snippet children({ props })}
<Form.Label>Name</Form.Label>
<Input
{...props}
autocomplete="name"
placeholder="Administrator"
bind:value={$formData.name}
/>
{/snippet}
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<Form.Field form={firstAdminForm} name="email">
<Form.Control id="email-{id}">
{#snippet children({ props })}
<Form.Label>Email</Form.Label>
<Input
{...props}
type="email"
autocomplete="email"
placeholder="admin@example.com"
bind:value={$formData.email}
/>
{/snippet}
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<Form.Field form={firstAdminForm} name="password">
<Form.Control id="password-{id}">
{#snippet children({ props })}
<Form.Label>Password</Form.Label>
<Input
{...props}
type="password"
autocomplete="new-password"
bind:value={$formData.password}
/>
{/snippet}
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<Button type="submit" class="w-full">Create admin</Button>
</Field.Group>
</form>
<Field.Description class="px-6 text-center">
+42 -55
View File
@@ -1,14 +1,15 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import GalleryVerticalEndIcon from "@lucide/svelte/icons/gallery-vertical-end";
import { Field as FormField, Control, FieldErrors } from 'formsnap';
import GalleryVerticalEndIcon from '@lucide/svelte/icons/gallery-vertical-end';
import * as Form from '$lib/components/ui/form/index.js';
import * as Field from '$lib/components/ui/field/index.js';
import { superForm, type SuperValidated } from 'sveltekit-superforms';
import { zod4Client } from 'sveltekit-superforms/adapters';
import type { HTMLAttributes } from "svelte/elements";
import { Input } from "$lib/components/ui/input/index.js";
import { Button } from "$lib/components/ui/button/index.js";
import { cn, type WithElementRef } from "$lib/utils.js";
import type { HTMLAttributes } from 'svelte/elements';
import { Input } from '$lib/components/ui/input/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import { cn, type WithElementRef } from '$lib/utils.js';
import { firstFormError } from '$lib/form-feedback';
import { loginSchema, type LoginSchema } from '$lib/schemas/auth';
let {
@@ -27,7 +28,7 @@
resetForm: false,
onUpdated: ({ form }) => {
if (!form.valid) {
toast.error(form.message ?? firstError(form.errors), {
toast.error(form.message ?? firstFormError(form.errors), {
id: 'login-error',
position: 'top-center'
});
@@ -42,24 +43,16 @@
});
const { form: formData, enhance } = loginForm;
function firstError(errors: Record<string, unknown>) {
for (const value of Object.values(errors)) {
if (Array.isArray(value) && typeof value[0] === 'string') {
return value[0];
}
}
return 'Check the highlighted fields.';
}
</script>
<div class={cn("flex flex-col gap-6", className)} bind:this={ref} {...restProps}>
<div class={cn('flex flex-col gap-6', className)} bind:this={ref} {...restProps}>
<form action="?/login" method="POST" use:enhance>
<Field.Group>
<div class="flex flex-col items-center gap-2 text-center">
<div class="flex flex-col items-center gap-2 font-medium">
<div class="bg-primary text-primary-foreground flex size-9 items-center justify-center rounded-md">
<div
class="flex size-9 items-center justify-center rounded-md bg-primary text-primary-foreground"
>
<GalleryVerticalEndIcon class="size-6" />
</div>
<span class="sr-only">Clearity</span>
@@ -69,45 +62,39 @@
Use the administrator account created for this workspace.
</Field.Description>
</div>
<FormField form={loginForm} name="email">
<Field.Field>
<Control id="email-{id}">
{#snippet children({ props })}
<Field.Label>Email</Field.Label>
<Input
{...props}
type="email"
autocomplete="email"
placeholder="admin@example.com"
bind:value={$formData.email}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<FormField form={loginForm} name="password">
<Field.Field>
<Control id="password-{id}">
{#snippet children({ props })}
<Field.Label>Password</Field.Label>
<Input
{...props}
type="password"
autocomplete="current-password"
bind:value={$formData.password}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
<Form.Field form={loginForm} name="email">
<Form.Control id="email-{id}">
{#snippet children({ props })}
<Form.Label>Email</Form.Label>
<Input
{...props}
type="email"
autocomplete="email"
placeholder="admin@example.com"
bind:value={$formData.email}
/>
{/snippet}
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<Form.Field form={loginForm} name="password">
<Form.Control id="password-{id}">
{#snippet children({ props })}
<Form.Label>Password</Form.Label>
<Input
{...props}
type="password"
autocomplete="current-password"
bind:value={$formData.password}
/>
{/snippet}
</Form.Control>
<Form.FieldErrors />
<Field.Description>
New users are created manually by an administrator; public registration is disabled.
</Field.Description>
</FormField>
<Field.Field>
<Button type="submit" class="w-full">Sign in</Button>
</Field.Field>
</Form.Field>
<Button type="submit" class="w-full">Sign in</Button>
</Field.Group>
</form>
<Field.Description class="px-6 text-center">
+23 -26
View File
@@ -1,7 +1,6 @@
<script lang="ts">
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Field as FormField, Control, FieldErrors } from 'formsnap';
import * as Field from '$lib/components/ui/field/index.js';
import * as Form from '$lib/components/ui/form/index.js';
import * as InputGroup from '$lib/components/ui/input-group/index.js';
let {
@@ -19,27 +18,25 @@
} = $props();
</script>
<FormField {form} {name}>
<Field.Field>
<Control {id}>
{#snippet children({ props })}
<Field.Label>{label}</Field.Label>
<InputGroup.Root>
<InputGroup.Addon>
<InputGroup.Text>£</InputGroup.Text>
</InputGroup.Addon>
<InputGroup.Input
{...props}
type="number"
min="0"
step="0.01"
inputmode="decimal"
placeholder="0.00"
bind:value={$data[name]}
/>
</InputGroup.Root>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<Form.Field {form} {name}>
<Form.Control {id}>
{#snippet children({ props })}
<Form.Label>{label}</Form.Label>
<InputGroup.Root>
<InputGroup.Addon>
<InputGroup.Text>£</InputGroup.Text>
</InputGroup.Addon>
<InputGroup.Input
{...props}
type="number"
min="0"
step="0.01"
inputmode="decimal"
placeholder="0.00"
bind:value={$data[name]}
/>
</InputGroup.Root>
{/snippet}
</Form.Control>
<Form.FieldErrors />
</Form.Field>
+42
View File
@@ -0,0 +1,42 @@
import { toast } from 'svelte-sonner';
type FormFeedback = {
valid: boolean;
message?: string;
errors: Record<string, unknown>;
};
export function handleFormToast(form: FormFeedback, id: string, onSuccess: () => void) {
if (form.valid) {
if (form.message) toast.success(form.message, { id });
onSuccess();
return;
}
toast.error(form.message ?? firstFormError(form.errors), { id });
}
export function firstFormError(errors: Record<string, unknown>) {
return findFirstError(errors) ?? 'Check the highlighted fields.';
}
function findFirstError(value: unknown): string | undefined {
if (typeof value === 'string') return value;
if (Array.isArray(value)) {
for (const item of value) {
const error = findFirstError(item);
if (error) return error;
}
return undefined;
}
if (value && typeof value === 'object') {
for (const item of Object.values(value)) {
const error = findFirstError(item);
if (error) return error;
}
}
return undefined;
}
+79
View File
@@ -0,0 +1,79 @@
type NamedRecord = Partial<Record<'name' | 'title' | 'invoiceNumber' | 'label', unknown>>;
type RelationOption = {
label: string;
value: string;
};
const gbpFormatter = new Intl.NumberFormat('en-GB', {
style: 'currency',
currency: 'GBP'
});
const dateFormatter = new Intl.DateTimeFormat('en-GB', {
day: '2-digit',
month: 'short',
year: 'numeric'
});
const dateTimeFormatter = new Intl.DateTimeFormat('en-GB', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
export function formatValue(value: unknown) {
if (value === null || value === undefined || value === '') return 'Not set';
return String(value);
}
export function formatMoney(value: unknown, fallback = 'Not set') {
if (value === null || value === undefined || value === '') return fallback;
const amount = typeof value === 'number' ? value : Number(value);
return gbpFormatter.format(Number.isFinite(amount) ? amount : 0);
}
export function formatDate(value: unknown, withTime = false) {
if (!value) return 'Not set';
const date = value instanceof Date ? value : new Date(String(value));
if (Number.isNaN(date.getTime())) return 'Not set';
return (withTime ? dateTimeFormatter : dateFormatter).format(date);
}
export function recordName(record: object | undefined, fallback: string) {
const item = record as NamedRecord | undefined;
return String(item?.name ?? item?.title ?? item?.invoiceNumber ?? item?.label ?? fallback);
}
export function relationLabel<Options extends object, Key extends keyof Options & string>(
options: Options,
value: unknown,
optionsKey: Key
) {
if (typeof value !== 'string') return 'Not set';
const optionList = options[optionsKey] as RelationOption[] | undefined;
return optionList?.find((option) => option.value === value)?.label ?? value;
}
export function filterRecords<T>(records: readonly T[], query: string) {
const normalizedQuery = query.trim().toLowerCase();
if (!normalizedQuery) return [...records];
return records.filter((record) => searchableText(record).includes(normalizedQuery));
}
function searchableText(value: unknown): string {
if (value === null || value === undefined) return '';
if (value instanceof Date) return value.toISOString().toLowerCase();
if (typeof value !== 'object') return String(value).toLowerCase();
if (Array.isArray(value)) return value.map(searchableText).join(' ');
return Object.values(value).map(searchableText).join(' ');
}