@lostgradient/cinder 0.23.1 → 0.24.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.
Files changed (122) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/components.json +1 -1
  3. package/dist/_internal/text-direction-sheet-index.d.ts +69 -0
  4. package/dist/components/access-gate/index.js +447 -354
  5. package/dist/components/approval-card/index.js +72 -1
  6. package/dist/components/autocomplete/index.js +72 -1
  7. package/dist/components/avatar-group/index.js +72 -1
  8. package/dist/components/carousel/index.js +73 -1
  9. package/dist/components/combobox/index.js +72 -1
  10. package/dist/components/command-menu/index.js +74 -1
  11. package/dist/components/context-menu/index.js +74 -1
  12. package/dist/components/date-picker/index.js +72 -1
  13. package/dist/components/date-range-field/index.js +72 -1
  14. package/dist/components/dropdown/index.js +74 -1
  15. package/dist/components/dropdown-menu/index.js +74 -1
  16. package/dist/components/file-upload/file-upload-list.svelte.d.ts +12 -0
  17. package/dist/components/file-upload/file-upload-utilities.d.ts +15 -0
  18. package/dist/components/file-upload/file-upload.css +152 -11
  19. package/dist/components/file-upload/file-upload.schema.js +39 -5
  20. package/dist/components/file-upload/file-upload.types.d.ts +33 -5
  21. package/dist/components/file-upload/index.js +1017 -264
  22. package/dist/components/hover-card/index.js +72 -1
  23. package/dist/components/invocation-rule-builder/index.js +72 -1
  24. package/dist/components/json-schema-editor/index.js +72 -1
  25. package/dist/components/mega-menu/index.js +73 -1
  26. package/dist/components/menu-bar/index.js +74 -1
  27. package/dist/components/multi-select/index.js +72 -1
  28. package/dist/components/navigation-bar/index.js +72 -1
  29. package/dist/components/popover/index.js +72 -1
  30. package/dist/components/portal/index.js +72 -1
  31. package/dist/components/selection-popover/index.js +72 -1
  32. package/dist/components/slider/index.js +73 -1
  33. package/dist/components/speed-dial/index.js +72 -1
  34. package/dist/components/speed-dial-action/index.js +72 -1
  35. package/dist/components/tooltip/index.js +72 -1
  36. package/dist/index.js +18932 -18257
  37. package/dist/server/components/access-gate/index.js +7 -4
  38. package/dist/server/components/approval-card/index.js +6 -5
  39. package/dist/server/components/autocomplete/index.js +6 -5
  40. package/dist/server/components/avatar-group/index.js +6 -5
  41. package/dist/server/components/carousel/index.js +3 -2
  42. package/dist/server/components/combobox/index.js +7 -6
  43. package/dist/server/components/command-menu/index.js +6 -5
  44. package/dist/server/components/context-menu/index.js +7 -6
  45. package/dist/server/components/date-picker/index.js +7 -6
  46. package/dist/server/components/date-range-field/index.js +7 -6
  47. package/dist/server/components/dropdown/index.js +7 -6
  48. package/dist/server/components/dropdown-menu/index.js +7 -6
  49. package/dist/server/components/file-upload/index.js +10 -2
  50. package/dist/server/components/hover-card/index.js +5 -4
  51. package/dist/server/components/icons/index.js +17 -11
  52. package/dist/server/components/invocation-rule-builder/index.js +7 -6
  53. package/dist/server/components/json-schema-editor/index.js +10 -7
  54. package/dist/server/components/mega-menu/index.js +4 -3
  55. package/dist/server/components/menu-bar/index.js +7 -6
  56. package/dist/server/components/multi-select/index.js +5 -4
  57. package/dist/server/components/navigation-bar/index.js +5 -4
  58. package/dist/server/components/popover/index.js +6 -5
  59. package/dist/server/components/portal/index.js +4 -3
  60. package/dist/server/components/selection-popover/index.js +5 -4
  61. package/dist/server/components/slider/index.js +4 -3
  62. package/dist/server/components/speed-dial/index.js +6 -5
  63. package/dist/server/components/speed-dial-action/index.js +5 -4
  64. package/dist/server/components/tooltip/index.js +6 -5
  65. package/dist/server/index.js +45 -39
  66. package/dist/server/{index.server-116jzzd0.js → index.server-0d1703dw.js} +1 -1
  67. package/dist/server/index.server-3cpak389.js +689 -0
  68. package/dist/server/{index.server-wmeaz6qk.js → index.server-5smw78xz.js} +78 -109
  69. package/dist/server/{index.server-nwgxhrzg.js → index.server-6vd98s4m.js} +1 -1
  70. package/dist/server/{index.server-4hvjet4z.js → index.server-7h3nmj3g.js} +7 -5
  71. package/dist/server/{index.server-3e8n2sry.js → index.server-7vzk6qhf.js} +2 -2
  72. package/dist/server/{index.server-h6qhx8mw.js → index.server-83fg1k4x.js} +7 -1
  73. package/dist/server/{index.server-5mz0e28m.js → index.server-8bv9bkm6.js} +1 -1
  74. package/dist/server/{index.server-59hgwg0n.js → index.server-8xr5tbrn.js} +1 -1
  75. package/dist/server/{index.server-x5zjwrnb.js → index.server-aphnpg78.js} +2 -2
  76. package/dist/server/{index.server-9scm7zf9.js → index.server-aywvs10h.js} +1 -1
  77. package/dist/server/index.server-bfkka7x4.js +2 -0
  78. package/dist/server/{index.server-2h45p8kd.js → index.server-bjj2hpx1.js} +2 -2
  79. package/dist/server/{index.server-4w0rydct.js → index.server-bw1wbzzk.js} +1 -1
  80. package/dist/server/{index.server-w5f4ex0f.js → index.server-c71m0a88.js} +1 -1
  81. package/dist/server/{index.server-kergq7c5.js → index.server-cmz3t3zw.js} +1 -1
  82. package/dist/server/{index.server-t2p901p7.js → index.server-cn3tg876.js} +1 -1
  83. package/dist/server/{index.server-6z6s8qz8.js → index.server-d05m93p4.js} +1 -1
  84. package/dist/server/{index.server-yr2ndv9a.js → index.server-d7twz1zm.js} +1 -1
  85. package/dist/server/{index.server-1cnz5ax1.js → index.server-emqv9bz6.js} +1 -1
  86. package/dist/server/index.server-fvtdyxbc.js +2 -0
  87. package/dist/server/{index.server-5wmzrvvs.js → index.server-gg4jre7c.js} +1 -1
  88. package/dist/server/{index.server-t91tbrmn.js → index.server-h76gdmj1.js} +2 -2
  89. package/dist/server/{index.server-bjw3e1wh.js → index.server-hvp84h1d.js} +1 -1
  90. package/dist/server/{index.server-7kez94sz.js → index.server-j6wms88v.js} +1 -1
  91. package/dist/server/{index.server-8t53gqe7.js → index.server-k21nfvxe.js} +2 -2
  92. package/dist/server/{index.server-6771g0q4.js → index.server-mf4dr1kp.js} +5 -1
  93. package/dist/server/{index.server-s2dseqdh.js → index.server-p69bvf14.js} +1 -1
  94. package/dist/server/{index.server-br3khchh.js → index.server-ppw26tpq.js} +1 -1
  95. package/dist/server/{index.server-q7r53g7z.js → index.server-s4pfz6pb.js} +1 -1
  96. package/dist/server/index.server-sje2hers.js +97 -0
  97. package/dist/server/{index.server-drdtprjs.js → index.server-spdds2hk.js} +1 -1
  98. package/dist/server/index.server-sz6y8xqk.js +2 -0
  99. package/dist/server/index.server-tkv7aey1.js +35 -0
  100. package/dist/server/{index.server-rf9pd5mr.js → index.server-w20xg416.js} +1 -1
  101. package/dist/server/index.server-xvg6mjdw.js +73 -0
  102. package/dist/server/{index.server-03ndc3td.js → index.server-ye5xkaq2.js} +1 -1
  103. package/dist/server/{index.server-ejdprw7f.js → index.server-ykvb4rcc.js} +1 -1
  104. package/dist/server/index.server-yq9evnp4.js +38 -0
  105. package/dist/server/index.server-yrfah2yz.js +33 -0
  106. package/dist/server/{index.server-9n2bc545.js → index.server-zbgdfzy6.js} +1 -1
  107. package/dist/server/{index.server-n6wm89xy.js → index.server-zj0x74bt.js} +1 -1
  108. package/package.json +1 -1
  109. package/src/_internal/text-direction-css.ts +6 -0
  110. package/src/_internal/text-direction-sheet-index.ts +170 -0
  111. package/src/components/file-upload/file-upload-list.svelte +198 -0
  112. package/src/components/file-upload/file-upload-utilities.ts +262 -0
  113. package/src/components/file-upload/file-upload.css +152 -11
  114. package/src/components/file-upload/file-upload.examples.json +1 -1
  115. package/src/components/file-upload/file-upload.schema.json +38 -4
  116. package/src/components/file-upload/file-upload.schema.ts +40 -4
  117. package/src/components/file-upload/file-upload.svelte +176 -146
  118. package/src/components/file-upload/file-upload.types.ts +33 -5
  119. package/src/components/portal/portal.utilities.svelte.ts +8 -0
  120. package/dist/server/index.server-1qvmrpnx.js +0 -328
  121. package/dist/server/index.server-4n1mxg74.js +0 -2
  122. package/dist/server/index.server-7trweg3f.js +0 -61
