~james/core

core/web/src/lib/components/ui/Field.svelte -rw-r--r-- 1.9 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<script module lang="ts">
	import { tv, type VariantProps } from "tailwind-variants";

	export const field = tv({
		slots: {
			root: "flex flex-col gap-1.5",
			label: "text-foreground-default",
			subtitle: "typography-paragraph-small text-foreground-muted"
		},
		variants: {
			labelCase: {
				upper: { label: "tracking-wide uppercase" },
				normal: { label: "" }
			}
		},
		defaultVariants: {
			labelCase: "normal"
		}
	});

	export type FieldVariants = VariantProps<typeof field>;
</script>

<script lang="ts">
	import type { Snippet } from "svelte";
	import type { HTMLAttributes } from "svelte/elements";

	interface Props extends Omit<HTMLAttributes<HTMLDivElement>, "class" | "children"> {
		label?: string;
		subtitle?: string | Snippet;
		for?: string;
		group?: boolean;
		required?: boolean;
		labelCase?: FieldVariants["labelCase"];
		class?: string;
		children: Snippet<[{ id: string }]>;
	}

	let {
		label,
		subtitle,
		for: forId,
		group = false,
		required = false,
		labelCase,
		class: className,
		children,
		...rest
	}: Props = $props();

	const generatedId = $props.id();
	const id = $derived(forId ?? generatedId);
	const labelId = $derived(`${id}-label`);
	const slot = $derived(field({ labelCase }));
</script>

{#snippet labelText()}
	{label}
	{#if required}
		<span class="text-foreground-danger">*</span>
	{/if}
{/snippet}

<div
	class={slot.root({ class: className })}
	role={group ? "group" : undefined}
	aria-labelledby={group && label ? labelId : undefined}
	{...rest}
>
	{#if label && group}
		<span id={labelId} class={slot.label()}>{@render labelText()}</span>
	{:else if label}
		<label for={id} class={slot.label()}>{@render labelText()}</label>
	{/if}
	{@render children({ id })}
	{#if typeof subtitle === "function"}
		<p class={slot.subtitle()}>{@render subtitle()}</p>
	{:else if subtitle}
		<p class={slot.subtitle()}>{subtitle}</p>
	{/if}
</div>