@marianmeres/stuic 3.182.0 → 3.184.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/README.md +1 -1
- package/dist/components/Input/FieldAssets.svelte +9 -132
- package/dist/components/Input/FieldSingleAsset.svelte +934 -0
- package/dist/components/Input/FieldSingleAsset.svelte.d.ts +152 -0
- package/dist/components/Input/README.md +269 -21
- package/dist/components/Input/_internal/asset-helpers.d.ts +16 -0
- package/dist/components/Input/_internal/asset-helpers.js +46 -0
- package/dist/components/Input/_internal/paste-target.d.ts +15 -0
- package/dist/components/Input/_internal/paste-target.js +114 -0
- package/dist/components/Input/field-single-asset-i18n-sk.d.ts +21 -0
- package/dist/components/Input/field-single-asset-i18n-sk.js +50 -0
- package/dist/components/Input/field-single-asset-i18n.d.ts +69 -0
- package/dist/components/Input/field-single-asset-i18n.js +76 -0
- package/dist/components/Input/index.css +217 -0
- package/dist/components/Input/index.d.ts +3 -0
- package/dist/components/Input/index.js +3 -0
- package/docs/domains/actions.md +3 -3
- package/docs/domains/components.md +22 -21
- package/package.json +1 -1
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { type Snippet } from "svelte";
|
|
2
|
+
import { type ValidateOptions, type ValidationResult } from "../../actions/validate.svelte.js";
|
|
3
|
+
import type { TranslateFn } from "../../types.js";
|
|
4
|
+
import { NotificationsStack } from "../Notifications/notifications-stack.svelte.js";
|
|
5
|
+
import { type THC } from "../Thc/Thc.svelte";
|
|
6
|
+
import type { FieldAsset } from "./FieldAssets.svelte";
|
|
7
|
+
import type { InputWrapClassProps } from "./types.js";
|
|
8
|
+
type SnippetWithId = Snippet<[{
|
|
9
|
+
id: string;
|
|
10
|
+
}]>;
|
|
11
|
+
/** What `processAsset` receives besides the optimistic (blob) asset. */
|
|
12
|
+
export interface FieldSingleAssetUploadContext {
|
|
13
|
+
/** The file to upload — already run through `transformFile`, if any. */
|
|
14
|
+
file: File;
|
|
15
|
+
/** Report upload progress (0–100). Rendered when `withOnProgress` is set. */
|
|
16
|
+
onProgress: (progress: number) => void;
|
|
17
|
+
}
|
|
18
|
+
export type FieldSingleAssetShape = "square" | "circle" | "wide";
|
|
19
|
+
export type FieldSingleAssetFit = "cover" | "contain";
|
|
20
|
+
export type FieldSingleAssetSize = "sm" | "md" | "lg";
|
|
21
|
+
/** `validateFile` verdict: a non-empty string rejects the file with that message. */
|
|
22
|
+
export type FieldSingleAssetFileCheck = string | void | null | undefined | false;
|
|
23
|
+
export interface Props extends InputWrapClassProps, Record<string, any> {
|
|
24
|
+
/**
|
|
25
|
+
* The serialized asset: by default the JSON of ONE `FieldAsset` object, or the
|
|
26
|
+
* empty string when the field is empty (see `parseValue` / `serializeValue`).
|
|
27
|
+
* Only ever rewritten when a user action SETTLES — an upload that resolves, a
|
|
28
|
+
* remove, an undo. An in-flight or failed upload never touches it.
|
|
29
|
+
*/
|
|
30
|
+
value: string;
|
|
31
|
+
/** The hidden input's name (what the form submits). */
|
|
32
|
+
name: string;
|
|
33
|
+
label?: SnippetWithId | THC;
|
|
34
|
+
description?: SnippetWithId | THC;
|
|
35
|
+
labelAfter?: SnippetWithId | THC;
|
|
36
|
+
below?: SnippetWithId | THC;
|
|
37
|
+
class?: string;
|
|
38
|
+
id?: string;
|
|
39
|
+
tabindex?: number;
|
|
40
|
+
renderSize?: "sm" | "md" | "lg" | string;
|
|
41
|
+
required?: boolean;
|
|
42
|
+
disabled?: boolean;
|
|
43
|
+
validate?: boolean | Omit<ValidateOptions, "setValidationResult">;
|
|
44
|
+
labelLeft?: boolean;
|
|
45
|
+
labelLeftWidth?: "normal" | "wide";
|
|
46
|
+
labelLeftBreakpoint?: number;
|
|
47
|
+
/** Classes for the hidden `<input type="file">` */
|
|
48
|
+
classInput?: string;
|
|
49
|
+
/** Classes for the outermost wrapper (the drop zone) */
|
|
50
|
+
classWrap?: string;
|
|
51
|
+
/** Classes for the tile (the preview button) */
|
|
52
|
+
classPreview?: string;
|
|
53
|
+
/** Classes for the tile's action buttons (remove, preview, retry) */
|
|
54
|
+
classControls?: string;
|
|
55
|
+
style?: string;
|
|
56
|
+
t?: TranslateFn;
|
|
57
|
+
notifications?: NotificationsStack;
|
|
58
|
+
/** Initial-fetch state: renders a skeleton in the tile's shape; takes no input. */
|
|
59
|
+
isLoading?: boolean;
|
|
60
|
+
/** `value` -> asset. Default: `JSON.parse`, `null` for an empty/invalid string. */
|
|
61
|
+
parseValue?: (serialized: string) => FieldAsset | null;
|
|
62
|
+
/** asset -> `value`. Default: `JSON.stringify`, `""` for `null`. */
|
|
63
|
+
serializeValue?: (asset: FieldAsset | null) => string;
|
|
64
|
+
/**
|
|
65
|
+
* The upload. Receives the optimistic asset (its `id` and every `url` are one
|
|
66
|
+
* blob URL of the file) and the file itself; resolves with the stored asset,
|
|
67
|
+
* which becomes the new `value`. A rejection keeps the previous `value`, shows
|
|
68
|
+
* an error state on the tile with Retry / Discard, and reports `notifications`
|
|
69
|
+
* (see `onUploadError` to take over that report).
|
|
70
|
+
* Without it the field is display-only (no picker, no drop, no paste).
|
|
71
|
+
*/
|
|
72
|
+
processAsset?: (asset: FieldAsset, ctx: FieldSingleAssetUploadContext) => Promise<FieldAsset>;
|
|
73
|
+
/** Render a progress ring driven by `ctx.onProgress` instead of a spinner. */
|
|
74
|
+
withOnProgress?: boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Called when `processAsset` rejects (with the raw rejection, so a status code or
|
|
77
|
+
* a custom error class is still inspectable), after the tile has entered its
|
|
78
|
+
* error state and before the default `notifications.error(...)` toast. Return
|
|
79
|
+
* `false` to skip that toast — for a rejection the page already renders its own
|
|
80
|
+
* way (a quota / plan-limit panel). The tile keeps Retry / Discard regardless.
|
|
81
|
+
*/
|
|
82
|
+
onUploadError?: (error: unknown, ctx: {
|
|
83
|
+
asset: FieldAsset;
|
|
84
|
+
file: File;
|
|
85
|
+
}) => void | boolean;
|
|
86
|
+
/** Same tokens as the HTML `accept` attribute; also applied to drops and pastes. */
|
|
87
|
+
accept?: string;
|
|
88
|
+
/** Passed to the file input: on phones opens the camera directly. */
|
|
89
|
+
capture?: "user" | "environment";
|
|
90
|
+
/** Reject files larger than this many bytes (checked after `transformFile`). */
|
|
91
|
+
maxSize?: number;
|
|
92
|
+
/**
|
|
93
|
+
* Custom check, run after `transformFile` and `maxSize`. Return a non-empty
|
|
94
|
+
* string to reject the file with that message (may be async — e.g. read image
|
|
95
|
+
* dimensions first).
|
|
96
|
+
*/
|
|
97
|
+
validateFile?: (file: File) => FieldSingleAssetFileCheck | Promise<FieldSingleAssetFileCheck>;
|
|
98
|
+
/**
|
|
99
|
+
* Pre-upload hook, run after the `accept` check: downscale a photo, or open a
|
|
100
|
+
* cropper and resolve with the cropped file. Resolving with `null`/`undefined`
|
|
101
|
+
* cancels silently (the user closed the cropper).
|
|
102
|
+
*/
|
|
103
|
+
transformFile?: (file: File) => File | null | undefined | Promise<File | null | undefined>;
|
|
104
|
+
/**
|
|
105
|
+
* Return `false` (may be async) to keep the asset. While a returned promise is
|
|
106
|
+
* pending the tile is busy: the Remove control shows a spinner, the tile and
|
|
107
|
+
* its controls are inert, and a second Remove is a no-op — so the hook may do
|
|
108
|
+
* the actual server-side delete and resolve with whether it succeeded.
|
|
109
|
+
*/
|
|
110
|
+
onBeforeRemove?: (asset: FieldAsset) => boolean | Promise<boolean>;
|
|
111
|
+
/** Return `false` (may be async) to keep the current asset instead of uploading `file`. */
|
|
112
|
+
onBeforeReplace?: (current: FieldAsset, file: File) => boolean | Promise<boolean>;
|
|
113
|
+
/**
|
|
114
|
+
* After a remove, an inline "Undo" stays available this many ms (the removed
|
|
115
|
+
* asset is only unlinked from `value`, never deleted anywhere, so undo is
|
|
116
|
+
* lossless). `0` disables it. Default `6000`.
|
|
117
|
+
*/
|
|
118
|
+
undoTtl?: number;
|
|
119
|
+
/**
|
|
120
|
+
* Opt-in: accept a clipboard paste (Ctrl/Cmd-V). Same routing as `FieldAssets`
|
|
121
|
+
* (one shared document listener: focused field wins; a bare paste with no focus
|
|
122
|
+
* goes to the only pasteable field on the page). A paste replaces. No-op without
|
|
123
|
+
* `processAsset`.
|
|
124
|
+
*/
|
|
125
|
+
pasteable?: boolean;
|
|
126
|
+
/** Tile shape. `circle` for avatars, `wide` (16:9) for banners / logos. Default `square`. */
|
|
127
|
+
shape?: FieldSingleAssetShape;
|
|
128
|
+
/** `cover` crops to fill, `contain` letterboxes on a neutral background (logos). Default `cover`. */
|
|
129
|
+
fit?: FieldSingleAssetFit;
|
|
130
|
+
/** Tile height: a preset (`5rem` / `8rem` / `12rem`) or any CSS length. Default `md`. */
|
|
131
|
+
size?: FieldSingleAssetSize | string;
|
|
132
|
+
/** What the empty tile shows instead of the default icon (e.g. an `Avatar` with initials). */
|
|
133
|
+
placeholder?: THC;
|
|
134
|
+
/** Hide the "Preview" action (the `AssetsPreview` lightbox). */
|
|
135
|
+
noPreview?: boolean;
|
|
136
|
+
/** Hide the lightbox's Download button. */
|
|
137
|
+
noDownload?: boolean;
|
|
138
|
+
/** See `AssetsPreview.onDownload`: replaces the default download of `url.original`. */
|
|
139
|
+
onDownload?: (asset: FieldAsset) => void | Promise<void>;
|
|
140
|
+
/** After every user-driven change of `value` (upload settled, remove, undo). */
|
|
141
|
+
onChange?: (asset: FieldAsset | null) => void;
|
|
142
|
+
}
|
|
143
|
+
declare const FieldSingleAsset: import("svelte").Component<Props, {
|
|
144
|
+
validate: () => ValidationResult | undefined;
|
|
145
|
+
clearValidation: () => void;
|
|
146
|
+
getValidation: () => ValidationResult | undefined;
|
|
147
|
+
focus: () => void;
|
|
148
|
+
scrollIntoView: (opts?: ScrollIntoViewOptions) => void;
|
|
149
|
+
openFilePicker: () => void;
|
|
150
|
+
}, "value">;
|
|
151
|
+
type FieldSingleAsset = ReturnType<typeof FieldSingleAsset>;
|
|
152
|
+
export default FieldSingleAsset;
|
|
@@ -4,25 +4,26 @@ A comprehensive form input system with multiple field components, validation sup
|
|
|
4
4
|
|
|
5
5
|
## Components
|
|
6
6
|
|
|
7
|
-
| Component
|
|
8
|
-
|
|
|
9
|
-
| `FieldInput`
|
|
10
|
-
| `FieldMoney`
|
|
11
|
-
| `FieldDate`
|
|
12
|
-
| `FieldDateRange`
|
|
13
|
-
| `FieldTextarea`
|
|
14
|
-
| `FieldSelect`
|
|
15
|
-
| `FieldCheckbox`
|
|
16
|
-
| `FieldRadios`
|
|
17
|
-
| `FieldSwitch`
|
|
18
|
-
| `FieldFile`
|
|
19
|
-
| `FieldAssets`
|
|
20
|
-
| `
|
|
21
|
-
| `
|
|
22
|
-
| `
|
|
23
|
-
| `
|
|
24
|
-
| `
|
|
25
|
-
| `
|
|
7
|
+
| Component | Description |
|
|
8
|
+
| ------------------ | -------------------------------------------------------------- |
|
|
9
|
+
| `FieldInput` | Text, email, password, number, and other input types |
|
|
10
|
+
| `FieldMoney` | Money amount stored as integer minor units (cents) |
|
|
11
|
+
| `FieldDate` | Single calendar date — trigger + dialog, or embedded calendar |
|
|
12
|
+
| `FieldDateRange` | Inclusive date range (`start` … `end`), same two presentations |
|
|
13
|
+
| `FieldTextarea` | Multi-line text input with auto-grow |
|
|
14
|
+
| `FieldSelect` | Dropdown select with option groups |
|
|
15
|
+
| `FieldCheckbox` | Single checkbox with label |
|
|
16
|
+
| `FieldRadios` | Radio button group |
|
|
17
|
+
| `FieldSwitch` | Toggle switch field |
|
|
18
|
+
| `FieldFile` | File upload input |
|
|
19
|
+
| `FieldAssets` | Asset/image upload with preview |
|
|
20
|
+
| `FieldSingleAsset` | One asset (avatar, logo, cover, one document) — see below |
|
|
21
|
+
| `FieldKeyValues` | Key-value pairs editor with JSON serialization |
|
|
22
|
+
| `FieldTable` | Rows × typed columns editor (a list of records) — see below |
|
|
23
|
+
| `FieldLikeButton` | Like/favorite toggle button |
|
|
24
|
+
| `Fieldset` | Fieldset with legend |
|
|
25
|
+
| `Honeypot` | Hidden anti-bot trap field (server-less) |
|
|
26
|
+
| `TimeTrap` | Anti-bot submit-timing primitive (server-less) |
|
|
26
27
|
|
|
27
28
|
## Common Props (FieldInput, FieldTextarea, FieldSelect)
|
|
28
29
|
|
|
@@ -677,8 +678,9 @@ all mounted pasteable fields):
|
|
|
677
678
|
anywhere in the field focuses it, and a `:focus-within` ring on the input box signals the
|
|
678
679
|
paste-ready state;
|
|
679
680
|
- a paste with **no focus anywhere** (fresh page — focus parked on `<body>`) is routed to
|
|
680
|
-
the field as long as it is the _only_ pasteable (and visible)
|
|
681
|
-
a bare Ctrl/Cmd-V works
|
|
681
|
+
the field as long as it is the _only_ pasteable (and visible) field on the page —
|
|
682
|
+
`FieldAssets` and `FieldSingleAsset` share one registry — so a bare Ctrl/Cmd-V works
|
|
683
|
+
with no prior click;
|
|
682
684
|
- focus elsewhere is respected: pasting while a text input, textarea, select,
|
|
683
685
|
contenteditable (even one nested _inside_ the field via the `label`/`description`/`below`
|
|
684
686
|
snippets) or any other widget holds focus is never hijacked. With several pasteable fields
|
|
@@ -756,6 +758,252 @@ until it settles, and a rejection is caught so a failed download never breaks th
|
|
|
756
758
|
|
|
757
759
|
---
|
|
758
760
|
|
|
761
|
+
## FieldSingleAsset
|
|
762
|
+
|
|
763
|
+
One asset — a profile picture, a logo, a cover image, a single contract PDF. `FieldAssets`
|
|
764
|
+
with `cardinality={1}` keeps the "many" interaction model (an add button that errors once
|
|
765
|
+
the limit is hit, delete only inside the lightbox, a grid of small tiles). This field is
|
|
766
|
+
built around a single tile instead:
|
|
767
|
+
|
|
768
|
+
- **The tile is the picker and the drop target.** Click it, drop onto the field, or (opt-in)
|
|
769
|
+
paste — every source _replaces_ what is there. Two files at once are refused.
|
|
770
|
+
- **Remove inline**, with an **Undo** offered for `undoTtl` ms (the asset is only unlinked
|
|
771
|
+
from `value`, never deleted anywhere, so undo is lossless). Focus returns to the tile. An
|
|
772
|
+
async `onBeforeRemove` gets a busy state for its round trip (spinner on the Remove
|
|
773
|
+
control, tile inert, second click ignored) — so it may be the real server-side delete.
|
|
774
|
+
- **Shape / fit / size presets**: `shape="circle"` for avatars, `shape="wide"` (16:9) for
|
|
775
|
+
banners, `fit="contain"` for logos that must never be cropped; `size` is `sm` / `md` / `lg`
|
|
776
|
+
(5 / 8 / 12rem tall) or any CSS length.
|
|
777
|
+
- **Optimistic preview + progress** — a spinner, or a ring driven by `onProgress` with
|
|
778
|
+
`withOnProgress`.
|
|
779
|
+
- **Rollback on failure.** `value` is only rewritten when the upload _resolves_. A rejection
|
|
780
|
+
keeps the previous asset, shows the error on the tile with **Retry** (same file) and
|
|
781
|
+
**Discard**, and reports through `notifications` — unless `onUploadError` returns `false`
|
|
782
|
+
because the page shows that failure its own way. X during an upload cancels it (a late
|
|
783
|
+
resolution is ignored).
|
|
784
|
+
- **Client-side checks** before any bytes move: `accept` (also for drops and pastes),
|
|
785
|
+
`maxSize`, a custom async `validateFile`, and a `transformFile` seam for downscaling a
|
|
786
|
+
photo — or plugging in a cropper later.
|
|
787
|
+
- **Preview** (the `AssetsPreview` lightbox: zoom, download, delete) as a secondary action.
|
|
788
|
+
- `disabled` really disables (no drop, no paste, no remove — preview stays); without
|
|
789
|
+
`processAsset` the field is display-only; `isLoading` renders a skeleton in the tile's
|
|
790
|
+
shape.
|
|
791
|
+
|
|
792
|
+
```svelte
|
|
793
|
+
<script lang="ts">
|
|
794
|
+
import { FieldSingleAsset, type FieldAsset } from "@marianmeres/stuic";
|
|
795
|
+
|
|
796
|
+
let value = $state("");
|
|
797
|
+
|
|
798
|
+
async function processAsset(
|
|
799
|
+
asset: FieldAsset,
|
|
800
|
+
{ file, onProgress }: { file: File; onProgress: (p: number) => void }
|
|
801
|
+
): Promise<FieldAsset> {
|
|
802
|
+
const body = new FormData();
|
|
803
|
+
body.append("file", file);
|
|
804
|
+
const res = await fetch("/api/avatar", { method: "POST", body });
|
|
805
|
+
if (!res.ok) throw new Error(`Upload failed (${res.status})`);
|
|
806
|
+
const stored = await res.json();
|
|
807
|
+
return { id: stored.id, url: stored.url, name: file.name, type: file.type };
|
|
808
|
+
}
|
|
809
|
+
</script>
|
|
810
|
+
|
|
811
|
+
<FieldSingleAsset
|
|
812
|
+
bind:value
|
|
813
|
+
name="avatar"
|
|
814
|
+
label="Profile picture"
|
|
815
|
+
shape="circle"
|
|
816
|
+
accept="image/*"
|
|
817
|
+
capture="user"
|
|
818
|
+
maxSize={2 * 1024 * 1024}
|
|
819
|
+
{processAsset}
|
|
820
|
+
withOnProgress
|
|
821
|
+
pasteable
|
|
822
|
+
required
|
|
823
|
+
/>
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
### Value
|
|
827
|
+
|
|
828
|
+
`value` is the JSON of **one** `FieldAsset` object, or `""` when empty — not an array. It
|
|
829
|
+
changes only when a user action settles: an upload that resolved, a remove, an undo. The
|
|
830
|
+
form never sees a blob asset, and `onChange` fires exactly on those changes.
|
|
831
|
+
|
|
832
|
+
For another shape — e.g. a backend that stores every relation as a list — pass
|
|
833
|
+
`parseValue` / `serializeValue`:
|
|
834
|
+
|
|
835
|
+
```svelte
|
|
836
|
+
<FieldSingleAsset
|
|
837
|
+
bind:value
|
|
838
|
+
name="logo"
|
|
839
|
+
parseValue={(s) => JSON.parse(s || "[]")[0] ?? null}
|
|
840
|
+
serializeValue={(a) => JSON.stringify(a ? [a] : [])}
|
|
841
|
+
/>
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
### Upload
|
|
845
|
+
|
|
846
|
+
`processAsset(asset, { file, onProgress })` receives the optimistic asset (its `id` and
|
|
847
|
+
every `url` are one blob URL of the file; `meta.size` is the byte size) plus the `file`
|
|
848
|
+
itself — already run through `transformFile` — and `onProgress(0–100)`. Resolve with the
|
|
849
|
+
stored asset: it becomes `value` as is (keep the blob URL as `url.thumb` if you like — it is
|
|
850
|
+
revoked only when the field unmounts).
|
|
851
|
+
|
|
852
|
+
Checks run in this order and the first failure stops with a message (via `notifications`,
|
|
853
|
+
or `alert` without one):
|
|
854
|
+
|
|
855
|
+
one file only → `accept` → `onBeforeReplace` → `transformFile` → `maxSize` → `validateFile`
|
|
856
|
+
→ `processAsset`
|
|
857
|
+
|
|
858
|
+
### When the failure is yours to show (`onUploadError`)
|
|
859
|
+
|
|
860
|
+
Some rejections are not failures but product states — a 402 "plan limit reached" that the
|
|
861
|
+
page already renders as an upgrade panel. Without a hook the field would stack its generic
|
|
862
|
+
toast on top of that panel. `onUploadError(error, { asset, file })` gets the raw rejection
|
|
863
|
+
first; return `false` to skip the toast. The tile still shows the error with Retry / Discard
|
|
864
|
+
(the user may come back to it after upgrading), so the override is deliberately that narrow:
|
|
865
|
+
|
|
866
|
+
```svelte
|
|
867
|
+
<script lang="ts">
|
|
868
|
+
let gated = $state<string | null>(null);
|
|
869
|
+
</script>
|
|
870
|
+
|
|
871
|
+
{#if gated}
|
|
872
|
+
<UpgradeNotice message={gated} />
|
|
873
|
+
{/if}
|
|
874
|
+
|
|
875
|
+
<FieldSingleAsset
|
|
876
|
+
...
|
|
877
|
+
onUploadError={(e) => {
|
|
878
|
+
if ((e as any)?.status === 402) {
|
|
879
|
+
gated = (e as Error).message;
|
|
880
|
+
return false; // handled above — no toast
|
|
881
|
+
}
|
|
882
|
+
}}
|
|
883
|
+
/>
|
|
884
|
+
```
|
|
885
|
+
|
|
886
|
+
### Removing the server copy too (`onBeforeRemove`)
|
|
887
|
+
|
|
888
|
+
By default a remove only unlinks the asset from `value` (hence the lossless Undo). When the
|
|
889
|
+
field owns a file that must go away on the server as well, do the `DELETE` inside
|
|
890
|
+
`onBeforeRemove` and resolve with whether it succeeded — the field clears `value` only then.
|
|
891
|
+
The round trip gets a busy state (spinner on the Remove control, `data-state="removing"`,
|
|
892
|
+
tile and controls inert, a second Remove ignored). Pair it with `undoTtl={0}`: restoring the
|
|
893
|
+
local value would lie about a file that is already gone.
|
|
894
|
+
|
|
895
|
+
```svelte
|
|
896
|
+
<FieldSingleAsset
|
|
897
|
+
...
|
|
898
|
+
undoTtl={0}
|
|
899
|
+
onBeforeRemove={async (asset) => {
|
|
900
|
+
const res = await fetch(`/api/logo/${asset.id}`, { method: "DELETE" });
|
|
901
|
+
return res.ok;
|
|
902
|
+
}}
|
|
903
|
+
/>
|
|
904
|
+
```
|
|
905
|
+
|
|
906
|
+
### Downscale or crop before upload (`transformFile`)
|
|
907
|
+
|
|
908
|
+
```svelte
|
|
909
|
+
<FieldSingleAsset ... transformFile={(file) => downscale(file, 512)} />
|
|
910
|
+
```
|
|
911
|
+
|
|
912
|
+
Return the file to upload, or `null` / `undefined` to cancel silently (the user closed your
|
|
913
|
+
cropper). `maxSize` and `validateFile` see the transformed file, so a 12 MP phone photo
|
|
914
|
+
downscaled on the client passes a 2 MB cap. A cropper is just a `transformFile` that opens
|
|
915
|
+
a dialog and resolves with the cropped file.
|
|
916
|
+
|
|
917
|
+
### Props
|
|
918
|
+
|
|
919
|
+
| Prop | Type | Default | Description |
|
|
920
|
+
| ---------------------------------------------------------- | ------------------------------------------------------ | ------------------ | ----------------------------------------------------------------------- |
|
|
921
|
+
| `value` | `string` | required, bindable | JSON of one `FieldAsset`, or `""` |
|
|
922
|
+
| `name` | `string` | required | The hidden input's name |
|
|
923
|
+
| `processAsset` | `(asset, { file, onProgress }) => Promise<FieldAsset>` | - | The upload. Without it the field is display-only |
|
|
924
|
+
| `withOnProgress` | `boolean` | `false` | Progress ring instead of a spinner |
|
|
925
|
+
| `onUploadError` | `(error, { asset, file }) => void \| boolean` | - | On a rejected upload, before the toast; `false` skips the toast |
|
|
926
|
+
| `accept` | `string` | - | HTML `accept` tokens (MIME, `image/*`, `.pdf`); applied to drops/pastes |
|
|
927
|
+
| `capture` | `"user" \| "environment"` | - | Passed to the file input: phones open the camera directly |
|
|
928
|
+
| `maxSize` | `number` | - | Max bytes, checked after `transformFile` |
|
|
929
|
+
| `validateFile` | `(file) => string \| void \| Promise<...>` | - | Non-empty string rejects with that message |
|
|
930
|
+
| `transformFile` | `(file) => File \| null \| Promise<...>` | - | Pre-upload hook; `null` cancels |
|
|
931
|
+
| `onBeforeRemove` | `(asset) => boolean \| Promise<boolean>` | - | `false` keeps the asset; busy state while a promise settles |
|
|
932
|
+
| `onBeforeReplace` | `(current, file) => boolean \| Promise<boolean>` | - | `false` keeps the current asset |
|
|
933
|
+
| `undoTtl` | `number` | `6000` | ms the inline Undo stays after a remove; `0` disables |
|
|
934
|
+
| `pasteable` | `boolean` | `false` | Accept Ctrl/Cmd-V (same routing as `FieldAssets`) |
|
|
935
|
+
| `shape` | `"square" \| "circle" \| "wide"` | `"square"` | Tile shape |
|
|
936
|
+
| `fit` | `"cover" \| "contain"` | `"cover"` | How an image fills the tile |
|
|
937
|
+
| `size` | `"sm" \| "md" \| "lg" \| string` | `"md"` | Tile height: preset or CSS length |
|
|
938
|
+
| `placeholder` | `THC` | - | Empty-tile content (e.g. an `Avatar` with initials) |
|
|
939
|
+
| `noPreview`, `noDownload` | `boolean` | `false` | Hide the Preview action / the lightbox's Download |
|
|
940
|
+
| `onDownload` | `(asset) => void \| Promise<void>` | - | Replaces the lightbox's default download (auth-gated bytes) |
|
|
941
|
+
| `onChange` | `(asset \| null) => void` | - | After every user-driven change of `value` |
|
|
942
|
+
| `parseValue`, `serializeValue` | see Value | JSON | Custom `value` shape |
|
|
943
|
+
| `isLoading` | `boolean` | `false` | Skeleton while the initial value is fetched |
|
|
944
|
+
| `notifications` | `NotificationsStack` | - | Where rejections and upload failures are reported (else `alert`) |
|
|
945
|
+
| `t` | `TranslateFn` | English | See i18n |
|
|
946
|
+
| `classWrap`, `classPreview`, `classControls`, `classInput` | `string` | - | Drop zone / tile / action buttons / hidden file input |
|
|
947
|
+
|
|
948
|
+
Plus the usual field props: `label`, `description`, `labelAfter`, `below`, `id`, `tabindex`,
|
|
949
|
+
`renderSize`, `required`, `disabled`, `validate`, `labelLeft*`, `style`, `class`, and the
|
|
950
|
+
shared `InputWrapClassProps`. The imperative API is the standard one — `validate()`,
|
|
951
|
+
`clearValidation()`, `getValidation()`, `focus()` (the tile), `scrollIntoView()` — plus
|
|
952
|
+
`openFilePicker()`.
|
|
953
|
+
|
|
954
|
+
### i18n
|
|
955
|
+
|
|
956
|
+
All UI texts go through `t`. English is built in; Slovak ships bundled and opt-in:
|
|
957
|
+
|
|
958
|
+
```svelte
|
|
959
|
+
<script>
|
|
960
|
+
import {
|
|
961
|
+
FieldSingleAsset,
|
|
962
|
+
createFieldSingleAssetT,
|
|
963
|
+
FIELD_SINGLE_ASSET_MESSAGES_SK,
|
|
964
|
+
} from "@marianmeres/stuic";
|
|
965
|
+
const t = createFieldSingleAssetT(FIELD_SINGLE_ASSET_MESSAGES_SK);
|
|
966
|
+
</script>
|
|
967
|
+
|
|
968
|
+
<FieldSingleAsset bind:value name="avatar" {processAsset} {t} />
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
`createFieldSingleAssetT(messages, fallbackMessages?)` falls back to
|
|
972
|
+
`FIELD_SINGLE_ASSET_MESSAGES_EN` for any key the catalog does not define. The catalog also
|
|
973
|
+
carries the keys of the embedded `AssetsPreview`, so one `t` serves both.
|
|
974
|
+
|
|
975
|
+
### Accessibility
|
|
976
|
+
|
|
977
|
+
- The field's `<label>` targets the tile button; the tile's accessible description says what
|
|
978
|
+
pressing it does ("Choose a file" / "Replace x.jpg").
|
|
979
|
+
- Remove / Preview / Retry / Discard are real named buttons, revealed on hover or focus,
|
|
980
|
+
always visible on touch, and on a failed upload.
|
|
981
|
+
- Uploading, uploaded, failed, removed and restored are announced through a polite live
|
|
982
|
+
region; a remove or undo moves focus back to the tile.
|
|
983
|
+
|
|
984
|
+
### CSS Variables
|
|
985
|
+
|
|
986
|
+
| Variable | Default | Description |
|
|
987
|
+
| ----------------------------------------------------- | -------------------------------- | --------------------------------------------------- |
|
|
988
|
+
| `--stuic-field-single-asset-size-{sm,md,lg}` | `5rem` / `8rem` / `12rem` | Tile height per `size` preset |
|
|
989
|
+
| `--stuic-field-single-asset-size` | (unset) | Explicit tile height, wins over the preset |
|
|
990
|
+
| `--stuic-field-single-asset-wide-ratio` | `16 / 9` | Aspect ratio of `shape="wide"` |
|
|
991
|
+
| `--stuic-field-single-asset-preview-bg` | `--stuic-color-muted` | Tile background (visible behind `fit="contain"`) |
|
|
992
|
+
| `--stuic-field-single-asset-preview-border` | `--stuic-color-border` | Tile border (dashed while empty) |
|
|
993
|
+
| `--stuic-field-single-asset-preview-border-hover` | `--stuic-color-ring` | Tile border on hover |
|
|
994
|
+
| `--stuic-field-single-asset-placeholder-text` | `--stuic-color-muted-foreground` | Empty-tile icon color |
|
|
995
|
+
| `--stuic-field-single-asset-meta-text` | `--stuic-color-muted-foreground` | The meta line / hint / undo line |
|
|
996
|
+
| `--stuic-field-single-asset-control-bg` / `-bg-hover` | `rgb(0 0 0 / 0.6)` / `0.8` | Action buttons |
|
|
997
|
+
| `--stuic-field-single-asset-control-text` | `#fff` | Action button icon color |
|
|
998
|
+
| `--stuic-field-single-asset-overlay-bg` | `rgb(0 0 0 / 0.4)` | Progress overlay |
|
|
999
|
+
| `--stuic-field-single-asset-error-color` | `--stuic-input-accent-error` | Failed-upload border + overlay tint |
|
|
1000
|
+
| `--stuic-field-single-asset-radius` | `--stuic-radius` | Tile radius (usage-site fallback; `circle` ignores) |
|
|
1001
|
+
| `--stuic-field-single-asset-control-radius` | `--stuic-radius-button` | Action button radius (usage-site fallback) |
|
|
1002
|
+
| `--stuic-field-single-asset-border-width` | `--stuic-border-width` | Tile border width (usage-site fallback) |
|
|
1003
|
+
| `--stuic-field-single-asset-transition` | `--stuic-transition` | Hover / reveal transitions (usage-site fallback) |
|
|
1004
|
+
|
|
1005
|
+
---
|
|
1006
|
+
|
|
759
1007
|
## Date and date range fields
|
|
760
1008
|
|
|
761
1009
|
`FieldDate` picks one calendar date, `FieldDateRange` an inclusive `start` … `end` pair.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Does a file pass an `accept` attribute value? Shared by `FieldAssets` and
|
|
3
|
+
* `FieldSingleAsset`.
|
|
4
|
+
*
|
|
5
|
+
* Tokens are the HTML `accept` ones, comma separated: a MIME type
|
|
6
|
+
* (`image/png`), a wildcard MIME (`image/*`, `*`), or an extension (`.pdf`).
|
|
7
|
+
* MIME tokens are matched as prefixes of the file's `type`; extension tokens
|
|
8
|
+
* are matched against the end of the file's `name` (the browser's own picker
|
|
9
|
+
* filters by the same rule, so a drop and a pick agree). An empty `accept`
|
|
10
|
+
* accepts everything; so does a file with an unknown (empty) `type` when the
|
|
11
|
+
* token is a MIME one — we cannot tell, and the picker would have let it
|
|
12
|
+
* through too.
|
|
13
|
+
*/
|
|
14
|
+
export declare function isAcceptedType(allowedAccept?: string, type?: string, name?: string): boolean;
|
|
15
|
+
/** `1234567` -> `"1.2 MB"` (1024-based, at most one decimal below 10). */
|
|
16
|
+
export declare function formatBytes(bytes: number): string;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Does a file pass an `accept` attribute value? Shared by `FieldAssets` and
|
|
3
|
+
* `FieldSingleAsset`.
|
|
4
|
+
*
|
|
5
|
+
* Tokens are the HTML `accept` ones, comma separated: a MIME type
|
|
6
|
+
* (`image/png`), a wildcard MIME (`image/*`, `*`), or an extension (`.pdf`).
|
|
7
|
+
* MIME tokens are matched as prefixes of the file's `type`; extension tokens
|
|
8
|
+
* are matched against the end of the file's `name` (the browser's own picker
|
|
9
|
+
* filters by the same rule, so a drop and a pick agree). An empty `accept`
|
|
10
|
+
* accepts everything; so does a file with an unknown (empty) `type` when the
|
|
11
|
+
* token is a MIME one — we cannot tell, and the picker would have let it
|
|
12
|
+
* through too.
|
|
13
|
+
*/
|
|
14
|
+
export function isAcceptedType(allowedAccept, type, name) {
|
|
15
|
+
if (!allowedAccept)
|
|
16
|
+
return true;
|
|
17
|
+
const tokens = (allowedAccept ?? "")
|
|
18
|
+
.split(",")
|
|
19
|
+
.map((v) => `${v || ""}`.trim().toLowerCase())
|
|
20
|
+
.filter(Boolean);
|
|
21
|
+
if (!tokens.length)
|
|
22
|
+
return true;
|
|
23
|
+
const _type = `${type ?? ""}`.toLowerCase();
|
|
24
|
+
const _name = `${name ?? ""}`.toLowerCase();
|
|
25
|
+
return tokens.some((tok) => {
|
|
26
|
+
if (tok.startsWith("."))
|
|
27
|
+
return !!_name && _name.endsWith(tok);
|
|
28
|
+
// unknown type: cannot decide, let it through (legacy behavior)
|
|
29
|
+
if (!_type)
|
|
30
|
+
return true;
|
|
31
|
+
const prefix = tok.includes("*") ? tok.slice(0, tok.indexOf("*")) : tok;
|
|
32
|
+
return _type.startsWith(prefix);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/** `1234567` -> `"1.2 MB"` (1024-based, at most one decimal below 10). */
|
|
36
|
+
export function formatBytes(bytes) {
|
|
37
|
+
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
38
|
+
let v = Math.max(0, Number(bytes) || 0);
|
|
39
|
+
let i = 0;
|
|
40
|
+
while (v >= 1024 && i < units.length - 1) {
|
|
41
|
+
v /= 1024;
|
|
42
|
+
i++;
|
|
43
|
+
}
|
|
44
|
+
const rounded = i === 0 ? Math.round(v) : parseFloat(v.toFixed(v < 10 ? 1 : 0));
|
|
45
|
+
return `${rounded} ${units[i]}`;
|
|
46
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type PasteTarget = {
|
|
2
|
+
el: HTMLElement;
|
|
3
|
+
handle: (e: ClipboardEvent) => void;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* Registers a pasteable field. Returns the unregister function. The document
|
|
7
|
+
* listener is installed with the first registration and removed with the last.
|
|
8
|
+
*/
|
|
9
|
+
export declare function registerPasteTarget(t: PasteTarget): () => void;
|
|
10
|
+
/**
|
|
11
|
+
* The file entries of a paste. Prefers `items` (lets us keep only file-kind
|
|
12
|
+
* entries, e.g. a pasted screenshot); falls back to `.files` for browsers that
|
|
13
|
+
* only populate that. Empty for a plain-text paste.
|
|
14
|
+
*/
|
|
15
|
+
export declare function extractClipboardFiles(e: ClipboardEvent): File[];
|