Repository navigation
Expand file tree
/
Copy pathexamples-react.html
More file actions
258 lines (242 loc) · 14.5 KB
/
Copy pathexamples-react.html
File metadata and controls
258 lines (242 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
<meta name="kmwc:title" content="React integration">
<meta name="kmwc:subtitle" content="A React component subscribes to a headless <code><web-dropzone></code> store via <code>useEffect</code> + <code>files-change</code>, then renders its own JSX file list with full pause / resume / retry control.">
<link rel="stylesheet" href="examples-local.css">
<style>
.rx-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-top: 1rem;
}
.rx-row {
display: grid;
grid-template-columns: 1.5rem 1fr 6rem 1fr 3rem auto;
gap: 0.75rem;
align-items: center;
padding: 0.6rem 0.8rem;
background: var(--kmwc-elevated-bg);
border: 1px solid var(--kmwc-border-color);
border-radius: 8px;
}
.rx-row__name { font-weight: 500; color: var(--kmwc-text-color-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rx-row__status {
font-size: 0.78rem;
text-transform: uppercase;
letter-spacing: 0.06em;
font-weight: 700;
text-align: center;
padding: 0.15rem 0.5rem;
border-radius: 999px;
}
.rx-row__status--pending { background: var(--kmwc-border-color); color: var(--kmwc-text-color-2); }
.rx-row__status--uploading{ background: var(--demo-info-bg); color: var(--demo-info-text-color); }
.rx-row__status--paused { background: var(--demo-warning-bg); color: var(--kmwc-warning-color); }
.rx-row__status--complete { background: var(--demo-success-bg); color: var(--kmwc-success-color); }
.rx-row__status--error { background: var(--demo-danger-bg); color: var(--kmwc-danger-color); }
/* Width is driven by the `--rx-progress` custom property on .rx-row
rather than an inline style on the fill, which gives React's
reconciler one stable element with a single changing CSS variable.
Avoids any per-tick remount / inline-style edge case in htm + React. */
.rx-row__bar {
position: relative;
height: 0.45rem;
background: var(--kmwc-border-color);
border-radius: 999px;
overflow: hidden;
}
/* No CSS transition — width is driven by --rx-progress which React
updates on every `files-change` (≈ 60 Hz during an upload). A 180 ms
transition would mean the bar visibly trails the numeric % by ~11
frames; with the transition removed, the bar tracks the percentage
text exactly. */
.rx-row__bar-fill {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: var(--rx-progress, 0%);
background: var(--kmwc-accent-color);
}
.rx-row__pct {
font-variant-numeric: tabular-nums;
text-align: right;
color: var(--kmwc-text-color-2);
font-size: 0.85rem;
}
.rx-row__actions { display: flex; gap: 0.35rem; }
.rx-row__action {
border: 1px solid var(--kmwc-border-color-strong);
background: var(--kmwc-main-bg);
border-radius: 6px;
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
color: var(--kmwc-text-color-2);
cursor: pointer;
}
.rx-row__action:hover { background: var(--kmwc-hover-bg); }
.rx-empty {
padding: 2rem 1rem;
text-align: center;
color: var(--kmwc-text-color-4);
font-style: italic;
border: 1px dashed var(--kmwc-border-color-strong);
border-radius: 8px;
}
.rx-toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 1rem;
}
.rx-toolbar button {
border: 1px solid var(--kmwc-border-color-strong);
background: var(--kmwc-main-bg);
border-radius: 6px;
padding: 0.4rem 0.85rem;
font-size: 0.85rem;
color: var(--kmwc-text-color-2);
cursor: pointer;
}
.rx-toolbar button:hover { background: var(--kmwc-hover-bg); }
.rx-toolbar button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
</style>
<section class="example-section">
<h2>RC01 · Why headless mode unlocks React patterns</h2>
<p>React expects to own the DOM it manages. With <code>render-mode="headless"</code> the dropzone steps back: it holds <code>FileState[]</code>, dispatches events, and lets your component own the rendering. The native <code><web-dropzone-picker></code> satellite is still used as the drop surface, because re-implementing drag-and-drop in React would mean re-implementing a feature web-dropzone already ships.</p>
<div class="note">
<div class="note-title">Pattern</div>
<ul>
<li>One <code>useRef</code> on the store element, one <code>useEffect</code> attaches the listener + upload callback.</li>
<li><code>useState</code> holds the file array; the <code>files-change</code> handler replaces it whole (the event is rAF-coalesced so this is cheap).</li>
<li>Per-row actions call <code>store.pauseFile(id)</code> / <code>resumeFile</code> / <code>retryFile</code> — the next event tick re-renders.</li>
</ul>
</div>
<p>This demo uses <a href="https://github.com/developit/htm" target="_blank">htm</a> for tagged-template JSX so the page works without a build step. With Babel or a real bundler you'd write the same code in regular JSX.</p>
<p><strong>Heads-up:</strong> htm passes attribute names through verbatim, so you still write <code>className</code> (not <code>class</code>) and <code>onClick</code> (not <code>onclick</code>) — anything React expects. <code>class</code> is silently dropped by React, which means CSS classes vanish and styled elements like the progress bar end up invisible.</p>
<p><strong>CSS transitions on the progress bar:</strong> avoid <code>transition: width Xms</code> on the bar fill. <code>files-change</code> fires ≈ 60 Hz during an upload, so a 180 ms transition makes the bar lag the numeric % by ~11 frames — looks like the bar is barely moving while the text shoots ahead. Drive the width directly from a CSS custom property on the row and skip the transition; React's per-event commits already give you smooth motion.</p>
</section>
<section class="example-section">
<h2>RC02 · Live demo</h2>
<p>The React tree below renders the picker, list, and a toolbar with <em>pause all / resume all / retry all / clear</em>. Drop a few files and watch React re-render on every coalesced <code>files-change</code> event.</p>
<p>The code under the demo is the whole page script (htm flavour) — exactly as it runs here.</p>
<kmwc-demo>
<div id="react-root"></div>
<script type="module" data-kmwc-show>
// Bare specifiers (`'react'`, `'react-dom/client'`) would normally be
// resolved by a browser importmap, but Vite's dev server runs its own
// import-analysis on inline modules and rejects them before the
// browser ever sees the importmap. Use full CDN URLs instead so Vite
// passes them through untouched.
import React, { useEffect, useRef, useState } from 'https://esm.sh/react@18'
import { createRoot } from 'https://esm.sh/react-dom@18/client'
import htm from 'https://esm.sh/htm@3'
const html = htm.bind(React.createElement)
function simulateUpload({ durationMs = 4000, failureRate = 0 } = {}) {
return ({ file, setProgress, signal, startPercent }) => new Promise((resolve, reject) => {
const startPct = startPercent
if (startPct >= 100) {
resolve({ metadata: { uploadedAt: new Date().toISOString() } })
return
}
const remainingPct = 100 - startPct
const remainingMs = durationMs * (remainingPct / 100)
const start = performance.now()
let aborted = false
signal?.addEventListener('abort', () => {
aborted = true
reject(new DOMException('Aborted', 'AbortError'))
})
const tick = () => {
if (aborted) return
const elapsed = performance.now() - start
const pct = Math.min(100, startPct + remainingPct * (elapsed / remainingMs))
setProgress(pct)
if (pct >= 100) {
if (Math.random() < failureRate) {
reject(new Error('Simulated upload failure'))
} else {
resolve({ metadata: { uploadedAt: new Date().toISOString() } })
}
return
}
requestAnimationFrame(tick)
}
requestAnimationFrame(tick)
})
}
const iconFor = (status) => ({
pending: '⏳', uploading: '⬆️', paused: '⏸️',
complete: '✅', error: '⚠️'
}[status] ?? '·')
const actionLabel = (status) => ({
uploading: 'Pause', paused: 'Resume', error: 'Retry'
}[status])
function Uploader() {
const storeRef = useRef(null)
const [files, setFiles] = useState([])
// Diagnostic — counts how many files-change events the listener
// actually receives. If this barely moves during an upload while
// progress visibly changes elsewhere, React is dropping renders.
const [eventCount, setEventCount] = useState(0)
useEffect(() => {
const store = storeRef.current
store.uploadFileCallback = simulateUpload({ durationMs: 4000 })
const onChange = (e) => {
setFiles(e.detail.files)
setEventCount((c) => c + 1)
}
store.addEventListener('files-change', onChange)
return () => store.removeEventListener('files-change', onChange)
}, [])
const rowAction = (f) => {
const s = storeRef.current
if (f.status === 'uploading') return s.pauseFile(f.id)
if (f.status === 'paused') return s.resumeFile(f.id)
if (f.status === 'error') return s.retryFile(f.id)
}
const callAll = (method) => () => storeRef.current?.[method]?.()
const anyUploading = files.some((f) => f.status === 'uploading')
const anyPaused = files.some((f) => f.status === 'paused')
const anyError = files.some((f) => f.status === 'error')
return html`
<web-dropzone ref=${storeRef} id="rx-store" render-mode="headless" multiple max-file-count="6"></web-dropzone>
<web-dropzone-picker for="rx-store" selector-appearance="card" labels='{"labels.prompt": "Drop files for React"}'></web-dropzone-picker>
${files.length === 0
? html`<div className="rx-empty">No files yet — drop something above.</div>`
: html`<div className="rx-list">
${files.map((f) => html`
<div key=${f.id} className="rx-row" style=${{ '--rx-progress': f.progress + '%' }}>
<span>${iconFor(f.status)}</span>
<span className="rx-row__name">${f.name}</span>
<span className=${`rx-row__status rx-row__status--${f.status}`}>${f.status}</span>
<span className="rx-row__bar">
<span className="rx-row__bar-fill"></span>
</span>
<span className="rx-row__pct">${f.progress.toFixed(1)}%</span>
<span className="rx-row__actions">
${actionLabel(f.status) && html`<button className="rx-row__action" onClick=${() => rowAction(f)}>${actionLabel(f.status)}</button>`}
</span>
</div>
`)}
</div>`}
<div className="rx-toolbar">
<button onClick=${callAll('pauseAll')} disabled=${!anyUploading}>Pause all</button>
<button onClick=${callAll('resumeAll')} disabled=${!anyPaused}>Resume all</button>
<button onClick=${callAll('retryAll')} disabled=${!anyError}>Retry all</button>
<button onClick=${callAll('clear')} disabled=${files.length === 0}>Clear</button>
<span style=${{ marginLeft: 'auto', alignSelf: 'center', fontSize: '0.85rem', color: 'var(--kmwc-text-color-2)', fontVariantNumeric: 'tabular-nums' }}>
files-change received: <strong>${eventCount}</strong>
</span>
</div>
`
}
createRoot(document.getElementById('react-root')).render(React.createElement(Uploader))
</script>
</kmwc-demo>
</section>
<footer>
<p>Web Dropzone · <a href="https://github.com/keenmate/web-dropzone">GitHub</a> · <a href="examples-architecture.html">Architecture</a></p>
</footer>