@krak-stack/assets 0.1.4 → 0.1.7

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.
Files changed (86) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +174 -20
  3. package/dist/access.d.ts +44 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +56 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/api.builder.d.ts +100 -0
  8. package/dist/api.builder.d.ts.map +1 -0
  9. package/dist/api.builder.js +233 -0
  10. package/dist/api.builder.js.map +1 -0
  11. package/dist/api.d.ts +2 -0
  12. package/dist/api.d.ts.map +1 -0
  13. package/dist/api.group.d.ts +222 -0
  14. package/dist/api.group.d.ts.map +1 -0
  15. package/dist/api.group.js +83 -0
  16. package/dist/api.group.js.map +1 -0
  17. package/dist/api.js +2 -0
  18. package/dist/api.js.map +1 -0
  19. package/dist/catalog.d.ts +91 -0
  20. package/dist/catalog.d.ts.map +1 -0
  21. package/dist/catalog.js +52 -0
  22. package/dist/catalog.js.map +1 -0
  23. package/dist/client.d.ts +245 -0
  24. package/dist/client.d.ts.map +1 -0
  25. package/dist/client.js +8 -0
  26. package/dist/client.js.map +1 -0
  27. package/dist/commands.d.ts +55 -0
  28. package/dist/commands.d.ts.map +1 -0
  29. package/dist/commands.js +127 -0
  30. package/dist/commands.js.map +1 -0
  31. package/dist/components/asset-input/html.d.ts +72 -0
  32. package/dist/components/asset-input/html.d.ts.map +1 -0
  33. package/dist/components/asset-input/html.js +1574 -0
  34. package/dist/components/asset-input/html.js.map +1 -0
  35. package/dist/components/asset-input/index.d.ts +331 -0
  36. package/dist/components/asset-input/react.d.ts +32 -0
  37. package/dist/components/asset-input/react.d.ts.map +1 -0
  38. package/dist/components/asset-input/react.js +2297 -0
  39. package/dist/components/asset-input/react.js.map +1 -0
  40. package/dist/components/asset-input/schema.d.ts +108 -0
  41. package/dist/components/asset-input/upload.d.ts +15 -0
  42. package/dist/components/asset-table/html.d.ts +110 -0
  43. package/dist/components/asset-table/html.d.ts.map +1 -0
  44. package/dist/components/asset-table/html.js +4994 -0
  45. package/dist/components/asset-table/html.js.map +1 -0
  46. package/dist/components/asset-table/index.d.ts +324 -0
  47. package/dist/components/asset-table/react.d.ts +22 -0
  48. package/dist/components/asset-table/react.d.ts.map +1 -0
  49. package/dist/components/asset-table/react.js +8317 -0
  50. package/dist/components/asset-table/react.js.map +1 -0
  51. package/dist/components/asset-table/schema.d.ts +73 -0
  52. package/dist/index.d.ts +215 -9
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +49 -24
  55. package/dist/index.js.map +1 -1
  56. package/dist/migrations/0004_upload_intents.d.ts +5 -0
  57. package/dist/migrations/0004_upload_intents.d.ts.map +1 -0
  58. package/dist/migrations/0004_upload_intents.js +14 -0
  59. package/dist/migrations/0004_upload_intents.js.map +1 -0
  60. package/dist/migrations.d.ts.map +1 -1
  61. package/dist/migrations.js +2 -0
  62. package/dist/migrations.js.map +1 -1
  63. package/dist/queries.d.ts +6 -0
  64. package/dist/queries.d.ts.map +1 -0
  65. package/dist/queries.js +18 -0
  66. package/dist/queries.js.map +1 -0
  67. package/dist/retrieval.d.ts +6 -1
  68. package/dist/retrieval.d.ts.map +1 -1
  69. package/dist/retrieval.js +48 -17
  70. package/dist/retrieval.js.map +1 -1
  71. package/dist/schema.d.ts +116 -1
  72. package/dist/schema.d.ts.map +1 -1
  73. package/dist/schema.js +88 -1
  74. package/dist/schema.js.map +1 -1
  75. package/dist/services/assets/library.d.ts +276 -0
  76. package/dist/services/assets/library.d.ts.map +1 -0
  77. package/dist/services/assets/library.js +122 -0
  78. package/dist/services/assets/library.js.map +1 -0
  79. package/dist/services/assets/schema.d.ts +3 -0
  80. package/dist/services/assets/url.d.ts +12 -0
  81. package/dist/services/assets/use-library.d.ts +20 -0
  82. package/dist/workflows.d.ts +2 -0
  83. package/dist/workflows.d.ts.map +1 -1
  84. package/dist/workflows.js +2 -0
  85. package/dist/workflows.js.map +1 -1
  86. package/package.json +44 -8