@@ -0,0 +1,170 @@
1
+ /**
2
+ * A cheap per-stylesheet index of "does this sheet declare `direction`
3
+ * anywhere?", used to skip whole stylesheets before the expensive direction
4
+ * walk in `text-direction-css.ts` ever looks at them.
5
+ *
6
+ * ## Why
7
+ *
8
+ * `matchesDirectionStyleRule` has exactly one way to return `true`: a
9
+ * `CSSStyleRule` whose `style.direction` is truthy AND whose selector matches
10
+ * the element (text-direction-css.ts:127-147). Every other branch is recursion
11
+ * — into `@import`ed sheets, native nesting, `@scope`, and conditional
12
+ * at-rules — that must eventually reach that same check. So a stylesheet that
13
+ * declares `direction` nowhere in its rule tree can never contribute a match,
14
+ * and skipping it is behavior-preserving by construction.
15
+ *
16
+ * That matters because the walk it skips is not cheap. It resolves nested
17
+ * selectors, evaluates `@scope` roots and limits, and runs container-query
18
+ * conditions — per element, per ancestor, per call, with no memoization above
19
+ * this layer (`resolveTextDirection` allocates a fresh `WeakMap` per call, and
20
+ * `elementDirectionStyleOverride` passes none at all). Measured in a real
21
+ * consuming app, one `Dropdown` mount walked a 179-sheet / 7651-rule document
22
+ * about 42 times — 7518 `sheet.cssRules` reads plus 44184 nested reads, ~370ms
23
+ * of blocking main-thread time — to answer a question whose answer was `false`
24
+ * for every element, because that app's CSS contains no `direction`
25
+ * declarations at all. See stevekinney/cinder#1262.
26
+ *
27
+ * The index makes that case cost one `cssRules.length` read per sheet.
28
+ *
29
+ * ## Cache validity
30
+ *
31
+ * Only NEGATIVE results ("declares no direction") are risky to cache — a
32
+ * positive answer sends the caller down its normal walk, which re-reads the
33
+ * CSSOM anyway. Negative entries are keyed by stylesheet object and validated
34
+ * against the sheet's top-level rule count, which changes on any
35
+ * `insertRule`/`deleteRule`. Three cases opt out of negative caching entirely
36
+ * rather than risk a stale skip:
37
+ *
38
+ * - A **constructed** stylesheet (`new CSSStyleSheet()`, i.e. no `ownerNode`).
39
+ * `replace()`/`replaceSync()` throw on any sheet that is not constructed, so
40
+ * constructed sheets are exactly the ones whose whole contents can be swapped
41
+ * without the rule count moving. They are re-scanned on every query.
42
+ * - A sheet containing `@import`, because an imported sheet loads
43
+ * asynchronously and can gain rules without changing its importer's count.
44
+ * - A sheet whose CSSOM is unreadable (cross-origin), which is reported as
45
+ * "declares direction" so the caller falls through to its own guarded walk
46
+ * instead of being silently filtered out.
47
+ *
48
+ * That leaves two mutations a rule-count key cannot observe, both on a
49
+ * non-constructed sheet: an in-place declaration edit
50
+ * (`rule.style.direction = 'rtl'`), and a `deleteRule` + `insertRule` pair
51
+ * between two queries that lands on the same count. Detecting either would mean
52
+ * reading every rule's text on every query, which is the cost this module
53
+ * exists to avoid. Both are covered by `invalidatePortalDirection()`, the
54
+ * library's existing public hook for "a CSSOM edit that emits no DOM
55
+ * mutation", which clears this index; {@link resetDirectionStyleSheetIndex} is
56
+ * the internal entry point it calls.
57
+ */
58
+
59
+ interface SheetIndexEntry {
60
+ /** Top-level rule count the entry was computed from. */
61
+ readonly ruleCount: number;
62
+ /** Whether any rule in the sheet's tree declares `direction`. */
63
+ readonly declaresDirection: boolean;
64
+ }
65
+
66
+ let sheetIndex = new WeakMap<CSSStyleSheet, SheetIndexEntry>();
67
+
68
+ /** Drops every cached entry. Exported for tests and for consumers that edit CSSOM declarations in place. */
69
+ export function resetDirectionStyleSheetIndex(): void {
70
+ // A WeakMap has no clear(); swapping in a fresh map is the equivalent.
71
+ sheetIndex = new WeakMap<CSSStyleSheet, SheetIndexEntry>();
72
+ }
73
+
74
+ /**
75
+ * Whether `sheet` declares `direction` on any rule in its tree — including
76
+ * inside nesting, `@scope`, conditional at-rules, and `@import`ed sheets.
77
+ *
78
+ * Permissive on purpose: this is a pre-filter, so anything it cannot read is
79
+ * reported as `true` and left for the caller's full (already guarded) walk. It
80
+ * also ignores whether a conditional rule is currently active, because the
81
+ * caller evaluates that itself.
82
+ */
83
+ export function styleSheetDeclaresDirection(sheet: CSSStyleSheet): boolean {
84
+ let rules: CSSRuleList;
85
+ try {
86
+ rules = sheet.cssRules;
87
+ } catch {
88
+ return true;
89
+ }
90
+
91
+ const cached = sheetIndex.get(sheet);
92
+ if (cached !== undefined && cached.ruleCount === rules.length) return cached.declaresDirection;
93
+
94
+ // `replace()`/`replaceSync()` throw on non-constructed sheets, so a
95
+ // constructed sheet is exactly the kind whose entire contents can be swapped
96
+ // without moving the rule count. Never cache a negative for one.
97
+ const isConstructed = Reflect.get(sheet, 'ownerNode') == null;
98
+
99
+ const scan: ScanState = { declaresDirection: false, cacheable: !isConstructed };
100
+ scanRuleList(rules, scan);
101
+
102
+ // A positive answer is always cacheable: it sends the caller down its normal
103
+ // walk, which re-reads the CSSOM itself. Only a negative can wrongly skip a
104
+ // sheet, so only a negative needs a key it can trust.
105
+ if (scan.cacheable || scan.declaresDirection) {
106
+ sheetIndex.set(sheet, { ruleCount: rules.length, declaresDirection: scan.declaresDirection });
107
+ } else {
108
+ sheetIndex.delete(sheet);
109
+ }
110
+ return scan.declaresDirection;
111
+ }
112
+
113
+ interface ScanState {
114
+ declaresDirection: boolean;
115
+ cacheable: boolean;
116
+ }
117
+
118
+ function scanRuleList(rules: CSSRuleList | Iterable<CSSRule>, state: ScanState): void {
119
+ for (const rule of Array.from(rules)) {
120
+ if (state.declaresDirection) return;
121
+
122
+ // CSSImportRule. An imported sheet loads asynchronously, so its importer's
123
+ // rule count is not a sound key for a NEGATIVE result — scan it, but mark
124
+ // the sheet uncacheable unless the scan comes back positive.
125
+ if (Reflect.get(rule, 'type') === 3) {
126
+ state.cacheable = false;
127
+ const imported = Reflect.get(rule, 'styleSheet');
128
+ if (imported) {
129
+ try {
130
+ const importedRules: unknown = Reflect.get(imported, 'cssRules');
131
+ if (isRuleCollection(importedRules)) scanRuleList(importedRules, state);
132
+ } catch {
133
+ // Cross-origin imports deny CSSOM access; assume they could declare it.
134
+ state.declaresDirection = true;
135
+ }
136
+ }
137
+ continue;
138
+ }
139
+
140
+ // Mirrors `isCssStyleRule` in text-direction-css.ts: a style rule is the
141
+ // only rule kind whose `direction` the walk can ever act on, and it is
142
+ // identified by having both a `style` object and a string `selectorText`.
143
+ const style: unknown = Reflect.get(rule, 'style');
144
+ if (
145
+ typeof style === 'object' &&
146
+ style !== null &&
147
+ typeof Reflect.get(rule, 'selectorText') === 'string' &&
148
+ Boolean(Reflect.get(style, 'direction'))
149
+ ) {
150
+ state.declaresDirection = true;
151
+ return;
152
+ }
153
+
154
+ if (!('cssRules' in rule)) continue;
155
+ try {
156
+ const nested: unknown = Reflect.get(rule, 'cssRules');
157
+ if (isRuleCollection(nested)) scanRuleList(nested, state);
158
+ } catch {
159
+ state.declaresDirection = true;
160
+ return;
161
+ }
162
+ }
163
+ }
164
+
165
+ function isRuleCollection(value: unknown): value is CSSRuleList | Iterable<CSSRule> {
166
+ if (typeof CSSRuleList !== 'undefined' && value instanceof CSSRuleList) return true;
167
+ if (Array.isArray(value)) return true;
168
+ if (typeof value !== 'object' || value === null) return false;
169
+ return typeof Reflect.get(value, Symbol.iterator) === 'function';
170
+ }
@@ -0,0 +1,198 @@
1
+ <script lang="ts">
2
+ import { tick } from 'svelte';
3
+ import RotateCcwIcon from 'lucide-svelte/icons/rotate-ccw';
4
+ import XIcon from 'lucide-svelte/icons/x';
5
+ import { formatBytes } from '../../utilities/format-bytes.ts';
6
+ import { fileTypeIcon } from './file-upload-utilities.ts';
7
+ let { entries, disabled, removable, onFileRetry, onRemove, onQueueEmptyFocus, } = $props();
8
+ const generatedId = $props.id();
9
+ let listElement = $state();
10
+ let pendingRemovalFocus = $state();
11
+ let pendingRetryFocus = $state();
12
+ function restoreRemovalFocus(pending) {
13
+ const activeElement = pending.removeButton.ownerDocument.activeElement;
14
+ if (activeElement && activeElement !== pending.removeButton.ownerDocument.body)
15
+ return;
16
+ if (pending.nextButton?.isConnected)
17
+ pending.nextButton.focus();
18
+ else
19
+ onQueueEmptyFocus();
20
+ }
21
+ $effect(() => {
22
+ const pending = pendingRemovalFocus;
23
+ if (!pending || entries.some((entry) => entry.id === pending.entryId))
24
+ return;
25
+ queueMicrotask(async () => {
26
+ await tick();
27
+ if (pendingRemovalFocus !== pending)
28
+ return;
29
+ restoreRemovalFocus(pending);
30
+ pendingRemovalFocus = undefined;
31
+ });
32
+ });
33
+ $effect(() => {
34
+ const pending = pendingRetryFocus;
35
+ const entry = pending && entries.find((candidate) => candidate.id === pending.entryId);
36
+ if (entry?.status === 'error' && entry.rejectionReason === undefined && onFileRetry)
37
+ return;
38
+ if (!pending)
39
+ return;
40
+ queueMicrotask(async () => {
41
+ await tick();
42
+ if (pendingRetryFocus !== pending || pending.retryButton.isConnected)
43
+ return;
44
+ const activeElement = pending.retryButton.ownerDocument.activeElement;
45
+ if (!activeElement || activeElement === pending.retryButton.ownerDocument.body) {
46
+ onQueueEmptyFocus();
47
+ }
48
+ pendingRetryFocus = undefined;
49
+ });
50
+ });
51
+ function progressValue(progress) {
52
+ if (progress === undefined)
53
+ return 0;
54
+ return Math.max(0, Math.min(100, progress));
55
+ }
56
+ async function handleRemove(entry, index, removeButton) {
57
+ const removeButtons = listElement?.querySelectorAll('.cinder-file-upload__remove');
58
+ const nextButton = removeButtons?.[index + 1] ?? removeButtons?.[index - 1];
59
+ pendingRemovalFocus = { entryId: entry.id, removeButton, nextButton };
60
+ const pending = pendingRemovalFocus;
61
+ onRemove(entry);
62
+ await tick();
63
+ if (pendingRemovalFocus !== pending)
64
+ return;
65
+ if (removeButton.isConnected)
66
+ return;
67
+ restoreRemovalFocus(pending);
68
+ pendingRemovalFocus = undefined;
69
+ }
70
+ async function handleRetry(entry, retryButton) {
71
+ pendingRetryFocus = { entryId: entry.id, retryButton };
72
+ const pending = pendingRetryFocus;
73
+ onFileRetry?.(entry);
74
+ await tick();
75
+ if (pendingRetryFocus !== pending)
76
+ return;
77
+ const activeElement = retryButton.ownerDocument.activeElement;
78
+ if (!retryButton.isConnected &&
79
+ (!activeElement || activeElement === retryButton.ownerDocument.body)) {
80
+ onQueueEmptyFocus();
81
+ }
82
+ if (!retryButton.isConnected)
83
+ pendingRetryFocus = undefined;
84
+ }
85
+ </script>
86
+
87
+ <ul bind:this={listElement} class="cinder-file-upload__list">
88
+ {#each entries as entry, index (entry.id)}
89
+ {@const errorId = entry.error ? `${generatedId}-${index}-error` : undefined}
90
+ {@const FileTypeIcon = fileTypeIcon(entry.file.type)}
91
+ <li class="cinder-file-upload__row" aria-describedby={errorId}>
92
+ <div class="cinder-file-upload__row-main">
93
+ <div class="cinder-file-upload__file-details">
94
+ <FileTypeIcon class="cinder-file-upload__file-icon" aria-hidden="true" />
95
+ <div class="cinder-file-upload__file-meta">
96
+ <span class="cinder-file-upload__file-name cinder-_truncate">{entry.file.name}</span>
97
+ <span class="cinder-file-upload__file-size">{formatBytes(entry.file.size)}</span>
98
+ </div>
99
+ </div>
100
+
101
+ <div class="cinder-file-upload__row-actions">
102
+ {#if entry.status === 'uploading'}
103
+ <span class="cinder-file-upload__status" data-status="uploading">Uploading</span>
104
+ {:else if entry.status === 'success'}
105
+ <span class="cinder-file-upload__status" data-status="success">
106
+ <svg
107
+ class="cinder-file-upload__status-icon"
108
+ aria-hidden="true"
109
+ viewBox="0 0 16 16"
110
+ fill="none"
111
+ xmlns="http://www.w3.org/2000/svg"
112
+ >
113
+ <path
114
+ d="M3.5 8.5L6.25 11.25L12.5 5"
115
+ stroke="currentColor"
116
+ stroke-width="1.5"
117
+ stroke-linecap="round"
118
+ stroke-linejoin="round"
119
+ />
120
+ </svg>
121
+ Complete
122
+ </span>
123
+ {:else if entry.status === 'error'}
124
+ <span class="cinder-file-upload__status" data-status="error">
125
+ <svg
126
+ class="cinder-file-upload__status-icon"
127
+ aria-hidden="true"
128
+ viewBox="0 0 16 16"
129
+ fill="none"
130
+ xmlns="http://www.w3.org/2000/svg"
131
+ >
132
+ <path
133
+ d="M8 4.5V8.25M8 11H8.00667M14 8C14 11.3137 11.3137 14 8 14C4.68629 14 2 11.3137 2 8C2 4.68629 4.68629 2 8 2C11.3137 2 14 4.68629 14 8Z"
134
+ stroke="currentColor"
135
+ stroke-width="1.5"
136
+ stroke-linecap="round"
137
+ stroke-linejoin="round"
138
+ />
139
+ </svg>
140
+ Failed
141
+ </span>
142
+ {:else}
143
+ <span class="cinder-file-upload__status" data-status="pending">Pending</span>
144
+ {/if}
145
+ {#if removable}
146
+ <button
147
+ type="button"
148
+ class="cinder-file-upload__remove"
149
+ {disabled}
150
+ aria-label={`Remove ${entry.file.name}`}
151
+ onclick={(event) => handleRemove(entry, index, event.currentTarget)}
152
+ >
153
+ <XIcon aria-hidden="true" />
154
+ </button>
155
+ {/if}
156
+ </div>
157
+ </div>
158
+
159
+ {#if entry.status === 'uploading'}
160
+ {@const value = progressValue(entry.progress)}
161
+ <div
162
+ class="cinder-file-upload__progress"
163
+ role="progressbar"
164
+ aria-label={`Uploading ${entry.file.name}`}
165
+ aria-valuemin="0"
166
+ aria-valuemax="100"
167
+ aria-valuenow={value}
168
+ >
169
+ <div
170
+ class="cinder-file-upload__progress-fill"
171
+ style={`--cinder-file-upload-progress: ${value}`}
172
+ ></div>
173
+ </div>
174
+ {/if}
175
+
176
+ {#if entry.error || (entry.status === 'error' && entry.rejectionReason === undefined && onFileRetry)}
177
+ <div class="cinder-file-upload__error-row">
178
+ {#if entry.error}
179
+ <p id={errorId} class="cinder-file-upload__error">{entry.error}</p>
180
+ {/if}
181
+ {#if entry.status === 'error' && entry.rejectionReason === undefined && onFileRetry}
182
+ <button
183
+ type="button"
184
+ class="cinder-file-upload__retry"
185
+ {disabled}
186
+ aria-label={`Retry ${entry.file.name}`}
187
+ aria-describedby={errorId}
188
+ onclick={(event) => handleRetry(entry, event.currentTarget)}
189
+ >
190
+ <RotateCcwIcon class="cinder-file-upload__retry-icon" aria-hidden="true" />
191
+ Retry
192
+ </button>
193
+ {/if}
194
+ </div>
195
+ {/if}
196
+ </li>
197
+ {/each}
198
+ </ul>
@@ -0,0 +1,262 @@
1
+ import FileIcon from 'lucide-svelte/icons/file';
2
+ import FileTextIcon from 'lucide-svelte/icons/file-text';
3
+ import ImageIcon from 'lucide-svelte/icons/image';
4
+ import TableIcon from 'lucide-svelte/icons/table';
5
+
6
+ import type { FileUploadEntry } from './file-upload.types.ts';
7
+
8
+ const INTERACTIVE_ARIA_ROLES = [
9
+ 'button',
10
+ 'checkbox',
11
+ 'combobox',
12
+ 'grid',
13
+ 'gridcell',
14
+ 'link',
15
+ 'listbox',
16
+ 'menu',
17
+ 'menubar',
18
+ 'menuitem',
19
+ 'menuitemcheckbox',
20
+ 'menuitemradio',
21
+ 'option',
22
+ 'radio',
23
+ 'radiogroup',
24
+ 'scrollbar',
25
+ 'searchbox',
26
+ 'slider',
27
+ 'spinbutton',
28
+ 'switch',
29
+ 'tab',
30
+ 'tablist',
31
+ 'textbox',
32
+ 'tree',
33
+ 'treegrid',
34
+ 'treeitem',
35
+ ];
36
+
37
+ export const INTERACTIVE_DESCENDANT_SELECTOR = [
38
+ ':any-link',
39
+ 'button',
40
+ 'input',
41
+ 'select',
42
+ 'textarea',
43
+ 'label',
44
+ 'summary',
45
+ 'details',
46
+ 'iframe',
47
+ 'object',
48
+ 'embed',
49
+ 'audio[controls]',
50
+ 'video[controls]',
51
+ "[contenteditable]:not([contenteditable='false'])",
52
+ ...INTERACTIVE_ARIA_ROLES.map((role) => `[role~='${role}']`),
53
+ '[tabindex]',
54
+ ].join(', ');
55
+
56
+ export function installFileUploadSurfaceActivation(
57
+ node: HTMLElement,
58
+ isDisabled: () => boolean,
59
+ openPicker: () => void,
60
+ ) {
61
+ function handleClick(event: MouseEvent) {
62
+ if (isDisabled()) return;
63
+ const ElementConstructor = node.ownerDocument.defaultView?.Element;
64
+ const target = event.target;
65
+ const interactiveDescendant =
66
+ ElementConstructor && target instanceof ElementConstructor
67
+ ? target.closest(INTERACTIVE_DESCENDANT_SELECTOR)
68
+ : null;
69
+ if (
70
+ interactiveDescendant &&
71
+ interactiveDescendant !== node &&
72
+ node.contains(interactiveDescendant)
73
+ )
74
+ return;
75
+ openPicker();
76
+ }
77
+ node.addEventListener('click', handleClick);
78
+ return { destroy: () => node.removeEventListener('click', handleClick) };
79
+ }
80
+
81
+ export function dataTransferHasFiles(dataTransfer: DataTransfer | null | undefined): boolean {
82
+ const fileTypes = dataTransfer?.types;
83
+ return fileTypes ? Array.from(fileTypes).includes('Files') : false;
84
+ }
85
+
86
+ const FILE_TYPE_ICONS: Record<string, typeof FileIcon> = {
87
+ 'image/': ImageIcon,
88
+ 'application/pdf': FileTextIcon,
89
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': FileTextIcon,
90
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': TableIcon,
91
+ 'text/csv': TableIcon,
92
+ 'text/': FileTextIcon,
93
+ };
94
+
95
+ const ACCEPT_TOKEN_LABELS: Record<string, string> = {
96
+ '.pdf': 'PDF',
97
+ 'application/pdf': 'PDF',
98
+ '.doc': 'DOC',
99
+ '.docx': 'DOCX',
100
+ 'application/msword': 'DOC',
101
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'DOCX',
102
+ '.xlsx': 'XLSX',
103
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'XLSX',
104
+ '.csv': 'CSV',
105
+ 'text/csv': 'CSV',
106
+ '.png': 'PNG',
107
+ 'image/png': 'PNG',
108
+ '.jpg': 'JPG',
109
+ '.jpeg': 'JPG',
110
+ 'image/jpeg': 'JPG',
111
+ };
112
+
113
+ function matchesAcceptToken(file: File, token: string): boolean {
114
+ const normalizedToken = token.trim().toLowerCase();
115
+ if (!normalizedToken) return true;
116
+
117
+ if (normalizedToken.startsWith('.')) {
118
+ return file.name.toLowerCase().endsWith(normalizedToken);
119
+ }
120
+
121
+ const fileType = file.type.toLowerCase();
122
+ if (normalizedToken.endsWith('/*')) {
123
+ return fileType.startsWith(normalizedToken.slice(0, -1));
124
+ }
125
+
126
+ return fileType === normalizedToken;
127
+ }
128
+
129
+ function formatList(items: string[]): string {
130
+ if (items.length === 0) return 'Any file type';
131
+ if (items.length === 1) return items[0]!;
132
+ if (items.length === 2) return `${items[0]} or ${items[1]}`;
133
+ return `${items.slice(0, -1).join(', ')}, or ${items.at(-1)}`;
134
+ }
135
+
136
+ export function acceptsFile(file: File, accept: string | undefined): boolean {
137
+ if (!accept?.trim()) return true;
138
+ const tokens = accept
139
+ .split(',')
140
+ .map((token) => token.trim())
141
+ .filter(Boolean);
142
+ if (tokens.length === 0) return true;
143
+ return tokens.some((token) => matchesAcceptToken(file, token));
144
+ }
145
+
146
+ export function nativeFilesMatch(fileList: FileList | null, files: File[]): boolean {
147
+ const currentFiles = Array.from(fileList ?? []);
148
+ return (
149
+ currentFiles.length === files.length &&
150
+ currentFiles.every((file, index) => file === files[index])
151
+ );
152
+ }
153
+
154
+ function nativeFilesFitTarget(fileList: FileList | null, files: File[]): boolean {
155
+ const currentFiles = Array.from(fileList ?? []);
156
+ return currentFiles.length > 0 && currentFiles.every((file) => files.includes(file));
157
+ }
158
+
159
+ export function fileUploadLimit(multiple: boolean, maxFiles: number | undefined) {
160
+ const normalizedMaxFiles =
161
+ maxFiles === undefined || !Number.isFinite(maxFiles)
162
+ ? undefined
163
+ : Math.max(0, Math.floor(maxFiles));
164
+ return multiple ? normalizedMaxFiles : Math.min(1, normalizedMaxFiles ?? 1);
165
+ }
166
+
167
+ export function installFilePickerReturnFallback(
168
+ inputElement: HTMLInputElement,
169
+ handleReturn: () => void,
170
+ ): () => void {
171
+ const ownerWindow = inputElement.ownerDocument.defaultView;
172
+ if (!ownerWindow) return () => {};
173
+ const windowTarget: Window = ownerWindow;
174
+ let timeoutId: number | undefined;
175
+ function cleanup() {
176
+ windowTarget.removeEventListener('focus', handleFocus);
177
+ if (timeoutId !== undefined) windowTarget.clearTimeout(timeoutId);
178
+ }
179
+ function handleFocus() {
180
+ timeoutId = windowTarget.setTimeout(() => {
181
+ cleanup();
182
+ handleReturn();
183
+ });
184
+ }
185
+ windowTarget.addEventListener('focus', handleFocus, { once: true });
186
+ return cleanup;
187
+ }
188
+
189
+ export function synchronizeNativeFileInput(
190
+ inputElement: HTMLInputElement | null | undefined,
191
+ entries: FileUploadEntry[],
192
+ multiple: boolean,
193
+ maxFiles: number | undefined,
194
+ ) {
195
+ if (!inputElement) return;
196
+ const acceptedEntries = entries.filter((entry) => entry.rejectionReason === undefined);
197
+ const limit = fileUploadLimit(multiple, maxFiles);
198
+ const acceptedFiles = (
199
+ limit === undefined ? acceptedEntries : acceptedEntries.slice(0, limit)
200
+ ).map((entry) => entry.file);
201
+ if (nativeFilesMatch(inputElement.files, acceptedFiles)) return;
202
+ if (typeof DataTransfer === 'undefined') {
203
+ if (!nativeFilesFitTarget(inputElement.files, acceptedFiles)) inputElement.value = '';
204
+ return;
205
+ }
206
+ let dataTransfer: DataTransfer;
207
+ try {
208
+ dataTransfer = new DataTransfer();
209
+ } catch {
210
+ if (!nativeFilesFitTarget(inputElement.files, acceptedFiles)) inputElement.value = '';
211
+ return;
212
+ }
213
+ for (const file of acceptedFiles) dataTransfer.items.add(file);
214
+ try {
215
+ inputElement.files = dataTransfer.files;
216
+ } catch {
217
+ if (!nativeFilesFitTarget(inputElement.files, acceptedFiles)) inputElement.value = '';
218
+ }
219
+ }
220
+
221
+ export function constrainFileUploadEntries(entries: FileUploadEntry[], limit: number | undefined) {
222
+ if (limit === undefined) return entries;
223
+ let acceptedCount = 0;
224
+ return entries.filter((entry) => {
225
+ if (entry.rejectionReason !== undefined) return true;
226
+ acceptedCount += 1;
227
+ return acceptedCount <= limit;
228
+ });
229
+ }
230
+
231
+ export function formatAcceptDescription(accept: string | undefined): string {
232
+ if (!accept?.trim()) return 'Any file type';
233
+ const labels = accept
234
+ .split(',')
235
+ .map((token) => token.trim().toLowerCase())
236
+ .filter(Boolean)
237
+ .map((token) => {
238
+ const knownLabel = ACCEPT_TOKEN_LABELS[token];
239
+ if (knownLabel) return knownLabel;
240
+ if (token.startsWith('.')) return token.slice(1).toUpperCase();
241
+ if (token.endsWith('/*')) return `${token.slice(0, -2)} files`;
242
+ return token;
243
+ });
244
+ const uniqueLabels = [...new Set(labels)];
245
+ const docIndex = uniqueLabels.indexOf('DOC');
246
+ const docxIndex = uniqueLabels.indexOf('DOCX');
247
+ if (docIndex !== -1 && docxIndex !== -1) {
248
+ uniqueLabels.splice(Math.max(docIndex, docxIndex), 1);
249
+ uniqueLabels[Math.min(docIndex, docxIndex)] = 'DOC/DOCX';
250
+ }
251
+ return formatList(uniqueLabels);
252
+ }
253
+
254
+ export function fileTypeIcon(fileType: string): typeof FileIcon {
255
+ const normalizedType = fileType.toLowerCase();
256
+ for (const [match, icon] of Object.entries(FILE_TYPE_ICONS)) {
257
+ if (match.endsWith('/') ? normalizedType.startsWith(match) : normalizedType === match) {
258
+ return icon;
259
+ }
260
+ }
261
+ return FileIcon;
262
+ }