svelte-ant-design 0.3.0 → 0.4.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.
@@ -0,0 +1,82 @@
1
+ <script lang="ts">
2
+ /*
3
+ * The few icons the input family needs, drawn here from plain geometry (a circle, a cross, an almond,
4
+ * a ring). They are decorative: the button that holds one carries the accessible name.
5
+ */
6
+ type IconName = 'clear' | 'eye' | 'eye-off' | 'search' | 'loading';
7
+
8
+ let { name }: { name: IconName } = $props();
9
+
10
+ // The cross of the clear icon is cut out of the disc with a mask, so it shows what is behind the icon
11
+ // (any variant, any background). The id is unique per instance.
12
+ const uid = $props.id();
13
+ const iconClass = $derived(`ads-input-icon ads-input-icon-${name}`);
14
+ </script>
15
+
16
+ <svg
17
+ class={iconClass}
18
+ viewBox="0 0 16 16"
19
+ width="1em"
20
+ height="1em"
21
+ aria-hidden="true"
22
+ focusable="false"
23
+ >
24
+ {#if name === 'clear'}
25
+ <mask id="{uid}-cut" maskUnits="userSpaceOnUse" x="0" y="0" width="16" height="16">
26
+ <rect width="16" height="16" fill="#fff" stroke="none" />
27
+ <path d="M5.6 5.6l4.8 4.8M10.4 5.6l-4.8 4.8" stroke="#000" stroke-width="1.6" />
28
+ </mask>
29
+ <circle cx="8" cy="8" r="7" fill="currentColor" mask="url(#{uid}-cut)" />
30
+ {:else if name === 'eye' || name === 'eye-off'}
31
+ <path d="M1 8s2.6-4.8 7-4.8S15 8 15 8s-2.6 4.8-7 4.8S1 8 1 8z" />
32
+ <circle cx="8" cy="8" r="2.1" />
33
+ {#if name === 'eye-off'}<path d="M2.6 13.4L13.4 2.6" />{/if}
34
+ {:else if name === 'search'}
35
+ <circle cx="7" cy="7" r="4.6" />
36
+ <path d="M10.4 10.4L14 14" />
37
+ {:else}
38
+ <circle class="track" cx="8" cy="8" r="6" />
39
+ <path class="arc" d="M8 2a6 6 0 0 1 6 6" />
40
+ {/if}
41
+ </svg>
42
+
43
+ <style>
44
+ .ads-input-icon {
45
+ display: block;
46
+ flex: none;
47
+ fill: none;
48
+ stroke: currentColor;
49
+ stroke-width: 1.4;
50
+ stroke-linecap: round;
51
+ stroke-linejoin: round;
52
+ }
53
+
54
+ /* The filled disc has no stroke. */
55
+ .ads-input-icon-clear circle {
56
+ stroke: none;
57
+ }
58
+
59
+ .ads-input-icon-loading {
60
+ animation: ads-input-spin var(--ads-motion-duration-spinner) linear infinite;
61
+ }
62
+
63
+ .ads-input-icon-loading .track {
64
+ opacity: 0.25;
65
+ }
66
+
67
+ .ads-input-icon-loading .arc {
68
+ stroke-width: 2;
69
+ }
70
+
71
+ @keyframes ads-input-spin {
72
+ to {
73
+ transform: rotate(360deg);
74
+ }
75
+ }
76
+
77
+ @media (prefers-reduced-motion: reduce) {
78
+ .ads-input-icon-loading {
79
+ animation-duration: var(--ads-motion-duration-spinner-reduced);
80
+ }
81
+ }
82
+ </style>
@@ -0,0 +1,7 @@
1
+ type IconName = 'clear' | 'eye' | 'eye-off' | 'search' | 'loading';
2
+ type $$ComponentProps = {
3
+ name: IconName;
4
+ };
5
+ declare const InputIcon: import("svelte").Component<$$ComponentProps, {}, "">;
6
+ type InputIcon = ReturnType<typeof InputIcon>;
7
+ export default InputIcon;
@@ -0,0 +1,248 @@
1
+ <script lang="ts">
2
+ import { tick, type Snippet } from 'svelte';
3
+ import type { HTMLAttributes, HTMLInputAttributes } from 'svelte/elements';
4
+ import type {
5
+ InputFocusOptions,
6
+ InputOTPClassNames,
7
+ InputOTPStyles,
8
+ InputSize,
9
+ InputStatus,
10
+ InputVariant
11
+ } from './types.js';
12
+ import { isProduction } from '../internal/env.js';
13
+ import { classList, styleText } from '../internal/semantic.js';
14
+ import { normalizeSize } from './field.js';
15
+ import Input from './Input.svelte';
16
+
17
+ type InputOTPProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'style' | 'onchange' | 'oninput'> & {
18
+ /** The characters entered so far, without gaps. Use `bind:value` for two-way binding; a plain value is the initial text. */
19
+ value?: string;
20
+ /** Number of cells. */
21
+ length?: number;
22
+ /** Hides the characters: `true` shows a bullet, a string is the single character shown instead. */
23
+ mask?: boolean | string;
24
+ /** Maps the whole text to the displayed text; the cell at index `i` shows the `i`-th character of the result. */
25
+ formatter?: (value: string) => string;
26
+ /** Rendered after the cell at the given index: plain text, or a snippet that receives the index. */
27
+ separator?: string | Snippet<[index: number]>;
28
+ /** Whether every cell is disabled. */
29
+ disabled?: boolean;
30
+ /** Size of the cells. `middle` and `default` are compatibility aliases of `medium`. */
31
+ size?: InputSize;
32
+ /** Visual variant of the cells. */
33
+ variant?: InputVariant;
34
+ /** Validation look of the cells. */
35
+ status?: InputStatus;
36
+ /** Native `autocomplete` of every cell; `one-time-code` enables autofill of a code. */
37
+ autocomplete?: HTMLInputAttributes['autocomplete'];
38
+ /** Called when every cell is filled, with the whole text. */
39
+ onchange?: (value: string) => void;
40
+ /** Called on each change, with one entry per cell (`''` for an empty one). */
41
+ oninput?: (values: string[]) => void;
42
+ /** Extra classes for the `root`, the cells (`input`) and the `separator`. */
43
+ classNames?: InputOTPClassNames;
44
+ /** Inline styles for the `root`, the cells (`input`) and the `separator`. */
45
+ styles?: InputOTPStyles;
46
+ /** Additional CSS class appended to the root classes. */
47
+ class?: string;
48
+ /** Inline style of the root; `styles.root` is applied after it. */
49
+ style?: string;
50
+ };
51
+
52
+ let {
53
+ value = $bindable(''),
54
+ length = 6,
55
+ mask = false,
56
+ formatter,
57
+ separator = undefined,
58
+ disabled = false,
59
+ size = 'medium',
60
+ variant = 'outlined',
61
+ status = undefined,
62
+ autocomplete = undefined,
63
+ onchange,
64
+ oninput,
65
+ classNames,
66
+ styles,
67
+ class: customClass,
68
+ style: customStyle,
69
+ ...rest
70
+ }: InputOTPProps = $props();
71
+
72
+ let cells: Array<ReturnType<typeof Input> | undefined> = $state([]);
73
+ // Whether an IME composition is open in a cell: its text is taken when the composition ends.
74
+ let composing = false;
75
+
76
+ // A bad length is a mistake while developing; a production build falls back to the default.
77
+ const count = $derived.by(() => {
78
+ if (Number.isInteger(length) && length >= 1) return length;
79
+ if (!isProduction()) throw new RangeError('InputOTP length must be a positive integer.');
80
+ return 6;
81
+ });
82
+
83
+ // The mask character: `true` is a bullet, a string is its first character.
84
+ const maskChar = $derived.by(() => {
85
+ if (mask === true) return '•';
86
+ if (typeof mask !== 'string' || mask === '') return undefined;
87
+ if ([...mask].length > 1 && !isProduction()) {
88
+ throw new RangeError('InputOTP mask must be a single character.');
89
+ }
90
+ return [...mask][0];
91
+ });
92
+
93
+ // The text as code points: one per cell, no gaps, never more than there are cells.
94
+ const chars = $derived([...(value ?? '')].slice(0, count));
95
+ const shown = $derived([...(formatter ? formatter(chars.join('')) : chars.join(''))]);
96
+
97
+ // A cell is as wide as the field is high, and has no inline padding (the character is centered).
98
+ const cellStyle = $derived(
99
+ `flex: none; width: var(${
100
+ { large: '--ads-control-height-lg', medium: '--ads-control-height', small: '--ads-control-height-sm' }[normalizeSize(size)]
101
+ }); --_pi: 0px;`
102
+ );
103
+
104
+ /** The accessible name of a cell (English; a locale mechanism is planned). */
105
+ const cellLabel = (index: number): string => `Character ${index + 1} of ${count}`;
106
+
107
+ function display(index: number): string {
108
+ if (maskChar !== undefined) return index < chars.length ? maskChar : '';
109
+ return shown[index] ?? '';
110
+ }
111
+
112
+ /** Puts `incoming` into the cells from `index`, replacing what is there; an empty text removes the character at `index`. */
113
+ function apply(index: number, incoming: string): void {
114
+ const next = [...chars];
115
+ const added = [...incoming];
116
+ const at = Math.min(index, next.length);
117
+ if (added.length === 0) next.splice(at, 1);
118
+ else next.splice(at, added.length, ...added);
119
+ const text = next.slice(0, count).join('');
120
+ const changed = text !== chars.join('');
121
+ value = text;
122
+ if (changed) {
123
+ oninput?.(Array.from({ length: count }, (_, i) => [...text][i] ?? ''));
124
+ if ([...text].length === count) onchange?.(text);
125
+ }
126
+ const target = Math.min(at + Math.max(added.length, 0), count - 1);
127
+ focusCell(added.length === 0 ? at : target);
128
+ }
129
+
130
+ // After the render, so a cell whose character just changed is selected with its new text.
131
+ function focusCell(index: number): void {
132
+ void tick().then(() => cells[Math.max(0, Math.min(index, count - 1))]?.focus({ cursor: 'all' }));
133
+ }
134
+
135
+ function handleCellChange(index: number, raw: string): void {
136
+ if (composing) return;
137
+ // The text of the cell without the character it showed before the edit (a typed character lands next to it).
138
+ const previous = display(index);
139
+ let incoming = raw;
140
+ if (previous !== '' && incoming.length > previous.length) {
141
+ if (incoming.startsWith(previous)) incoming = incoming.slice(previous.length);
142
+ else if (incoming.endsWith(previous)) incoming = incoming.slice(0, incoming.length - previous.length);
143
+ }
144
+ apply(index, incoming);
145
+ }
146
+
147
+ function handleKeydown(index: number, event: KeyboardEvent): void {
148
+ if (event.isComposing) return;
149
+ const rtl = getComputedStyle(event.currentTarget as HTMLElement).direction === 'rtl';
150
+ if (event.key === 'Backspace') {
151
+ event.preventDefault();
152
+ if (index < chars.length) apply(index, '');
153
+ else if (index > 0) apply(index - 1, '');
154
+ } else if (event.key === 'Delete') {
155
+ event.preventDefault();
156
+ if (index < chars.length) apply(index, '');
157
+ } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
158
+ event.preventDefault();
159
+ const forward = (event.key === 'ArrowRight') !== rtl;
160
+ focusCell(index + (forward ? 1 : -1));
161
+ }
162
+ }
163
+
164
+ function handlePaste(index: number, event: ClipboardEvent): void {
165
+ event.preventDefault();
166
+ // Nothing to paste (an empty clipboard, or no text in it) changes nothing: an empty text would remove a character.
167
+ const pasted = event.clipboardData?.getData('text') ?? '';
168
+ if (pasted !== '') apply(index, pasted);
169
+ }
170
+
171
+ // A cell past the first empty one cannot be filled (the text has no gaps): focus goes to the first empty cell.
172
+ function handleFocus(index: number, event: FocusEvent): void {
173
+ const first = Math.min(chars.length, count - 1);
174
+ if (index > first) focusCell(first);
175
+ else (event.currentTarget as HTMLInputElement).select();
176
+ }
177
+
178
+ /** Moves focus to the first empty cell (the last one when all are filled). */
179
+ export function focus(options?: InputFocusOptions): void {
180
+ cells[Math.min(chars.length, count - 1)]?.focus(options);
181
+ }
182
+
183
+ /** Removes focus from the cell that has it. */
184
+ export function blur(): void {
185
+ for (const cell of cells) cell?.blur();
186
+ }
187
+ </script>
188
+
189
+ <!--
190
+ A group of single-character inputs. The characters live in one string (`value`), and cell `i` shows the `i`-th
191
+ character of it, so the cells never have gaps. Each cell is an `Input`, so the sizes, variants and statuses are
192
+ those of the input.
193
+ -->
194
+ <div
195
+ {...rest}
196
+ role="group"
197
+ class={classList('ads-input-otp', customClass, classNames?.root)}
198
+ style={styleText(customStyle, styles?.root)}
199
+ >
200
+ {#each { length: count }, index (index)}
201
+ <Input
202
+ bind:this={cells[index]}
203
+ bind:value={() => display(index), () => {}}
204
+ type="text"
205
+ style={cellStyle}
206
+ classNames={{ input: classNames?.input }}
207
+ styles={{ input: { 'text-align': 'center', ...styles?.input } }}
208
+ {size}
209
+ {variant}
210
+ {status}
211
+ {disabled}
212
+ {autocomplete}
213
+ autocapitalize="off"
214
+ spellcheck={false}
215
+ aria-label={cellLabel(index)}
216
+ onchange={(next) => handleCellChange(index, next)}
217
+ onkeydown={(event) => handleKeydown(index, event)}
218
+ onpaste={(event) => handlePaste(index, event)}
219
+ onfocus={(event) => handleFocus(index, event)}
220
+ onclick={(event) => event.currentTarget.select()}
221
+ oncompositionstart={() => (composing = true)}
222
+ oncompositionend={() => (composing = false)}
223
+ />
224
+ {#if separator && index < count - 1}
225
+ <span
226
+ class={classList('ads-input-otp-separator', classNames?.separator)}
227
+ style={styleText(styles?.separator)}
228
+ >{#if typeof separator === 'string'}{separator}{:else}{@render separator(index)}{/if}</span
229
+ >
230
+ {/if}
231
+ {/each}
232
+ </div>
233
+
234
+ <style>
235
+ .ads-input-otp {
236
+ display: inline-flex;
237
+ align-items: center;
238
+ gap: var(--ads-input-otp-gap);
239
+ font-family: var(--ads-font-family);
240
+ }
241
+
242
+ .ads-input-otp-separator {
243
+ display: inline-flex;
244
+ flex: none;
245
+ align-items: center;
246
+ color: var(--ads-color-text);
247
+ }
248
+ </style>
@@ -0,0 +1,43 @@
1
+ import { type Snippet } from 'svelte';
2
+ import type { HTMLAttributes, HTMLInputAttributes } from 'svelte/elements';
3
+ import type { InputFocusOptions, InputOTPClassNames, InputOTPStyles, InputSize, InputStatus, InputVariant } from './types.js';
4
+ type InputOTPProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'style' | 'onchange' | 'oninput'> & {
5
+ /** The characters entered so far, without gaps. Use `bind:value` for two-way binding; a plain value is the initial text. */
6
+ value?: string;
7
+ /** Number of cells. */
8
+ length?: number;
9
+ /** Hides the characters: `true` shows a bullet, a string is the single character shown instead. */
10
+ mask?: boolean | string;
11
+ /** Maps the whole text to the displayed text; the cell at index `i` shows the `i`-th character of the result. */
12
+ formatter?: (value: string) => string;
13
+ /** Rendered after the cell at the given index: plain text, or a snippet that receives the index. */
14
+ separator?: string | Snippet<[index: number]>;
15
+ /** Whether every cell is disabled. */
16
+ disabled?: boolean;
17
+ /** Size of the cells. `middle` and `default` are compatibility aliases of `medium`. */
18
+ size?: InputSize;
19
+ /** Visual variant of the cells. */
20
+ variant?: InputVariant;
21
+ /** Validation look of the cells. */
22
+ status?: InputStatus;
23
+ /** Native `autocomplete` of every cell; `one-time-code` enables autofill of a code. */
24
+ autocomplete?: HTMLInputAttributes['autocomplete'];
25
+ /** Called when every cell is filled, with the whole text. */
26
+ onchange?: (value: string) => void;
27
+ /** Called on each change, with one entry per cell (`''` for an empty one). */
28
+ oninput?: (values: string[]) => void;
29
+ /** Extra classes for the `root`, the cells (`input`) and the `separator`. */
30
+ classNames?: InputOTPClassNames;
31
+ /** Inline styles for the `root`, the cells (`input`) and the `separator`. */
32
+ styles?: InputOTPStyles;
33
+ /** Additional CSS class appended to the root classes. */
34
+ class?: string;
35
+ /** Inline style of the root; `styles.root` is applied after it. */
36
+ style?: string;
37
+ };
38
+ declare const InputOTP: import("svelte").Component<InputOTPProps, {
39
+ focus: (options?: InputFocusOptions) => void;
40
+ blur: () => void;
41
+ }, "value">;
42
+ type InputOTP = ReturnType<typeof InputOTP>;
43
+ export default InputOTP;
@@ -0,0 +1,125 @@
1
+ <script lang="ts">
2
+ import type { Snippet } from 'svelte';
3
+ import type { InputFocusOptions, InputProps } from './types.js';
4
+ import Input from './Input.svelte';
5
+ import InputIcon from './InputIcon.svelte';
6
+
7
+ type InputPasswordProps = Omit<InputProps, 'type'> & {
8
+ /** Whether the text is shown. Use `bind:visible` for two-way binding; a plain value is the initial state. */
9
+ visible?: boolean;
10
+ /** Shows the toggle button. The object form tunes it: `tabIndex` and the accessible name `label`. */
11
+ visibilityToggle?: boolean | { tabIndex?: number; label?: string };
12
+ /** Called once per user toggle with the new visibility. */
13
+ onvisiblechange?: (visible: boolean) => void;
14
+ /** Custom content of the toggle button, given the current visibility. */
15
+ iconRender?: Snippet<[visible: boolean]>;
16
+ };
17
+
18
+ let {
19
+ value = $bindable(''),
20
+ visible = $bindable(false),
21
+ visibilityToggle = true,
22
+ onvisiblechange,
23
+ iconRender,
24
+ suffix = undefined,
25
+ disabled = false,
26
+ ...rest
27
+ }: InputPasswordProps = $props();
28
+
29
+ let inner: ReturnType<typeof Input> | undefined = $state();
30
+
31
+ const toggleConfig = $derived(typeof visibilityToggle === 'object' ? visibilityToggle : undefined);
32
+ const toggleShown = $derived(visibilityToggle !== false);
33
+
34
+ function toggle(): void {
35
+ const next = !visible;
36
+ visible = next;
37
+ onvisiblechange?.(next);
38
+ }
39
+
40
+ /** Moves focus to the input; `cursor` places the caret or selects the text. */
41
+ export function focus(options?: InputFocusOptions): void {
42
+ inner?.focus(options);
43
+ }
44
+
45
+ /** Removes focus from the input. */
46
+ export function blur(): void {
47
+ inner?.blur();
48
+ }
49
+ </script>
50
+
51
+ {#snippet affix()}
52
+ {#if typeof suffix === 'string'}{suffix}{:else if suffix}{@render suffix()}{/if}
53
+ {#if toggleShown}
54
+ <!-- A native button; a press does not take focus from the field. The name stays, `aria-pressed` follows the state. -->
55
+ <button
56
+ type="button"
57
+ class="ads-input-password-toggle"
58
+ aria-label={toggleConfig?.label ?? 'Show password'}
59
+ aria-pressed={visible}
60
+ tabindex={toggleConfig?.tabIndex}
61
+ {disabled}
62
+ onmousedown={(event) => event.preventDefault()}
63
+ onclick={toggle}
64
+ >
65
+ {#if iconRender}
66
+ {@render iconRender(visible)}
67
+ {:else}
68
+ <InputIcon name={visible ? 'eye' : 'eye-off'} />
69
+ {/if}
70
+ </button>
71
+ {/if}
72
+ {/snippet}
73
+
74
+ <Input
75
+ bind:this={inner}
76
+ bind:value
77
+ {...rest}
78
+ {disabled}
79
+ type={visible ? 'text' : 'password'}
80
+ suffix={suffix || toggleShown ? affix : undefined}
81
+ />
82
+
83
+ <style>
84
+ .ads-input-password-toggle {
85
+ display: inline-flex;
86
+ flex: none;
87
+ align-items: center;
88
+ justify-content: center;
89
+ margin: 0;
90
+ padding: 0;
91
+ border: 0;
92
+ border-radius: 2px;
93
+ background: transparent;
94
+ color: var(--ads-input-icon-color);
95
+ font: inherit;
96
+ font-size: var(--ads-input-icon-size);
97
+ line-height: 1;
98
+ cursor: pointer;
99
+ transition: color var(--ads-motion-duration) var(--ads-motion-ease);
100
+ }
101
+
102
+ .ads-input-password-toggle:not(:first-child) {
103
+ margin-inline-start: var(--ads-input-gap);
104
+ }
105
+
106
+ .ads-input-password-toggle:hover:not(:disabled) {
107
+ color: var(--ads-input-icon-color-hover);
108
+ }
109
+
110
+ .ads-input-password-toggle:disabled {
111
+ color: var(--ads-color-text-disabled);
112
+ cursor: not-allowed;
113
+ }
114
+
115
+ .ads-input-password-toggle:focus-visible {
116
+ outline: var(--ads-focus-outline-width) solid var(--ads-color-focus-outline);
117
+ outline-offset: 1px;
118
+ }
119
+
120
+ @media (prefers-reduced-motion: reduce) {
121
+ .ads-input-password-toggle {
122
+ transition: none;
123
+ }
124
+ }
125
+ </style>
@@ -0,0 +1,21 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { InputFocusOptions, InputProps } from './types.js';
3
+ type InputPasswordProps = Omit<InputProps, 'type'> & {
4
+ /** Whether the text is shown. Use `bind:visible` for two-way binding; a plain value is the initial state. */
5
+ visible?: boolean;
6
+ /** Shows the toggle button. The object form tunes it: `tabIndex` and the accessible name `label`. */
7
+ visibilityToggle?: boolean | {
8
+ tabIndex?: number;
9
+ label?: string;
10
+ };
11
+ /** Called once per user toggle with the new visibility. */
12
+ onvisiblechange?: (visible: boolean) => void;
13
+ /** Custom content of the toggle button, given the current visibility. */
14
+ iconRender?: Snippet<[visible: boolean]>;
15
+ };
16
+ declare const InputPassword: import("svelte").Component<InputPasswordProps, {
17
+ focus: (options?: InputFocusOptions) => void;
18
+ blur: () => void;
19
+ }, "value" | "visible">;
20
+ type InputPassword = ReturnType<typeof InputPassword>;
21
+ export default InputPassword;