@@ -0,0 +1,1574 @@
1
+ // ../assets/src/components/asset-input/html.ts
2
+ import { Effect as Effect4, Layer, Redacted as Redacted4 } from "effect";
3
+ import { AsyncResult as AsyncResult2 } from "effect/reactivity";
4
+ import { Component as Component7 } from "effect/ui";
5
+ import { Html as Html4 } from "effect/ui/html";
6
+ import { Dialog, Field } from "effect/ui/kit";
7
+ import { Button as Button3, buttonVariants as buttonVariants3 } from "@/components/effectcn/button";
8
+ import {
9
+ DialogBackdrop,
10
+ DialogDescription,
11
+ DialogHeader,
12
+ DialogPopup,
13
+ DialogTitle,
14
+ DialogViewport
15
+ } from "@/components/effectcn/dialog";
16
+ import { FieldLabel, FieldRoot } from "@/components/effectcn/field";
17
+
18
+ // ../../src/components/file-input/html.ts
19
+ import { Effect, Redacted as Redacted2, Schema as Schema3, Stream } from "effect";
20
+ import { Component as Component2, Mount } from "effect/ui";
21
+ import { Html } from "effect/ui/html";
22
+ import { Button, buttonVariants } from "@/components/effectcn/button";
23
+ import {
24
+ FileDropHint,
25
+ FileDropIcon,
26
+ FileDropTitle,
27
+ fileDropZoneClass
28
+ } from "@/components/effectcn/file-drop";
29
+ import { krakstackLocaleRead } from "@krak-stack/registry/krakstack-provider/html";
30
+ import {
31
+ CloudUpload as UploadIcon,
32
+ File as FileIcon,
33
+ Captions,
34
+ Binary,
35
+ BookOpen,
36
+ Box,
37
+ CalendarDays,
38
+ Contact,
39
+ Database,
40
+ Disc3,
41
+ FileCode,
42
+ FileJson,
43
+ FileTerminal,
44
+ FileType,
45
+ Globe,
46
+ Mail,
47
+ Package,
48
+ Presentation,
49
+ FileArchive,
50
+ FileAudio,
51
+ FileImage,
52
+ FileSpreadsheet,
53
+ FileText,
54
+ FileVideo,
55
+ FileUp as ChooseIcon,
56
+ X as RemoveIcon
57
+ } from "@krak-stack/registry/lucide-effect";
58
+
59
+ // ../../src/lib/utils.ts
60
+ import { cn } from "cn";
61
+
62
+ // ../../src/components/file-input/classes.ts
63
+ var fileInputClasses = {
64
+ root: "grid min-w-0 grid-cols-1 gap-3"
65
+ };
66
+ var resolveFileInputClasses = (overrides) => ({
67
+ ...fileInputClasses,
68
+ ...overrides
69
+ });
70
+
71
+ // ../../src/components/file-input/file-type.ts
72
+ var fileType = (mimeType) => {
73
+ const type = mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
74
+ if (!type || type === "application/octet-stream")
75
+ return "file";
76
+ if (type.startsWith("image/"))
77
+ return "image";
78
+ if (type.startsWith("video/"))
79
+ return "video";
80
+ if (type.startsWith("audio/"))
81
+ return "audio";
82
+ if (type.startsWith("font/"))
83
+ return "font";
84
+ if (type.startsWith("model/"))
85
+ return "model";
86
+ if (type.startsWith("message/"))
87
+ return "mail";
88
+ if (type.endsWith("+json") || type === "application/json")
89
+ return "json";
90
+ if (type.includes("spreadsheet") || type.includes("ms-excel"))
91
+ return "spreadsheet";
92
+ if (type.includes("presentation") || type.includes("ms-powerpoint"))
93
+ return "presentation";
94
+ switch (type) {
95
+ case "text/vtt":
96
+ case "application/x-subrip":
97
+ case "application/ttml+xml":
98
+ return "caption";
99
+ case "application/zip":
100
+ case "application/x-zip-compressed":
101
+ case "application/x-7z-compressed":
102
+ case "application/vnd.rar":
103
+ case "application/x-rar-compressed":
104
+ case "application/x-tar":
105
+ case "application/gzip":
106
+ case "application/x-gzip":
107
+ case "application/x-bzip2":
108
+ case "application/x-xz":
109
+ case "application/zstd":
110
+ return "archive";
111
+ case "text/csv":
112
+ case "text/tab-separated-values":
113
+ return "spreadsheet";
114
+ case "text/html":
115
+ case "application/xhtml+xml":
116
+ return "web";
117
+ case "text/css":
118
+ case "text/javascript":
119
+ case "application/javascript":
120
+ case "text/typescript":
121
+ case "application/typescript":
122
+ case "application/yaml":
123
+ case "text/yaml":
124
+ case "application/toml":
125
+ return "code";
126
+ case "application/x-sh":
127
+ case "text/x-shellscript":
128
+ case "application/x-bat":
129
+ return "script";
130
+ case "application/sql":
131
+ case "application/vnd.sqlite3":
132
+ case "application/x-sqlite3":
133
+ return "database";
134
+ case "application/epub+zip":
135
+ case "application/x-mobipocket-ebook":
136
+ case "application/vnd.amazon.ebook":
137
+ return "book";
138
+ case "application/x-iso9660-image":
139
+ case "application/x-apple-diskimage":
140
+ return "disc";
141
+ case "application/vnd.android.package-archive":
142
+ case "application/x-debian-package":
143
+ case "application/x-rpm":
144
+ case "application/x-msi":
145
+ return "package";
146
+ case "application/wasm":
147
+ case "application/x-msdownload":
148
+ case "application/x-executable":
149
+ return "binary";
150
+ case "application/vnd.ms-fontobject":
151
+ case "application/font-woff":
152
+ case "application/x-font-ttf":
153
+ return "font";
154
+ case "application/vnd.ms-outlook":
155
+ return "mail";
156
+ case "text/calendar":
157
+ return "calendar";
158
+ case "text/vcard":
159
+ case "text/x-vcard":
160
+ return "contact";
161
+ case "application/xml":
162
+ case "text/xml":
163
+ return "code";
164
+ default:
165
+ if (type.endsWith("+xml") || type.startsWith("text/x-"))
166
+ return "code";
167
+ if (type.startsWith("text/") || type.includes("word") || type === "application/pdf" || type === "application/rtf")
168
+ return "document";
169
+ return "file";
170
+ }
171
+ };
172
+
173
+ // ../../src/components/file-input/index.ts
174
+ import { Redacted, Schema as Schema2 } from "effect";
175
+ import { Component, UiSchema } from "effect/ui";
176
+
177
+ // ../../src/components/file-input/schema.ts
178
+ import { Schema, Struct } from "effect";
179
+ var AcceptLabel = Schema.declare((value) => typeof value === "function").annotate({ identifier: "FilePickerAcceptLabel" });
180
+ var FilePickerFilesSchema = Schema.Redacted(Schema.Array(Schema.File)).annotate({ identifier: "FilePickerFiles" });
181
+ var FileInputClassesOverridesSchema = Schema.Record(Schema.Literals(Struct.keys(fileInputClasses)), Schema.optionalKey(Schema.String)).annotate({ identifier: "FileInputClassesOverrides" });
182
+ var FilePickerPropsSchema = Schema.Struct({
183
+ classes: Schema.optional(FileInputClassesOverridesSchema),
184
+ accept: Schema.optional(Schema.String),
185
+ canClear: Schema.optional(Schema.Boolean),
186
+ file: Schema.optional(Schema.File),
187
+ files: Schema.optional(Schema.Array(Schema.File)),
188
+ id: Schema.String,
189
+ image: Schema.optional(Schema.Struct({
190
+ alt: Schema.String,
191
+ height: Schema.Number,
192
+ src: Schema.optional(Schema.String),
193
+ width: Schema.Number
194
+ }).annotate({ identifier: "FilePickerImage" })),
195
+ invalid: Schema.optional(Schema.Boolean),
196
+ locale: Schema.optional(Schema.String),
197
+ messages: Schema.optional(Schema.Record(Schema.String, Schema.Struct({
198
+ accepts: Schema.optional(AcceptLabel),
199
+ chooseFile: Schema.optional(Schema.String),
200
+ chooseFiles: Schema.optional(Schema.String),
201
+ deleteFile: Schema.optional(Schema.String),
202
+ dropFile: Schema.optional(Schema.String),
203
+ dropFiles: Schema.optional(Schema.String),
204
+ replaceFile: Schema.optional(Schema.String)
205
+ }).annotate({ identifier: "FilePickerMessageOverrides" }))),
206
+ multiple: Schema.optional(Schema.Boolean),
207
+ name: Schema.String,
208
+ required: Schema.optional(Schema.Boolean),
209
+ showImageThumbnails: Schema.optionalKey(Schema.Boolean)
210
+ }).annotate({ identifier: "FilePickerProps" });
211
+
212
+ // ../../src/components/file-input/index.ts
213
+ var defaultMessages = {
214
+ en: {
215
+ accepts: (accepts) => `Accepts: ${accepts}`,
216
+ chooseFile: "Choose file",
217
+ chooseFiles: "Choose files",
218
+ deleteFile: "Delete",
219
+ dropFile: "Drag and drop a file here",
220
+ dropFiles: "Drag and drop files here",
221
+ replaceFile: "Replace file"
222
+ },
223
+ fr: {
224
+ accepts: (accepts) => `Accepte : ${accepts}`,
225
+ chooseFile: "Choisir un fichier",
226
+ chooseFiles: "Choisir des fichiers",
227
+ deleteFile: "Supprimer",
228
+ dropFile: "Glissez-déposez un fichier ici",
229
+ dropFiles: "Glissez-déposez des fichiers ici",
230
+ replaceFile: "Remplacer le fichier"
231
+ }
232
+ };
233
+ var filePickerMessages = (locale = "en", translations) => ({
234
+ ...locale.startsWith("fr") ? defaultMessages.fr : defaultMessages.en,
235
+ ...translations?.[locale.split("-")[0] ?? locale],
236
+ ...translations?.[locale]
237
+ });
238
+ var formatBytes = (bytes, locale) => {
239
+ const units = [
240
+ "byte",
241
+ "kilobyte",
242
+ "megabyte",
243
+ "gigabyte",
244
+ "terabyte"
245
+ ];
246
+ const index = Math.min(bytes === 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
247
+ const value = index === 0 ? bytes : Number((bytes / 1024 ** index).toFixed(1));
248
+ return new Intl.NumberFormat(locale, {
249
+ style: "unit",
250
+ unit: units[index],
251
+ unitDisplay: "short"
252
+ }).format(value);
253
+ };
254
+ var fileDescription = (file, locale) => [
255
+ (file.name.includes(".") ? file.name.split(".").pop()?.toUpperCase() : "") || file.type.split("/").pop()?.toUpperCase(),
256
+ formatBytes(file.size, locale)
257
+ ].filter(Boolean).join(" · ");
258
+ var filePickerKey = ({ name, size, lastModified }) => `${name}:${size}:${lastModified}`;
259
+ var mergePickedFiles = (files, added) => Array.from(new Map([...files, ...added].map((file) => [filePickerKey(file), file])).values());
260
+ var FilePickerMessage = UiSchema.TaggedEnum({
261
+ Selected: { files: FilePickerFilesSchema },
262
+ Dropped: { files: FilePickerFilesSchema },
263
+ Removed: { index: Schema2.Int },
264
+ Cleared: {},
265
+ Blurred: {},
266
+ DragEntered: {},
267
+ DragLeft: {}
268
+ }).annotate({ identifier: "FilePickerMessage" });
269
+ var FilePickerEvents = UiSchema.TaggedEnum({
270
+ Change: { file: Schema2.Redacted(Schema2.File) },
271
+ FilesChange: { files: FilePickerFilesSchema },
272
+ Clear: {},
273
+ Blur: {}
274
+ }).annotate({ identifier: "FilePickerEvents" });
275
+ var filePickerOptions = {
276
+ name: "FilePicker",
277
+ props: FilePickerPropsSchema,
278
+ model: Schema2.Int,
279
+ message: FilePickerMessage,
280
+ events: FilePickerEvents,
281
+ restore: false
282
+ };
283
+ var selectFiles = ($, files, dropped) => {
284
+ const events = [];
285
+ if (files.length > 0) {
286
+ if ($.props.multiple) {
287
+ events.push(FilePickerEvents.FilesChange({
288
+ files: Redacted.make(mergePickedFiles($.props.files ?? [], files))
289
+ }));
290
+ } else if (files[0]) {
291
+ events.push(FilePickerEvents.Change({ file: Redacted.make(files[0]) }));
292
+ }
293
+ }
294
+ if (dropped)
295
+ events.push(FilePickerEvents.Blur());
296
+ return $.set(dropped ? 0 : $.model).emit(...events);
297
+ };
298
+ var filePickerBehaviours = {
299
+ init: () => 0,
300
+ update: Component.define(filePickerOptions).update({
301
+ Selected: ($, { files }) => selectFiles($, Redacted.value(files), false),
302
+ Dropped: ($, { files }) => selectFiles($, Redacted.value(files), true),
303
+ Removed: ($, { index }) => $.set($.model).emit(FilePickerEvents.FilesChange({
304
+ files: Redacted.make(($.props.files ?? []).filter((_, position) => position !== index))
305
+ })),
306
+ Cleared: ($) => $.set($.model).emit(FilePickerEvents.Clear()),
307
+ Blurred: ($) => $.set($.model).emit(FilePickerEvents.Blur()),
308
+ DragEntered: ($) => $.model + 1,
309
+ DragLeft: ($) => Math.max(0, $.model - 1)
310
+ })
311
+ };
312
+
313
+ // ../../src/components/file-input/html.ts
314
+ var fileIcons = {
315
+ file: FileIcon,
316
+ archive: FileArchive,
317
+ binary: Binary,
318
+ book: BookOpen,
319
+ calendar: CalendarDays,
320
+ code: FileCode,
321
+ contact: Contact,
322
+ database: Database,
323
+ disc: Disc3,
324
+ font: FileType,
325
+ json: FileJson,
326
+ mail: Mail,
327
+ model: Box,
328
+ package: Package,
329
+ presentation: Presentation,
330
+ script: FileTerminal,
331
+ web: Globe,
332
+ image: FileImage,
333
+ video: FileVideo,
334
+ audio: FileAudio,
335
+ caption: Captions,
336
+ spreadsheet: FileSpreadsheet,
337
+ document: FileText
338
+ };
339
+ var fileTypeIconRenderer = (mimeType) => fileIcons[fileType(mimeType)];
340
+ var FileTypeIcon = (h, mimeType) => fileTypeIconRenderer(mimeType)(h, { size: 18 });
341
+ var PreviewFile = Mount.make("FilePickerPreviewFile", { args: { file: Schema3.Redacted(Schema3.File) } }, (image, _, changes) => Effect.gen(function* () {
342
+ let url;
343
+ yield* Effect.addFinalizer(() => Effect.sync(() => {
344
+ if (url)
345
+ URL.revokeObjectURL(url);
346
+ }));
347
+ yield* changes.pipe(Stream.runForEach(({ file }) => Effect.sync(() => {
348
+ if (url)
349
+ URL.revokeObjectURL(url);
350
+ url = URL.createObjectURL(Redacted2.value(file));
351
+ image.src = url;
352
+ })));
353
+ return Component2.noop;
354
+ }));
355
+ var FileThumbnail = (h, file) => fileType(file.type) === "image" ? h.img.class("size-9 shrink-0 rounded-md object-cover").attr("alt", "").onMount(PreviewFile({ file: Redacted2.make(file) })) : FileTypeIcon(h, file.type);
356
+ var props = Schema3.Struct({
357
+ ...filePickerOptions.props.fields,
358
+ title: Schema3.String,
359
+ showAcceptHint: Schema3.optionalKey(Schema3.Boolean)
360
+ }).annotate({ identifier: "FilePickerHtmlProps" });
361
+ var FileInput = Html.component({
362
+ ...filePickerOptions,
363
+ props,
364
+ slots: ["actions"],
365
+ reads: { localeConfig: krakstackLocaleRead }
366
+ }).make({
367
+ ...filePickerBehaviours,
368
+ view: (h, dragDepth) => {
369
+ const fileInputClasses = resolveFileInputClasses(h.props.classes);
370
+ const p = h.props;
371
+ const locale = p.locale ?? h.reads.localeConfig?.locale ?? "en";
372
+ const copy = filePickerMessages(locale, p.messages);
373
+ const files = p.files ?? [];
374
+ const icon = (file) => file && p.showImageThumbnails ? FileThumbnail(h, file) : FileTypeIcon(h, file?.type ?? "");
375
+ const selected = !p.multiple && Boolean(p.file ?? p.image?.src);
376
+ const inputLabel = p.multiple ? copy.chooseFiles : copy.chooseFile;
377
+ const chooser = h.label.class(cn(buttonVariants({ variant: "outline" }), "focus-within:ring-ring relative cursor-pointer overflow-hidden focus-within:ring-2")).children(ChooseIcon(h), inputLabel, h.input.id(p.id).class("absolute inset-0 z-10 size-full cursor-pointer opacity-0").attrs({
378
+ type: "file",
379
+ name: p.name,
380
+ accept: p.accept,
381
+ multiple: p.multiple ? "" : undefined,
382
+ required: p.required && !p.file && files.length === 0 && !p.image?.src ? "" : undefined,
383
+ "aria-invalid": p.invalid ? "true" : "false",
384
+ "aria-label": inputLabel
385
+ }).value("").on("blur", FilePickerMessage.Blurred()).on("change", ({ files }) => FilePickerMessage.Selected({ files: Redacted2.make(files) })));
386
+ const remove = (label, onPress) => Button(h, {
387
+ variant: "ghost",
388
+ size: "icon-sm",
389
+ props: { type: "button" },
390
+ onPress
391
+ }).attr("aria-label", label).children(RemoveIcon(h));
392
+ const attachment = (name, file) => h.div.class("min-w-0 flex-1").children(h.p.class("break-words text-sm font-medium").children(name), file && h.p.class("text-muted-foreground break-words text-xs").children(fileDescription(file, locale)));
393
+ const dropzone = h.div.class(cn(fileDropZoneClass, "min-h-32 min-w-0")).attrs({
394
+ "data-dragging": dragDepth > 0 ? "true" : "false",
395
+ "data-drag-over": dragDepth > 0 ? "" : undefined
396
+ }).dropTarget({ accepts: ["Files"], dropEffect: "copy" }).on("dragenter", FilePickerMessage.DragEntered()).on("dragleave", FilePickerMessage.DragLeft()).on("drop", ({ files }) => FilePickerMessage.Dropped({ files: Redacted2.make(files) })).children(FileDropIcon(h).children(UploadIcon(h)), h.div.class("min-w-0").children(FileDropTitle(h).children(p.multiple ? copy.dropFiles : copy.dropFile), p.showAcceptHint !== false && p.accept && FileDropHint(h, { class: "break-words" }).children(copy.accepts(p.accept ?? ""))), h.div.class("flex flex-wrap items-center justify-center gap-2").children(chooser, h.slots.actions));
397
+ const preview = p.image && (p.file || p.image.src) ? h.img.class("h-auto max-w-full rounded border object-contain").attrs({
398
+ alt: p.image.alt,
399
+ width: String(p.image.width),
400
+ height: String(p.image.height),
401
+ src: p.file ? undefined : p.image.src
402
+ }) : null;
403
+ return h.div.class(fileInputClasses.root).children(selected ? h.div.class("flex flex-wrap items-center gap-3 rounded-lg border p-3").children(preview && p.file ? preview.onMount(PreviewFile({ file: Redacted2.make(p.file) })) : preview ?? icon(p.file), attachment(p.file?.name ?? p.title, p.file), p.canClear !== false && remove(`${copy.deleteFile} ${p.title}`, FilePickerMessage.Cleared())) : dropzone, p.multiple && files.length > 0 && h.ul.class("grid gap-2").children(files.map((file, index) => h.li.key(`${filePickerKey(file)}:${index}`).class("flex items-center gap-3 rounded-lg border p-3").children(icon(file), attachment(file.name, file), remove(`${copy.deleteFile} ${file.name}`, FilePickerMessage.Removed({ index }))))));
404
+ }
405
+ });
406
+
407
+ // ../assets/src/components/asset-input/html.ts
408
+ import { krakstackLocaleRead as krakstackLocaleRead4 } from "@krak-stack/registry/krakstack-provider/html";
409
+
410
+ // ../../src/components/upload-attachment/html.ts
411
+ import { Schema as Schema6 } from "effect";
412
+ import { Html as Html2 } from "effect/ui/html";
413
+ import { Button as Button2 } from "@/components/effectcn/button";
414
+ import { krakstackLocaleRead as krakstackLocaleRead2 } from "@krak-stack/registry/krakstack-provider/html";
415
+ import {
416
+ Check,
417
+ File as FileIcon2,
418
+ LoaderCircle,
419
+ RotateCcw,
420
+ TriangleAlert,
421
+ X
422
+ } from "@krak-stack/registry/lucide-effect";
423
+
424
+ // ../../src/components/upload-attachment/classes.ts
425
+ var uploadAttachmentStatusRowClass = "mt-1 flex items-center gap-2";
426
+ var uploadAttachmentClasses = {
427
+ pendingIcon: "motion-safe:animate-spin",
428
+ status: "text-muted-foreground text-xs",
429
+ progress: "accent-primary h-1.5 min-w-0 flex-1 overflow-hidden rounded-full [&:not(:indeterminate)]:appearance-none [&:not(:indeterminate)]:bg-muted [&::-webkit-progress-bar]:bg-muted [&::-webkit-progress-value]:rounded-full [&::-webkit-progress-value]:bg-primary [&::-moz-progress-bar]:rounded-full [&::-moz-progress-bar]:bg-primary"
430
+ };
431
+ var resolveUploadAttachmentClasses = (overrides) => ({
432
+ ...uploadAttachmentClasses,
433
+ ...overrides
434
+ });
435
+
436
+ // ../../src/components/upload-attachment/index.ts
437
+ import { Schema as Schema5 } from "effect";
438
+ import { Component as Component3, UiSchema as UiSchema2 } from "effect/ui";
439
+
440
+ // ../../src/components/upload-attachment/schema.ts
441
+ import { Schema as Schema4, Struct as Struct2 } from "effect";
442
+ var UploadAttachmentStateSchema = Schema4.Union([
443
+ Schema4.Struct({
444
+ status: Schema4.Literals(["idle", "processing", "done", "cancelled"])
445
+ }),
446
+ Schema4.Struct({
447
+ status: Schema4.Literal("uploading"),
448
+ progress: Schema4.optional(Schema4.Number)
449
+ }),
450
+ Schema4.Struct({ status: Schema4.Literal("error"), message: Schema4.String })
451
+ ]).annotate({ identifier: "UploadAttachmentState" });
452
+ var Messages = Schema4.Struct({
453
+ idle: Schema4.String,
454
+ uploading: Schema4.String,
455
+ processing: Schema4.String,
456
+ done: Schema4.String,
457
+ cancelled: Schema4.String,
458
+ cancel: Schema4.String,
459
+ retry: Schema4.String,
460
+ remove: Schema4.String
461
+ }).annotate({ identifier: "UploadAttachmentMessages" });
462
+ var UploadAttachmentClassesOverridesSchema = Schema4.Record(Schema4.Literals(Struct2.keys(uploadAttachmentClasses)), Schema4.optionalKey(Schema4.String)).annotate({ identifier: "UploadAttachmentClassesOverrides" });
463
+ var UploadAttachmentPropsSchema = Schema4.Struct({
464
+ classes: Schema4.optional(UploadAttachmentClassesOverridesSchema),
465
+ name: Schema4.String,
466
+ description: Schema4.optional(Schema4.String),
467
+ state: UploadAttachmentStateSchema,
468
+ disabled: Schema4.optional(Schema4.Boolean),
469
+ className: Schema4.optional(Schema4.String),
470
+ locale: Schema4.optional(Schema4.String),
471
+ messages: Schema4.optional(Schema4.Record(Schema4.String, Messages.mapFields((fields) => ({
472
+ idle: Schema4.optional(fields.idle),
473
+ uploading: Schema4.optional(fields.uploading),
474
+ processing: Schema4.optional(fields.processing),
475
+ done: Schema4.optional(fields.done),
476
+ cancelled: Schema4.optional(fields.cancelled),
477
+ cancel: Schema4.optional(fields.cancel),
478
+ retry: Schema4.optional(fields.retry),
479
+ remove: Schema4.optional(fields.remove)
480
+ }))))
481
+ }).annotate({ identifier: "UploadAttachmentProps" });
482
+
483
+ // ../../src/components/upload-attachment/index.ts
484
+ var defaultMessages2 = {
485
+ en: {
486
+ idle: "Ready to upload",
487
+ uploading: "Uploading",
488
+ processing: "Processing",
489
+ done: "Upload complete",
490
+ cancelled: "Upload cancelled",
491
+ cancel: "Cancel upload",
492
+ retry: "Retry upload",
493
+ remove: "Remove attachment"
494
+ },
495
+ fr: {
496
+ idle: "Prêt à téléverser",
497
+ uploading: "Téléversement",
498
+ processing: "Traitement",
499
+ done: "Téléversement terminé",
500
+ cancelled: "Téléversement annulé",
501
+ cancel: "Annuler le téléversement",
502
+ retry: "Réessayer le téléversement",
503
+ remove: "Retirer la pièce jointe"
504
+ }
505
+ };
506
+ var getUploadAttachmentPresentation = (state, locale = "en", messages) => {
507
+ const copy = {
508
+ ...locale.startsWith("fr") ? defaultMessages2.fr : defaultMessages2.en,
509
+ ...messages?.[locale.split("-")[0] ?? locale],
510
+ ...messages?.[locale]
511
+ };
512
+ return {
513
+ copy,
514
+ busy: state.status === "uploading" || state.status === "processing",
515
+ retry: state.status === "error" || state.status === "cancelled",
516
+ progress: state.status === "uploading" && state.progress !== undefined && Number.isFinite(state.progress) ? Math.min(100, Math.max(0, state.progress)) : undefined,
517
+ status: state.status === "error" ? state.message : copy[state.status]
518
+ };
519
+ };
520
+ var UploadAttachmentAction = UiSchema2.TaggedEnum({
521
+ Cancel: {},
522
+ Retry: {},
523
+ Remove: {}
524
+ }).annotate({ identifier: "UploadAttachmentAction" });
525
+ var uploadAttachmentOptions = {
526
+ name: "UploadAttachment",
527
+ props: UploadAttachmentPropsSchema,
528
+ model: Schema5.Null,
529
+ message: UploadAttachmentAction,
530
+ events: UploadAttachmentAction,
531
+ restore: false
532
+ };
533
+ var update = ($, action) => {
534
+ const { busy, retry } = getUploadAttachmentPresentation($.props.state);
535
+ const available = action._tag === "Cancel" ? busy : action._tag === "Retry" ? retry : !busy;
536
+ return !$.props.disabled && available ? $.set(null).emit(action) : null;
537
+ };
538
+ var uploadAttachmentBehaviours = {
539
+ init: () => null,
540
+ update: Component3.define(uploadAttachmentOptions).update({
541
+ Cancel: update,
542
+ Retry: update,
543
+ Remove: update
544
+ })
545
+ };
546
+
547
+ // ../../src/components/upload-attachment/html.ts
548
+ var props2 = Schema6.Struct({
549
+ ...uploadAttachmentOptions.props.fields,
550
+ canCancel: Schema6.optional(Schema6.Boolean),
551
+ canRetry: Schema6.optional(Schema6.Boolean),
552
+ canRemove: Schema6.optional(Schema6.Boolean)
553
+ }).annotate({ identifier: "UploadAttachmentHtmlProps" });
554
+ var UploadAttachment = Html2.component({
555
+ ...uploadAttachmentOptions,
556
+ props: props2,
557
+ slots: ["fileIcon"],
558
+ reads: { localeConfig: krakstackLocaleRead2 }
559
+ }).make({
560
+ ...uploadAttachmentBehaviours,
561
+ view: (h) => {
562
+ const uploadAttachmentClasses = resolveUploadAttachmentClasses(h.props.classes);
563
+ const { name, description, state, disabled, className, locale, messages } = h.props;
564
+ const { busy, copy, progress, retry, status } = getUploadAttachmentPresentation(state, locale ?? h.reads.localeConfig?.locale, messages);
565
+ const id = h.id("name");
566
+ const action = (label, onPress) => Button2(h, {
567
+ variant: "ghost",
568
+ size: "icon-sm",
569
+ props: { type: "button", disabled },
570
+ onPress
571
+ }).attr("aria-label", `${label}: ${name}`).children(onPress._tag === "Retry" ? RotateCcw(h) : X(h));
572
+ return h.div.class(cn("flex min-w-0 items-start gap-3 rounded-lg border p-3", className)).attrs({
573
+ "data-component": "upload-attachment",
574
+ "data-state": state.status,
575
+ "aria-labelledby": id
576
+ }).children(h.span.class("bg-muted grid size-9 shrink-0 place-items-center rounded-md").children(h.span.class("peer empty:hidden").children(h.slots.fileIcon), h.span.class("peer-[:not(:empty)]:hidden").children(state.status === "done" ? Check(h, { size: 18 }) : state.status === "error" ? TriangleAlert(h, { size: 18 }) : busy ? LoaderCircle(h, {
577
+ size: 18,
578
+ className: uploadAttachmentClasses.pendingIcon
579
+ }) : FileIcon2(h, { size: 18 }))), h.div.class("min-w-0 flex-1").children(h.p.id(id).class("truncate text-sm font-medium").children(name), description && h.p.class("text-muted-foreground text-xs").children(description), h.div.class(uploadAttachmentStatusRowClass).children(h.p.attrs({
580
+ "data-slot": "upload-attachment-status",
581
+ role: state.status === "error" ? "alert" : "status"
582
+ }).class(uploadAttachmentClasses.status).children(status), state.status === "uploading" && h.progress.attrs({
583
+ "data-slot": "upload-attachment-progress",
584
+ "aria-label": `${copy.uploading}: ${name}`,
585
+ max: "100",
586
+ value: progress?.toString()
587
+ }).class(uploadAttachmentClasses.progress))), h.div.class("flex items-center gap-1").children(busy && h.props.canCancel && action(copy.cancel, UploadAttachmentAction.Cancel()), retry && h.props.canRetry && action(copy.retry, UploadAttachmentAction.Retry()), !busy && h.props.canRemove && action(copy.remove, UploadAttachmentAction.Remove())));
588
+ }
589
+ });
590
+
591
+ // ../../src/components/virtualized-combobox/html.ts
592
+ import { Html as Html3 } from "effect/ui/html";
593
+ import { Combobox, VirtualList } from "effect/ui/kit";
594
+ import { buttonVariants as buttonVariants2 } from "@/components/effectcn/button";
595
+ import {
596
+ ComboboxButton,
597
+ ComboboxClear,
598
+ ComboboxEmpty,
599
+ ComboboxItem,
600
+ ComboboxItemIndicator,
601
+ ComboboxPopup,
602
+ ComboboxPositioner,
603
+ ComboboxSearchInput
604
+ } from "@/components/effectcn/combobox";
605
+ import { krakstackLocaleRead as krakstackLocaleRead3 } from "@krak-stack/registry/krakstack-provider/html";
606
+
607
+ // ../../src/components/virtualized-combobox/classes.ts
608
+ var virtualizedComboboxClasses = {
609
+ itemLabel: "min-w-0 truncate",
610
+ groupLabel: "text-muted-foreground px-2 pt-3 pb-1 text-start text-xs",
611
+ itemContent: "flex min-w-0 flex-1 items-center gap-2 text-start",
612
+ itemMedia: "bg-muted grid size-8 shrink-0 place-items-center overflow-hidden rounded-md [&_svg]:size-4",
613
+ itemImage: "size-full object-cover",
614
+ itemDescription: "text-muted-foreground block truncate text-xs"
615
+ };
616
+ var virtualizedComboboxGroupHeight = 36;
617
+ var virtualizedComboboxDetailHeight = 52;
618
+ var resolveVirtualizedComboboxClasses = (overrides) => ({
619
+ ...virtualizedComboboxClasses,
620
+ ...overrides
621
+ });
622
+
623
+ // ../../src/components/virtualized-combobox/index.ts
624
+ import { Schema as Schema8 } from "effect";
625
+ import { Component as Component4, UiSchema as UiSchema3 } from "effect/ui";
626
+
627
+ // ../../src/components/virtualized-combobox/schema.ts
628
+ import { Predicate, Schema as Schema7, Struct as Struct3 } from "effect";
629
+ var Icon = Schema7.declare((value) => Predicate.isFunction(value)).annotate({ identifier: "VirtualizedComboboxIcon" });
630
+ var VirtualizedComboboxOptionSchema = Schema7.Struct({
631
+ value: Schema7.String.pipe(Schema7.mutableKey),
632
+ label: Schema7.String.pipe(Schema7.mutableKey),
633
+ description: Schema7.optionalKey(Schema7.String),
634
+ imageSrc: Schema7.optionalKey(Schema7.String),
635
+ icon: Schema7.optionalKey(Icon)
636
+ }).annotate({ identifier: "VirtualizedComboboxOption" });
637
+ var VirtualizedComboboxLabelsSchema = Schema7.Struct({
638
+ clear: Schema7.optionalKey(Schema7.String),
639
+ search: Schema7.optionalKey(Schema7.String),
640
+ selectMore: Schema7.optionalKey(Schema7.String)
641
+ }).annotate({ identifier: "VirtualizedComboboxLabels" });
642
+ var VirtualizedComboboxClassesOverridesSchema = Schema7.Record(Schema7.Literals(Struct3.keys(virtualizedComboboxClasses)), Schema7.optionalKey(Schema7.String)).annotate({ identifier: "VirtualizedComboboxClassesOverrides" });
643
+ var VirtualizedComboboxSharedPropsSchema = Schema7.Struct({
644
+ classes: Schema7.optional(VirtualizedComboboxClassesOverridesSchema),
645
+ ariaLabel: Schema7.String,
646
+ ariaInvalid: Schema7.optionalKey(Schema7.Boolean),
647
+ contentClassName: Schema7.optionalKey(Schema7.String),
648
+ disabled: Schema7.optionalKey(Schema7.Boolean),
649
+ items: Schema7.Array(VirtualizedComboboxOptionSchema),
650
+ locale: Schema7.optionalKey(Schema7.String),
651
+ open: Schema7.optionalKey(Schema7.Boolean),
652
+ searchValue: Schema7.optionalKey(Schema7.String),
653
+ triggerId: Schema7.optionalKey(Schema7.String)
654
+ }).annotate({ identifier: "VirtualizedComboboxSharedProps" });
655
+ var htmlFields = {
656
+ ...VirtualizedComboboxSharedPropsSchema.fields,
657
+ emptyLabel: Schema7.String,
658
+ placeholder: Schema7.String,
659
+ triggerLabel: Schema7.optionalKey(Schema7.String),
660
+ triggerIcon: Schema7.optionalKey(Icon),
661
+ itemHeight: Schema7.optionalKey(Schema7.Int.check(Schema7.isGreaterThan(0))),
662
+ filter: Schema7.optionalKey(Schema7.Literals(["contains", "none"])),
663
+ messages: Schema7.optionalKey(Schema7.Record(Schema7.String, Schema7.Struct({
664
+ ...VirtualizedComboboxLabelsSchema.fields,
665
+ selected: Schema7.optionalKey(Schema7.String)
666
+ })))
667
+ };
668
+ var VirtualizedComboboxPropsSchema = Schema7.Union([
669
+ Schema7.Struct({
670
+ ...htmlFields,
671
+ multiple: Schema7.optionalKey(Schema7.Literal(false)),
672
+ value: Schema7.NullOr(VirtualizedComboboxOptionSchema)
673
+ }),
674
+ Schema7.Struct({
675
+ ...htmlFields,
676
+ multiple: Schema7.Literal(true),
677
+ value: Schema7.Array(VirtualizedComboboxOptionSchema)
678
+ })
679
+ ]).annotate({ identifier: "VirtualizedComboboxProps" });
680
+
681
+ // ../../src/components/virtualized-combobox/index.ts
682
+ var isText = Schema8.is(Schema8.String);
683
+ var defaultMessages3 = {
684
+ en: {
685
+ clear: "Clear selection",
686
+ search: "Search...",
687
+ selected: (count) => `${count} selected`,
688
+ selectMore: "Select more"
689
+ },
690
+ fr: {
691
+ clear: "Effacer la sélection",
692
+ search: "Rechercher...",
693
+ selected: (count) => `${count} sélectionnés`,
694
+ selectMore: "Sélectionner davantage"
695
+ }
696
+ };
697
+ var virtualizedComboboxMessages = (locale, translations) => {
698
+ const language = locale.split("-")[0];
699
+ const labels = {
700
+ ...defaultMessages3[language === "fr" ? "fr" : "en"],
701
+ ...translations?.[language ?? locale],
702
+ ...translations?.[locale]
703
+ };
704
+ const selected = labels.selected;
705
+ return {
706
+ ...labels,
707
+ selected: isText(selected) ? (count) => selected.replaceAll("{count}", String(count)) : selected
708
+ };
709
+ };
710
+ var selectedLabel = (value, placeholder) => {
711
+ if (!value)
712
+ return placeholder;
713
+ if ("label" in value)
714
+ return value.label;
715
+ return value.length ? value.map(({ label }) => label).join(", ") : placeholder;
716
+ };
717
+ var selectionEntries = (items, selected, groupSelections, labels) => {
718
+ const entries = items.map((item, index) => ({
719
+ kind: "item",
720
+ item,
721
+ index
722
+ }));
723
+ if (!groupSelections || entries.length === 0)
724
+ return entries;
725
+ const chosen = entries.filter(({ item }) => selected.has(item.value));
726
+ return [
727
+ ...chosen.length ? [
728
+ {
729
+ kind: "group",
730
+ key: "selected",
731
+ label: labels.selected(selected.size)
732
+ },
733
+ ...chosen
734
+ ] : [],
735
+ { kind: "group", key: "available", label: labels.selectMore },
736
+ ...entries.filter(({ item }) => !selected.has(item.value))
737
+ ];
738
+ };
739
+ var events = {
740
+ OpenChanged: { open: Schema8.Boolean },
741
+ SearchChanged: { searchValue: Schema8.String },
742
+ ValueChanged: {
743
+ value: Schema8.NullOr(Schema8.Union([Schema8.String, Schema8.Array(Schema8.String)]))
744
+ }
745
+ };
746
+ var selectionId = (value) => isText(value) ? value : null;
747
+ var selectionIds = (value) => isText(value) ? [value] : value ?? [];
748
+ var VirtualizedComboboxEvents = UiSchema3.TaggedEnum(events).annotate({
749
+ identifier: "VirtualizedComboboxEvents"
750
+ });
751
+ var VirtualizedComboboxMessage = UiSchema3.TaggedEnum({
752
+ ...events,
753
+ Highlighted: { value: Schema8.String },
754
+ ImageFailed: { src: Schema8.String }
755
+ }).annotate({ identifier: "VirtualizedComboboxMessage" });
756
+ var virtualizedComboboxOptions = {
757
+ name: "VirtualizedCombobox",
758
+ props: VirtualizedComboboxPropsSchema,
759
+ model: Schema8.Struct({
760
+ open: Schema8.Boolean,
761
+ searchValue: Schema8.String,
762
+ failedImages: Schema8.Array(Schema8.String),
763
+ highlight: Schema8.NullOr(Schema8.Struct({ value: Schema8.String, id: Schema8.Int }))
764
+ }).annotate({ identifier: "VirtualizedComboboxModel" }),
765
+ message: VirtualizedComboboxMessage,
766
+ events: VirtualizedComboboxEvents,
767
+ restore: false
768
+ };
769
+ var update2 = Component4.define(virtualizedComboboxOptions).update({
770
+ OpenChanged: ($, { open }) => $.set({
771
+ ...$.model,
772
+ open: $.props.open === undefined ? open : $.model.open,
773
+ highlight: open ? $.model.highlight : null
774
+ }).emit(VirtualizedComboboxEvents.OpenChanged({ open })),
775
+ SearchChanged: ($, { searchValue }) => $.evolve({
776
+ searchValue: $.props.searchValue === undefined ? searchValue : $.model.searchValue,
777
+ highlight: null
778
+ }).emit(VirtualizedComboboxEvents.SearchChanged({ searchValue })),
779
+ ValueChanged: ($, { value }) => $.set($.model).emit(VirtualizedComboboxEvents.ValueChanged({ value })),
780
+ Highlighted: ($, { value }) => $.evolve({
781
+ highlight: { value, id: ($.model.highlight?.id ?? 0) + 1 }
782
+ }),
783
+ ImageFailed: ($, { src }) => $.model.failedImages.includes(src) ? $.model : $.evolve({ failedImages: [...$.model.failedImages, src] })
784
+ });
785
+ var virtualizedComboboxBehaviours = {
786
+ init: () => ({
787
+ open: false,
788
+ searchValue: "",
789
+ highlight: null,
790
+ failedImages: []
791
+ }),
792
+ update: update2
793
+ };
794
+
795
+ // ../../src/components/virtualized-combobox/html.ts
796
+ var visibleRows = 8;
797
+ var itemKey = (value) => `item:${value}`;
798
+ var VirtualizedCombobox = Html3.component({
799
+ ...virtualizedComboboxOptions,
800
+ reads: { localeConfig: krakstackLocaleRead3 }
801
+ }).make({
802
+ ...virtualizedComboboxBehaviours,
803
+ view: (h, model) => {
804
+ const virtualizedComboboxClasses = resolveVirtualizedComboboxClasses(h.props.classes);
805
+ const props = h.props;
806
+ const optionsByValue = new Map(props.items.map((item) => [item.value, item]));
807
+ const rowHeight = props.itemHeight ?? (props.items.some(({ description, imageSrc, icon }) => description || imageSrc || icon) ? virtualizedComboboxDetailHeight : 36);
808
+ const locale = props.locale ?? h.reads.localeConfig?.locale ?? "en";
809
+ const labels = virtualizedComboboxMessages(locale, props.messages);
810
+ const value = props.multiple ? props.value.map((item) => item.value) : props.value?.value ?? null;
811
+ const selected = new Set(selectionIds(value));
812
+ return Combobox(h, {
813
+ props: {
814
+ open: props.open ?? model.open,
815
+ inputValue: props.searchValue ?? model.searchValue,
816
+ items: props.items.map(({ value, label }) => ({ value, label })),
817
+ value,
818
+ locale,
819
+ multiple: props.multiple,
820
+ filter: props.filter,
821
+ disabled: props.disabled,
822
+ id: props.triggerId,
823
+ sideOffset: 6,
824
+ inputInPopup: true,
825
+ virtualized: true
826
+ },
827
+ onEmit: {
828
+ RequestedOpen: () => VirtualizedComboboxMessage.OpenChanged({ open: true }),
829
+ RequestedClose: () => VirtualizedComboboxMessage.OpenChanged({ open: false }),
830
+ RequestedInputValue: ({ inputValue }) => VirtualizedComboboxMessage.SearchChanged({ searchValue: inputValue }),
831
+ Picked: ({ value }) => VirtualizedComboboxMessage.ValueChanged({
832
+ value: props.multiple ? selectionIds(value) : selectionId(value)
833
+ }),
834
+ Highlighted: ({ reason, value }) => reason === "keyboard" && value !== null ? VirtualizedComboboxMessage.Highlighted({ value }) : undefined,
835
+ Settled: () => {
836
+ return;
837
+ }
838
+ },
839
+ view: (combo) => {
840
+ const entries = selectionEntries(combo.items, selected, props.multiple === true, labels);
841
+ const keys = entries.map((entry) => entry.kind === "group" ? `group:${entry.key}` : itemKey(entry.item.value));
842
+ const highlight = model.highlight && keys.includes(itemKey(model.highlight.value)) ? model.highlight : undefined;
843
+ return h.div.class("relative min-w-0").children((props.triggerIcon ? combo.trigger(h.button.class(buttonVariants2({ variant: "outline" }))).children(props.triggerIcon(h, { size: 16 }), props.triggerLabel ?? selectedLabel(props.value, props.placeholder)) : ComboboxButton(h, combo, {
844
+ class: "w-full min-w-0 aria-invalid:border-destructive",
845
+ value: props.triggerLabel ?? selectedLabel(props.value, props.placeholder),
846
+ valueClass: selected.size > 0 ? "pr-7" : undefined
847
+ })).attrs({
848
+ "aria-label": props.ariaLabel,
849
+ "aria-invalid": props.ariaInvalid ? "true" : undefined
850
+ }), !props.triggerIcon && selected.size > 0 && ComboboxClear(h, combo, {
851
+ class: "absolute right-7 top-1/2 -translate-y-1/2"
852
+ })?.attrs({ "aria-label": labels.clear, tabindex: "0" }), ComboboxPositioner(h, combo, {
853
+ class: "overflow-visible border-0 bg-transparent p-0 text-inherit"
854
+ }).children(ComboboxPopup(h, combo, { class: props.contentClassName }).attr("aria-label", props.ariaLabel).children(ComboboxSearchInput(h, combo, {
855
+ placeholder: labels.search
856
+ }), ComboboxEmpty(h, combo).children(props.emptyLabel), VirtualList(h, {
857
+ props: {
858
+ count: entries.length,
859
+ itemSize: rowHeight,
860
+ sizes: entries.some(({ kind }) => kind === "group") ? entries.map(({ kind }) => kind === "group" ? virtualizedComboboxGroupHeight : rowHeight) : undefined,
861
+ measure: false,
862
+ keys,
863
+ initialCount: visibleRows,
864
+ overscan: 8,
865
+ scrollTo: highlight && {
866
+ target: { _tag: "Key", key: itemKey(highlight.value) },
867
+ id: `${highlight.id}:${highlight.value}`,
868
+ align: "nearest"
869
+ }
870
+ },
871
+ view: (list) => list.viewport(h.div.class("min-h-0 overflow-auto overscroll-contain py-1")).attr("style", `max-height:${rowHeight * visibleRows}px`).attr("tabindex", "-1").children(list.list(combo.list(h.div)).children(...list.items.map((index) => {
872
+ const entry = entries[index];
873
+ const element = h.div.key(keys[index]);
874
+ if (entry.kind === "group") {
875
+ return list.item({
876
+ element: element.attr("role", "presentation"),
877
+ index
878
+ }).class("px-1").children(h.div.class(virtualizedComboboxClasses.groupLabel).children(entry.label));
879
+ }
880
+ const { value, label } = entry.item;
881
+ const details = optionsByValue.get(value);
882
+ const image = details?.imageSrc && !model.failedImages.includes(details.imageSrc) ? details.imageSrc : undefined;
883
+ return list.item({
884
+ element: element.attr("role", "presentation"),
885
+ index
886
+ }).children(ComboboxItem(h, combo, {
887
+ class: "mx-1 h-full",
888
+ value
889
+ }).attrs({
890
+ "aria-posinset": String(entry.index + 1),
891
+ "aria-setsize": String(combo.items.length)
892
+ }).children(h.span.class(virtualizedComboboxClasses.itemContent).children((image || details?.icon) && h.span.attr("aria-hidden", "true").class(virtualizedComboboxClasses.itemMedia).children(image ? h.img.attrs({
893
+ src: image,
894
+ alt: "",
895
+ loading: "lazy"
896
+ }).class(virtualizedComboboxClasses.itemImage).on("error", VirtualizedComboboxMessage.ImageFailed({
897
+ src: image
898
+ })) : details?.icon?.(h, {
899
+ size: 16
900
+ })), h.span.class("min-w-0 flex-1").children(h.span.class(`block ${virtualizedComboboxClasses.itemLabel}`).children(label), details?.description && h.span.class(virtualizedComboboxClasses.itemDescription).children(details.description))), ComboboxItemIndicator(h, combo, { value })));
901
+ })))
902
+ }))));
903
+ }
904
+ });
905
+ }
906
+ });
907
+
908
+ // ../assets/src/components/asset-input/html.ts
909
+ import { FolderOpen, X as X2 } from "@krak-stack/registry/lucide-effect";
910
+
911
+ // ../assets/src/services/assets/url.ts
912
+ import { Schema as Schema10 } from "effect";
913
+
914
+ // ../assets/src/services/assets/schema.ts
915
+ import { Schema as Schema9 } from "effect";
916
+ var AssetHttpUrl = Schema9.String.check(Schema9.makeFilter((value) => {
917
+ if (!/^https?:\/\/[^/]/i.test(value) || /[\s\\]/u.test(value))
918
+ return false;
919
+ try {
920
+ const url = new URL(value);
921
+ return !url.username && !url.password;
922
+ } catch {
923
+ return false;
924
+ }
925
+ })).annotate({ identifier: "AssetHttpUrl" });
926
+ var AssetRelativeUrl = Schema9.String.check(Schema9.isPattern(/^\/(?!\/)[^\s\\]*$/u)).annotate({ identifier: "AssetRelativeUrl" });
927
+
928
+ // ../assets/src/services/assets/url.ts
929
+ var isAssetHttpUrl = Schema10.is(AssetHttpUrl);
930
+ var isAssetRelativeUrl = Schema10.is(AssetRelativeUrl);
931
+ var assetUrl = ({ url }) => isAssetHttpUrl(url) || isAssetRelativeUrl(url) ? url : undefined;
932
+ var assetImage = (asset) => {
933
+ const url = asset.mimeType.trim().toLowerCase().startsWith("image/") ? assetUrl(asset) : undefined;
934
+ if (!url)
935
+ return {};
936
+ const version = asset.updatedAt?.getTime();
937
+ const imageSrc = version !== undefined && Number.isFinite(version) && /^\/api\/assets\/[^/?#]+\/file$/.test(url) ? `${url}?v=${version}` : url;
938
+ return { imageSrc };
939
+ };
940
+
941
+ // ../assets/src/components/asset-input/index.ts
942
+ import { Effect as Effect3, Queue, Redacted as Redacted3, Schema as Schema13, Stream as Stream2 } from "effect";
943
+ import { Command, Component as Component6, UiSchema as UiSchema5 } from "effect/ui";
944
+
945
+ // ../assets/src/services/assets/library.ts
946
+ import {
947
+ Context,
948
+ Effect as Effect2,
949
+ Schema as Schema11
950
+ } from "effect";
951
+ import { AsyncResult } from "effect/reactivity";
952
+ import { Component as Component5, Query, UiSchema as UiSchema4, View } from "effect/ui";
953
+ var AssetLibraryAccessSchema = Schema11.Struct({
954
+ scopeKey: Schema11.NonEmptyString,
955
+ permissions: Schema11.Array(Schema11.Literals(["list", "read", "create", "update", "delete"]))
956
+ }).annotate({ identifier: "AssetLibraryAccess" });
957
+ var AssetListQuerySchema = Schema11.Struct({
958
+ search: Schema11.optionalKey(Schema11.String.check(Schema11.isMaxLength(200))),
959
+ kind: Schema11.optionalKey(Schema11.Literals(["image", "video", "caption", "document"]))
960
+ }).annotate({ identifier: "AssetListQuery" });
961
+ var AssetListItemSchema = Schema11.Struct({
962
+ id: Schema11.String.check(Schema11.isUUID()),
963
+ name: Schema11.NonEmptyString,
964
+ mimeType: Schema11.NonEmptyString,
965
+ byteSize: Schema11.Int,
966
+ createdAt: Schema11.Date,
967
+ updatedAt: Schema11.Date,
968
+ url: Schema11.optionalKey(Schema11.String)
969
+ }).annotate({ identifier: "AssetListItem" });
970
+ var AssetStatsSchema = Schema11.Struct({
971
+ assetCount: Schema11.Int,
972
+ storageUsedBytes: Schema11.Int
973
+ }).annotate({ identifier: "AssetStats" });
974
+ var AssetListSchema = Schema11.Struct({
975
+ items: Schema11.Array(AssetListItemSchema),
976
+ stats: AssetStatsSchema
977
+ }).annotate({ identifier: "AssetList" });
978
+ var AssetListArgsSchema = Schema11.Struct({
979
+ ...AssetListQuerySchema.fields,
980
+ scopeKey: Schema11.NonEmptyString,
981
+ showFiles: Schema11.Boolean
982
+ }).annotate({ identifier: "AssetListArgs" });
983
+ var AssetListError = Schema11.Literals([
984
+ "unauthorized",
985
+ "forbidden",
986
+ "unavailable"
987
+ ]).annotate({ identifier: "AssetListError" });
988
+
989
+ class AssetList extends Query.Service()("@krak-stack/assets/AssetList", {
990
+ args: AssetListArgsSchema,
991
+ success: AssetListSchema,
992
+ error: AssetListError,
993
+ staleTime: "30 seconds"
994
+ }) {
995
+ }
996
+ var disabledAssetListLayer = AssetList.toLayer(() => Effect2.fail("unavailable"));
997
+ var assetListArgs = (scopeKey, permissions, query = {}) => permissions.includes("list") ? { ...query, scopeKey, showFiles: permissions.includes("read") } : undefined;
998
+ var assetLibraryQuery = (getAccess) => ({
999
+ query: AssetList,
1000
+ dropPrevious: true,
1001
+ args: ({ props }) => {
1002
+ const access = getAccess(props);
1003
+ return access && assetListArgs(access.scopeKey, access.permissions);
1004
+ }
1005
+ });
1006
+ var AssetLibraryPropsSchema = Schema11.Struct({
1007
+ access: AssetLibraryAccessSchema
1008
+ }).annotate({ identifier: "AssetLibraryModelProps" });
1009
+ var AssetLibrarySnapshot = Schema11.Struct({
1010
+ data: Schema11.NullOr(AssetListSchema),
1011
+ status: Schema11.Literals(["idle", "loading", "ready", "failed"])
1012
+ }).annotate({ identifier: "AssetLibrarySnapshot" });
1013
+ var AssetLibraryMessage = UiSchema4.TaggedEnum({
1014
+ LibraryChanged: { library: AssetLibrarySnapshot }
1015
+ }).annotate({ identifier: "AssetLibraryMessage" });
1016
+ var emptyAssetLibrary = { data: null, status: "idle" };
1017
+ var assetLibrarySnapshot = (result) => AsyncResult.isSuccess(result) ? { data: result.value, status: "ready" } : {
1018
+ data: null,
1019
+ status: AsyncResult.isFailure(result) ? "failed" : "loading"
1020
+ };
1021
+ var libraryQuery = (result) => AssetLibraryMessage.LibraryChanged({ library: assetLibrarySnapshot(result) });
1022
+ var assetLibraryOptions = {
1023
+ name: "AssetLibraryView",
1024
+ props: AssetLibraryPropsSchema,
1025
+ model: Schema11.Null,
1026
+ message: Schema11.Never,
1027
+ restore: false,
1028
+ queries: {
1029
+ library: assetLibraryQuery((props) => props.access)
1030
+ }
1031
+ };
1032
+ var options = {
1033
+ ...assetLibraryOptions,
1034
+ name: "AssetLibraryModel",
1035
+ model: AssetLibrarySnapshot,
1036
+ message: AssetLibraryMessage,
1037
+ queries: {
1038
+ library: {
1039
+ ...assetLibraryOptions.queries.library,
1040
+ onChange: libraryQuery
1041
+ }
1042
+ }
1043
+ };
1044
+ var definition = Component5.define(options);
1045
+ var AssetLibraryModel = definition.make({
1046
+ init: () => emptyAssetLibrary,
1047
+ update: definition.update({ LibraryChanged: (_, { library }) => library }),
1048
+ view: () => View.text("")
1049
+ });
1050
+ var AssetUploadTransportMessages = {
1051
+ en: {
1052
+ rejected: "The file did not pass the security scan.",
1053
+ failed: "The file could not be published."
1054
+ },
1055
+ fr: {
1056
+ rejected: "Le fichier n’a pas passé l’analyse de sécurité.",
1057
+ failed: "Impossible de publier le fichier."
1058
+ }
1059
+ };
1060
+
1061
+ class AssetLibraryActions extends Context.Service()("@krak-stack/assets/AssetLibraryActions") {
1062
+ }
1063
+
1064
+ // ../assets/src/components/asset-input/schema.ts
1065
+ import { Schema as Schema12 } from "effect";
1066
+ var AssetInputItemSchema = Schema12.Struct({
1067
+ id: Schema12.String,
1068
+ name: Schema12.String,
1069
+ mimeType: Schema12.String,
1070
+ url: Schema12.optionalKey(Schema12.String),
1071
+ updatedAt: Schema12.optionalKey(Schema12.Date)
1072
+ }).annotate({ identifier: "AssetInputItem" });
1073
+ var text = Schema12.optionalKey(Schema12.String);
1074
+ var flag = Schema12.optionalKey(Schema12.Boolean);
1075
+ var AssetKindSchema = Schema12.Literals([
1076
+ "document",
1077
+ "image",
1078
+ "video",
1079
+ "caption"
1080
+ ]);
1081
+ var AssetUploadMessagesSchema = Schema12.Record(Schema12.String, Schema12.Struct({
1082
+ upload: text,
1083
+ close: text,
1084
+ cancel: text,
1085
+ dialogTitle: text,
1086
+ dialogDescription: text,
1087
+ libraryDialogTitle: text,
1088
+ libraryDialogDescription: text,
1089
+ uploadError: text,
1090
+ kindError: text,
1091
+ publishError: text
1092
+ })).annotate({ identifier: "AssetUploadMessages" });
1093
+ var AssetUploadPropsSchema = Schema12.Struct({
1094
+ accept: text,
1095
+ processingLabel: text,
1096
+ messages: Schema12.optionalKey(AssetUploadMessagesSchema)
1097
+ }).annotate({ identifier: "AssetUploadProps" });
1098
+ var AssetInputPropsSchema = Schema12.Struct({
1099
+ label: Schema12.String,
1100
+ access: Schema12.optionalKey(AssetLibraryAccessSchema),
1101
+ replaceId: text,
1102
+ uploadTrigger: Schema12.optionalKey(Schema12.Literal("button")),
1103
+ assets: Schema12.optionalKey(Schema12.Array(AssetInputItemSchema)),
1104
+ kind: Schema12.optionalKey(AssetKindSchema),
1105
+ value: Schema12.optionalKey(Schema12.Union([Schema12.String, Schema12.Array(Schema12.String)])),
1106
+ multiple: flag,
1107
+ disabled: flag,
1108
+ locale: text,
1109
+ messages: Schema12.optionalKey(Schema12.Record(Schema12.String, Schema12.Struct({
1110
+ placeholder: text,
1111
+ multiplePlaceholder: text,
1112
+ empty: text,
1113
+ selected: text,
1114
+ remove: text
1115
+ }))),
1116
+ uploader: Schema12.optionalKey(AssetUploadPropsSchema)
1117
+ }).annotate({ identifier: "AssetInputProps" });
1118
+ var AssetInputPickerPropsSchema = AssetInputPropsSchema.mapFields(({ assets, access, value }) => ({ assets, access, value })).annotate({ identifier: "AssetInputPickerProps" });
1119
+ var AssetUploadJobSchema = Schema12.Struct({
1120
+ id: Schema12.Int,
1121
+ file: Schema12.Redacted(Schema12.File),
1122
+ phase: Schema12.Literals([
1123
+ "uploading",
1124
+ "processing",
1125
+ "done",
1126
+ "error",
1127
+ "rejected"
1128
+ ]),
1129
+ progress: Schema12.optionalKey(Schema12.Finite),
1130
+ retryPublication: flag,
1131
+ error: text
1132
+ }).annotate({ identifier: "AssetUploadJob" });
1133
+
1134
+ // ../assets/src/components/asset-input/index.ts
1135
+ var assetInputPickerOptions = {
1136
+ name: "AssetInputPicker",
1137
+ props: AssetInputPickerPropsSchema,
1138
+ model: Schema13.Null,
1139
+ message: Schema13.Never,
1140
+ restore: false,
1141
+ queries: {
1142
+ library: assetLibraryQuery((props) => props.assets === undefined && props.value !== undefined ? props.access : undefined)
1143
+ }
1144
+ };
1145
+ var assetInputPickerBehaviours = {
1146
+ init: () => null,
1147
+ update: () => null
1148
+ };
1149
+ var inputCopy = {
1150
+ en: {
1151
+ placeholder: "Choose asset",
1152
+ multiplePlaceholder: "Choose assets",
1153
+ empty: "No assets found.",
1154
+ selected: "Selected asset",
1155
+ remove: "Remove asset"
1156
+ },
1157
+ fr: {
1158
+ placeholder: "Choisir un fichier existant",
1159
+ multiplePlaceholder: "Choisir des fichiers existants",
1160
+ empty: "Aucun fichier trouvé.",
1161
+ selected: "Fichier sélectionné",
1162
+ remove: "Retirer le fichier"
1163
+ }
1164
+ };
1165
+ var uploadCopy = {
1166
+ en: {
1167
+ upload: "Upload",
1168
+ dialogTitle: "Upload asset",
1169
+ dialogDescription: "This uploads and selects the file. Save the form separately to keep your changes.",
1170
+ libraryDialogTitle: "Upload files",
1171
+ libraryDialogDescription: "Review your files before uploading them to the library.",
1172
+ cancel: "Cancel",
1173
+ close: "Close",
1174
+ uploadError: "Could not upload the file.",
1175
+ kindError: "Choose a file of the required type.",
1176
+ publishError: "Could not confirm publication."
1177
+ },
1178
+ fr: {
1179
+ upload: "Téléverser",
1180
+ dialogTitle: "Téléverser un fichier",
1181
+ dialogDescription: "Le fichier sera téléversé et sélectionné. Enregistrez ensuite le formulaire pour conserver vos modifications.",
1182
+ libraryDialogTitle: "Téléverser des fichiers",
1183
+ libraryDialogDescription: "Vérifiez vos fichiers avant de les téléverser dans la bibliothèque.",
1184
+ cancel: "Annuler",
1185
+ close: "Fermer",
1186
+ uploadError: "Impossible de téléverser le fichier.",
1187
+ kindError: "Choisissez un fichier du type requis.",
1188
+ publishError: "Impossible de confirmer la publication."
1189
+ }
1190
+ };
1191
+ var language = (locale) => locale.split("-")[0] ?? locale;
1192
+ var assetInputMessages = (locale, messages) => ({
1193
+ ...language(locale) === "fr" ? inputCopy.fr : inputCopy.en,
1194
+ ...messages?.[language(locale)],
1195
+ ...messages?.[locale]
1196
+ });
1197
+ var assetUploadMessages = (locale, messages) => ({
1198
+ ...language(locale) === "fr" ? uploadCopy.fr : uploadCopy.en,
1199
+ ...messages?.[language(locale)],
1200
+ ...messages?.[locale]
1201
+ });
1202
+ var matchesAssetKind = (mimeType, kind) => {
1203
+ const type = mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
1204
+ const category = type.startsWith("image/") ? "image" : type.startsWith("video/") ? "video" : type === "text/vtt" ? "caption" : "document";
1205
+ return kind === undefined || category === kind;
1206
+ };
1207
+ var assetUploadAccept = (kind) => kind === "image" ? "image/*" : kind === "video" ? "video/*" : kind === "caption" ? ".vtt,text/vtt" : undefined;
1208
+ var hasInvalidAssetFiles = (files, kind) => files.some((staged) => {
1209
+ const file = Redacted3.value(staged);
1210
+ const mimeType = file.name.toLowerCase().endsWith(".vtt") ? "text/vtt" : file.type;
1211
+ return !matchesAssetKind(mimeType, kind);
1212
+ });
1213
+ var assetSelection = (value) => Schema13.is(Schema13.String)(value) ? value ? [value] : [] : value ?? [];
1214
+ var redactedFile = Schema13.Redacted(Schema13.File);
1215
+ var files = Schema13.Array(redactedFile);
1216
+ var result = {
1217
+ Progress: { id: Schema13.Int, progress: Schema13.Finite },
1218
+ Processing: { id: Schema13.Int },
1219
+ Completed: { id: Schema13.Int, assetId: Schema13.String },
1220
+ Failed: { id: Schema13.Int, retryPublication: Schema13.Boolean },
1221
+ Rejected: { id: Schema13.Int, error: Schema13.String }
1222
+ };
1223
+ var AssetUploadResult = UiSchema5.TaggedEnum(result).annotate({
1224
+ identifier: "AssetUploadResult"
1225
+ });
1226
+
1227
+ class RunAssetUpload extends Command.Service()("asset-input/RunAssetUpload", {
1228
+ args: {
1229
+ id: Schema13.Int,
1230
+ file: redactedFile,
1231
+ retryPublication: Schema13.Boolean
1232
+ },
1233
+ success: AssetUploadResult,
1234
+ stream: true,
1235
+ group: ["id"],
1236
+ mode: "switch"
1237
+ }) {
1238
+ }
1239
+ var assetUploadLayer = (transport) => {
1240
+ const staged = new WeakMap;
1241
+ return RunAssetUpload.toLayer(({ id, file, retryPublication }) => Stream2.callback((queue) => Effect3.tryPromise(async (signal) => {
1242
+ const source = Redacted3.value(file);
1243
+ let transferred = retryPublication;
1244
+ try {
1245
+ let prepared = retryPublication ? staged.get(file) : undefined;
1246
+ if (!prepared) {
1247
+ transferred = false;
1248
+ const context = await transport.upload(source, {
1249
+ signal,
1250
+ onProgress: (progress) => {
1251
+ if (!signal.aborted && !transferred && Number.isFinite(progress))
1252
+ Queue.offerUnsafe(queue, AssetUploadResult.Progress({ id, progress }));
1253
+ }
1254
+ });
1255
+ if (signal.aborted)
1256
+ return;
1257
+ prepared = { context };
1258
+ staged.set(file, prepared);
1259
+ }
1260
+ transferred = true;
1261
+ Queue.offerUnsafe(queue, AssetUploadResult.Processing({ id }));
1262
+ const publication = await transport.publish(prepared.context, signal);
1263
+ if (signal.aborted)
1264
+ return;
1265
+ staged.delete(file);
1266
+ Queue.offerUnsafe(queue, publication.status === "published" ? AssetUploadResult.Completed({
1267
+ id,
1268
+ assetId: publication.assetId
1269
+ }) : AssetUploadResult.Rejected({ id, error: publication.message }));
1270
+ } catch {
1271
+ if (!signal.aborted)
1272
+ Queue.offerUnsafe(queue, AssetUploadResult.Failed({ id, retryPublication: transferred }));
1273
+ } finally {
1274
+ Queue.endUnsafe(queue);
1275
+ }
1276
+ }).pipe(Effect3.ignore)));
1277
+ };
1278
+ var libraryUpload = (run, locale, replaceId) => {
1279
+ const copy = AssetUploadTransportMessages[locale.startsWith("fr") ? "fr" : "en"];
1280
+ return {
1281
+ upload: (file, { signal, onProgress }) => run(AssetLibraryActions.use((transport) => transport.upload(file, onProgress, replaceId)), { signal }),
1282
+ publish: (upload, signal) => run(AssetLibraryActions.use((transport) => transport.publish(upload)).pipe(Effect3.map((result) => result.status === "published" ? result : { status: "rejected", message: copy[result.reason] })), { signal })
1283
+ };
1284
+ };
1285
+ var AssetInputEvents = UiSchema5.TaggedEnum({
1286
+ Changed: { ids: Schema13.Array(Schema13.String) },
1287
+ Published: { assetId: Schema13.String, file: redactedFile }
1288
+ }).annotate({ identifier: "AssetInputEvents" });
1289
+ var AssetInputMessage = UiSchema5.TaggedEnum({
1290
+ Open: {},
1291
+ Stage: { files },
1292
+ SetFiles: { files },
1293
+ Upload: {},
1294
+ Dismiss: {},
1295
+ Closed: {},
1296
+ RemoveJob: { id: Schema13.Int },
1297
+ Retry: { id: Schema13.Int },
1298
+ Changed: { ids: Schema13.Array(Schema13.String) },
1299
+ ...result
1300
+ }).annotate({ identifier: "AssetInputMessage" });
1301
+ var assetInputOptions = {
1302
+ name: "AssetInput",
1303
+ props: AssetInputPropsSchema,
1304
+ model: Schema13.Struct({
1305
+ open: Schema13.Boolean,
1306
+ files,
1307
+ jobs: Schema13.Array(AssetUploadJobSchema),
1308
+ nextId: Schema13.Int
1309
+ }).annotate({ identifier: "AssetInputModel" }),
1310
+ message: AssetInputMessage,
1311
+ events: AssetInputEvents,
1312
+ restore: false
1313
+ };
1314
+ var active = (job) => job.phase === "uploading" || job.phase === "processing";
1315
+ var canCloseAssetUpload = (jobs) => jobs.some(({ phase }) => phase === "done") && !jobs.some(active);
1316
+ var withJob = (model, id, change) => model.open ? {
1317
+ ...model,
1318
+ jobs: model.jobs.map((job) => job.id === id && active(job) ? change(job) : job)
1319
+ } : model;
1320
+ var issue = (job) => RunAssetUpload.make({
1321
+ id: job.id,
1322
+ file: job.file,
1323
+ retryPublication: job.retryPublication ?? false
1324
+ });
1325
+ var definition2 = Component6.define(assetInputOptions);
1326
+ var update3 = definition2.update({
1327
+ Open: ($) => $.props.uploader && !$.props.disabled && !$.model.open ? { ...$.model, open: true, files: [], jobs: [] } : $.model,
1328
+ Stage: ($, { files }) => $.props.uploader && !$.props.disabled && files.length ? {
1329
+ ...$.model,
1330
+ open: true,
1331
+ jobs: $.model.open ? $.model.jobs : [],
1332
+ files: $.props.multiple ? files : files.slice(0, 1)
1333
+ } : $.model,
1334
+ SetFiles: ($, { files }) => $.model.open ? { ...$.model, files: $.props.multiple ? files : files.slice(0, 1) } : $.model,
1335
+ Dismiss: ($) => $.set({ ...$.model, open: false }).run(Command.interrupt(RunAssetUpload)),
1336
+ Closed: ($) => $.model.open ? $.model : { ...$.model, files: [], jobs: [] },
1337
+ Upload: ($) => {
1338
+ if (!$.model.open || !$.props.uploader || $.props.disabled || $.model.jobs.length || !$.model.files.length || hasInvalidAssetFiles($.model.files, $.props.kind))
1339
+ return $.model;
1340
+ const jobs = $.model.files.map((file, offset) => ({
1341
+ id: $.model.nextId + offset,
1342
+ file: Redacted3.make(Redacted3.value(file)),
1343
+ phase: "uploading"
1344
+ }));
1345
+ return $.set({
1346
+ ...$.model,
1347
+ files: [],
1348
+ jobs,
1349
+ nextId: $.model.nextId + jobs.length
1350
+ }).run(...jobs.map(issue));
1351
+ },
1352
+ RemoveJob: ($, { id }) => $.model.open ? $.set({
1353
+ ...$.model,
1354
+ jobs: $.model.jobs.filter((job) => job.id !== id)
1355
+ }).run(Command.interrupt(RunAssetUpload, { id })) : $.model,
1356
+ Retry: ($, { id }) => {
1357
+ const job = $.model.jobs.find((job) => job.id === id && job.phase === "error");
1358
+ if (!$.model.open || !job || !$.props.uploader || $.props.disabled)
1359
+ return $.model;
1360
+ const next = {
1361
+ ...job,
1362
+ phase: job.retryPublication ? "processing" : "uploading",
1363
+ progress: undefined
1364
+ };
1365
+ return $.set({
1366
+ ...$.model,
1367
+ jobs: $.model.jobs.map((job) => job.id === id ? next : job)
1368
+ }).run(issue(next));
1369
+ },
1370
+ Changed: ($, { ids }) => $.props.disabled ? $.model : $.emit(AssetInputEvents.Changed({
1371
+ ids: $.props.multiple ? ids : ids.slice(0, 1)
1372
+ })),
1373
+ Progress: ($, { id, progress }) => withJob($.model, id, (job) => job.phase === "uploading" ? { ...job, progress } : job),
1374
+ Processing: ($, { id }) => withJob($.model, id, (job) => ({ ...job, phase: "processing" })),
1375
+ Failed: ($, { id, retryPublication }) => withJob($.model, id, (job) => ({
1376
+ ...job,
1377
+ phase: "error",
1378
+ retryPublication
1379
+ })),
1380
+ Rejected: ($, { id, error }) => withJob($.model, id, (job) => ({ ...job, phase: "rejected", error })),
1381
+ Completed: ($, { id, assetId }) => {
1382
+ if (!$.model.open)
1383
+ return $.model;
1384
+ const job = $.model.jobs.find((job) => job.id === id && active(job));
1385
+ return job ? $.set(withJob($.model, id, (job) => ({ ...job, phase: "done" }))).emit(AssetInputEvents.Published({ assetId, file: job.file })) : $.model;
1386
+ }
1387
+ });
1388
+ var assetInputBehaviours = {
1389
+ init: () => ({ open: false, files: [], jobs: [], nextId: 0 }),
1390
+ update: update3
1391
+ };
1392
+ var assetUploadState = (job, copy) => {
1393
+ switch (job.phase) {
1394
+ case "uploading":
1395
+ return { status: "uploading", progress: job.progress };
1396
+ case "processing":
1397
+ return { status: "processing" };
1398
+ case "done":
1399
+ return { status: "done" };
1400
+ case "rejected":
1401
+ return {
1402
+ status: "error",
1403
+ message: job.error ?? copy.publishError
1404
+ };
1405
+ case "error":
1406
+ return {
1407
+ status: "error",
1408
+ message: job.retryPublication ? copy.publishError : copy.uploadError
1409
+ };
1410
+ }
1411
+ };
1412
+
1413
+ // ../assets/src/components/asset-input/html.ts
1414
+ var AssetInputView = Html4.component({
1415
+ ...assetInputOptions,
1416
+ slots: ["uploadAction"],
1417
+ reads: { localeConfig: krakstackLocaleRead4 }
1418
+ }).make({
1419
+ ...assetInputBehaviours,
1420
+ view: (h, model) => {
1421
+ const p = h.props;
1422
+ const locale = p.locale ?? h.reads.localeConfig?.locale ?? "en";
1423
+ const labels = assetInputMessages(locale, p.messages);
1424
+ const upload = p.uploader;
1425
+ const copy = assetUploadMessages(locale, upload?.messages);
1426
+ const ids = assetSelection(p.value);
1427
+ const selected = new Map(p.assets?.map((asset) => [asset.id, asset]));
1428
+ const placeholder = p.multiple ? labels.multiplePlaceholder : labels.placeholder;
1429
+ const option = (value) => ({
1430
+ value,
1431
+ label: selected.get(value)?.name ?? labels.selected
1432
+ });
1433
+ const items = p.assets?.filter(({ mimeType }) => matchesAssetKind(mimeType, p.kind)).map((asset) => ({
1434
+ value: asset.id,
1435
+ label: asset.name,
1436
+ description: asset.mimeType,
1437
+ icon: fileTypeIconRenderer(asset.mimeType),
1438
+ ...assetImage(asset)
1439
+ })) ?? [];
1440
+ const picker = p.assets && VirtualizedCombobox(h, {
1441
+ props: {
1442
+ ariaLabel: placeholder,
1443
+ placeholder,
1444
+ triggerLabel: placeholder,
1445
+ triggerIcon: FolderOpen,
1446
+ emptyLabel: labels.empty,
1447
+ locale,
1448
+ disabled: p.disabled,
1449
+ items,
1450
+ contentClassName: "w-80",
1451
+ ...p.multiple ? { multiple: true, value: ids.map(option) } : { value: ids[0] ? option(ids[0]) : null }
1452
+ },
1453
+ onEmit: (event) => event._tag === "ValueChanged" ? AssetInputMessage.Changed({ ids: assetSelection(event.value ?? undefined) }) : undefined
1454
+ });
1455
+ const choose = (staged) => FileInput(h, {
1456
+ props: {
1457
+ id: h.id(staged ? "staged" : "file"),
1458
+ name: "",
1459
+ title: p.label,
1460
+ multiple: p.multiple,
1461
+ locale,
1462
+ accept: upload?.accept ?? assetUploadAccept(p.kind),
1463
+ showAcceptHint: false,
1464
+ ...staged ? { showImageThumbnails: true } : {},
1465
+ file: staged && !p.multiple && model.files[0] ? Redacted4.value(model.files[0]) : undefined,
1466
+ files: staged && p.multiple ? model.files.map(Redacted4.value) : undefined
1467
+ },
1468
+ slots: { actions: staged ? undefined : picker },
1469
+ onEmit: (event) => {
1470
+ const files = event._tag === "Change" ? [event.file] : event._tag === "FilesChange" ? Redacted4.value(event.files).map((file) => Redacted4.make(file)) : event._tag === "Clear" ? [] : undefined;
1471
+ return files && (staged ? AssetInputMessage.SetFiles({ files }) : AssetInputMessage.Stage({ files }));
1472
+ }
1473
+ });
1474
+ const showPicker = p.multiple || ids.length === 0;
1475
+ const buttonTrigger = p.uploadTrigger === "button" && upload && !p.disabled;
1476
+ return Field(h, {
1477
+ props: { disabled: p.disabled },
1478
+ view: (field) => FieldRoot(h, field).children(FieldLabel(h, field, {
1479
+ class: buttonTrigger && !p.assets ? "sr-only" : undefined
1480
+ }).children(p.label), ids.length > 0 && h.div.class(p.multiple ? "flex min-w-0 gap-2 overflow-x-auto p-1 scroll-p-1" : "min-w-0").children(ids.map((id) => {
1481
+ const item = selected.get(id);
1482
+ const imageSrc = item && assetImage(item).imageSrc;
1483
+ return h.div.key(id).class(p.multiple ? "flex min-w-40 max-w-full shrink-0 items-center gap-2 rounded-lg border p-2" : "flex min-w-0 items-center gap-2 rounded-lg border p-2").children(h.span.class("bg-muted grid size-9 shrink-0 place-items-center overflow-hidden rounded-md").children(imageSrc ? h.img.class("size-full object-cover").attrs({
1484
+ src: imageSrc,
1485
+ alt: ""
1486
+ }) : FileTypeIcon(h, item?.mimeType ?? "")), h.div.class("min-w-0 flex-1").children(h.p.class("truncate text-sm font-medium").children(item?.name ?? labels.selected), item?.mimeType && h.p.class("text-muted-foreground truncate text-xs").children(item.mimeType)), Button3(h, {
1487
+ variant: "ghost",
1488
+ size: "icon-sm",
1489
+ props: { type: "button", disabled: p.disabled },
1490
+ onPress: AssetInputMessage.Changed({
1491
+ ids: ids.filter((value) => value !== id)
1492
+ })
1493
+ }).attr("aria-label", item ? `${labels.remove}: ${item.name}` : labels.remove).children(X2(h, { size: 16 })));
1494
+ })), showPicker && (upload && !p.disabled && !buttonTrigger ? choose(false) : picker), showPicker && !p.disabled && !upload && h.slots.uploadAction, (upload || model.open) && Dialog(h, {
1495
+ props: { open: model.open },
1496
+ onEmit: (event) => event._tag === "RequestedClose" ? AssetInputMessage.Dismiss() : event._tag === "RequestedOpen" ? AssetInputMessage.Open() : event._tag === "Settled" && !event.open ? AssetInputMessage.Closed() : undefined,
1497
+ view: (dialog) => h.div.children(showPicker && buttonTrigger && dialog.trigger(h.button.class(buttonVariants3()).attr("type", "button")).children(copy.upload), dialog.portal(h.div.class("relative z-50"))?.children(DialogBackdrop(h, dialog), DialogViewport(h, dialog, {
1498
+ class: "grid-cols-1 grid-rows-1"
1499
+ }).children(DialogPopup(h, dialog, {
1500
+ class: "min-w-0 overflow-x-hidden overflow-y-auto [overflow-wrap:anywhere]"
1501
+ }).children(DialogHeader(h).children(DialogTitle(h, dialog).children(p.assets ? copy.dialogTitle : copy.libraryDialogTitle), DialogDescription(h, dialog).children(p.assets ? copy.dialogDescription : copy.libraryDialogDescription)), model.jobs.length > 0 ? h.div.class("grid min-w-0 grid-cols-1 gap-2").children(model.jobs.map((job) => {
1502
+ const file = Redacted4.value(job.file);
1503
+ return UploadAttachment(h, {
1504
+ key: String(job.id),
1505
+ props: {
1506
+ name: file.name,
1507
+ state: assetUploadState(job, copy),
1508
+ locale,
1509
+ canCancel: true,
1510
+ canRetry: Boolean(upload && !p.disabled && job.phase === "error"),
1511
+ canRemove: job.phase !== "done",
1512
+ messages: upload?.processingLabel ? {
1513
+ [locale]: {
1514
+ processing: upload.processingLabel
1515
+ }
1516
+ } : undefined
1517
+ },
1518
+ slots: {
1519
+ fileIcon: FileThumbnail(h, file)
1520
+ },
1521
+ onEmit: (event) => event._tag === "Retry" ? AssetInputMessage.Retry({ id: job.id }) : AssetInputMessage.RemoveJob({ id: job.id })
1522
+ });
1523
+ })) : upload && !p.disabled && choose(true), hasInvalidAssetFiles(model.files, p.kind) && h.p.attr("role", "alert").class("text-destructive text-sm").children(copy.kindError), h.div.class("flex flex-wrap justify-end gap-2").children(dialog.close(h.button.class(buttonVariants3({ variant: "outline" })).attr("type", "button")).children(canCloseAssetUpload(model.jobs) ? copy.close : copy.cancel), upload && !p.disabled && !model.jobs.length && model.files.length > 0 && Button3(h, {
1524
+ props: {
1525
+ type: "button",
1526
+ disabled: hasInvalidAssetFiles(model.files, p.kind)
1527
+ },
1528
+ onPress: AssetInputMessage.Upload()
1529
+ }).children(copy.upload))))))
1530
+ }))
1531
+ });
1532
+ }
1533
+ });
1534
+ var connectedUpload = (props) => Layer.unwrap(Effect4.context().pipe(Effect4.map((context) => assetUploadLayer(libraryUpload(Effect4.runPromiseWith(context), props.locale ?? "en", props.replaceId)))));
1535
+ var ConnectedAssetInput = AssetInputView.pipe(Component7.provide(connectedUpload));
1536
+ var AssetInput = Html4.component({
1537
+ ...assetInputPickerOptions,
1538
+ name: "AssetInputConnection",
1539
+ props: assetInputOptions.props,
1540
+ message: AssetInputEvents,
1541
+ events: AssetInputEvents,
1542
+ slots: ["uploadAction"],
1543
+ reads: { localeConfig: krakstackLocaleRead4 }
1544
+ }).make({
1545
+ ...assetInputPickerBehaviours,
1546
+ update: ($, event) => $.emit(event),
1547
+ view: (h) => {
1548
+ const { access, uploader, replaceId, value } = h.props;
1549
+ const result = h.queries.library;
1550
+ const assets = h.props.assets ?? (value !== undefined && access?.permissions.includes("list") ? AsyncResult2.isSuccess(result) ? result.value.items : [] : undefined);
1551
+ const connected = !uploader && access?.permissions.includes(replaceId ? "update" : "create");
1552
+ const Input = connected ? ConnectedAssetInput : AssetInputView;
1553
+ const locale = h.props.locale ?? h.reads.localeConfig?.locale ?? "en";
1554
+ return Input(h, {
1555
+ key: JSON.stringify([access?.scopeKey, connected, replaceId, locale]),
1556
+ props: {
1557
+ ...h.props,
1558
+ ...assets === undefined ? {} : { assets },
1559
+ locale,
1560
+ ...connected ? { uploader: {} } : {}
1561
+ },
1562
+ slots: h.slots,
1563
+ onEmit: (event) => event
1564
+ });
1565
+ }
1566
+ });
1567
+ export {
1568
+ AssetInput,
1569
+ AssetInputEvents,
1570
+ AssetInputItemSchema,
1571
+ AssetUploadResult,
1572
+ RunAssetUpload,
1573
+ assetUploadLayer
1574
+ };