@pseudolux-ui/media-library 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1083 @@
1
+ <view>
2
+ <div class="upload" $ref="host">
3
+ <input class="file-input" type="file" $ref="fileInput" $accept="state.accept" multiple tabindex="-1" aria-hidden="true" @change="filesChosen" />
4
+
5
+ <!-- Drop anywhere in the library. Named for where the files will go, so
6
+ nobody has to guess which group they land in. -->
7
+ <div class="up-drop" $show="state.dragging" aria-hidden="true">
8
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 15V3M7 8l5-5 5 5M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path></svg>
9
+ <h2>{{ state.dropLabel }}</h2>
10
+ <p class="px-muted">You'll describe and label them on the next screen.</p>
11
+ <span class="px-subtle">{{ state.typesHint }}</span>
12
+ </div>
13
+
14
+ <div class="up-b" role="dialog" aria-modal="true" $aria-label="state.title" $show="state.open" $ref="root" @keydown="onKey">
15
+ <div class="up-main">
16
+ <div class="up-head">
17
+ <div class="px-row head-row">
18
+ <h2>{{ state.title }}</h2>
19
+ <span class="px-subtle" aria-live="polite">{{ state.progressText }}</span>
20
+ <button class="px-btn px-btn-ghost px-btn-sm close" type="button" $ref="close" @click="close">{{ state.finished ? 'Done' : 'Hide' }}</button>
21
+ </div>
22
+
23
+ <!-- Where they go, asked before any is sent when there is more than
24
+ one group to choose from. -->
25
+ <div class="hold" $show="state.held">
26
+ <label class="hold-into">
27
+ <span>Add them to</span>
28
+ <select class="px-select" $model="state.heldGroup" aria-label="Group to upload to">
29
+ <option $for="one in state.writeGroups" $key="one" $value="one" $text="one"></option>
30
+ </select>
31
+ </label>
32
+ <span class="px-subtle">Everyone who can see {{ state.heldGroup }} will be able to use them.</span>
33
+ <button class="px-btn px-btn-primary px-btn-sm" type="button" @click="sendHeld">{{ state.heldAction }}</button>
34
+ </div>
35
+
36
+ <div class="up-prog" role="progressbar" aria-label="Uploaded" aria-valuemin="0" aria-valuemax="100" $aria-valuenow="state.pct"><span $style="state.barStyle"></span></div>
37
+ <div class="px-row badges">
38
+ <span class="px-badge px-badge-ok" $show="state.counts.ready">{{ state.counts.ready }} added</span>
39
+ <span class="px-badge px-badge-neutral" $show="state.counts.active">{{ state.counts.active }} uploading</span>
40
+ <span class="px-badge px-badge-warn" $show="state.counts.questions">{{ state.counts.questions }} to decide</span>
41
+ <span class="px-badge px-badge-warn" $show="state.counts.need">{{ state.counts.needLabel }}</span>
42
+ <span class="px-badge px-badge-danger" $show="state.counts.failed">{{ state.counts.failed }} couldn't upload</span>
43
+ </div>
44
+ <div class="up-tools">
45
+ <span class="px-subtle">Pick</span>
46
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" @click="pick('all')">All</button>
47
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" @click="pick('need')">Need words</button>
48
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" @click="pick('none')">None</button>
49
+ <span class="px-subtle tab-note">Tab moves to the next picture's alt text</span>
50
+ </div>
51
+ </div>
52
+
53
+ <div class="up-list">
54
+ <div class="up-r" $for="row in state.rows" $key="row.key" $class="{ 'is-on': row.picked }">
55
+ <input class="tick" type="checkbox" $checked="row.picked" $disabled="!row.pickable" $aria-label="'Pick ' + row.name" @change="togglePick(row)" />
56
+ <div class="up-th">
57
+ <img $src="row.preview" alt="" $style="row.active ? 'opacity: .55' : ''" />
58
+ <span class="pg" $show="row.active"><span $style="row.barStyle"></span></span>
59
+ </div>
60
+ <div class="up-body">
61
+ <div class="px-row name-row">
62
+ <b class="row-name">{{ row.name }}</b>
63
+ <span class="px-subtle">{{ row.sizeLabel }}</span>
64
+ <span class="px-badge px-badge-neutral" $show="state.manyGroups && row.group">{{ row.group }}</span>
65
+ <span class="px-badge px-badge-danger" $show="row.small" $title="row.smallTitle">{{ row.small }}</span>
66
+ <span class="px-subtle" $show="row.active">{{ row.pctLabel }}</span>
67
+ </div>
68
+
69
+ <div class="up-q" $if="row.question" role="group" $aria-label="'About ' + row.name">
70
+ <img class="q-pic" $src="row.matchThumb" alt="" />
71
+ <span class="q-text">{{ row.exact ? 'This exact picture is' : 'Looks like' }} <b>{{ row.matchName }}</b>{{ row.exact ? ', already in the library' : ', already in the library' }}{{ row.matchMeta }}.</span>
72
+ <button class="px-btn px-btn-primary px-btn-sm" type="button" @click="skipUpload(row)">Skip, keep that one</button>
73
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" $show="state.canConfirm" @click="uploadAnyway(row)">Add anyway</button>
74
+ </div>
75
+
76
+ <p class="px-subtle" $if="row.skipped">Skipped: using the one already in the library.</p>
77
+
78
+ <p class="fail" $if="row.failed" role="alert">
79
+ <span class="text-danger">{{ row.name }} {{ row.message }}</span> {{ row.help }}
80
+ <button class="px-btn px-btn-secondary px-btn-sm" type="button" $show="row.retryable" @click="retryUpload(row)">Try again</button>
81
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" @click="dismiss(row)">Dismiss</button>
82
+ </p>
83
+
84
+ <textarea class="px-textarea alt" $if="row.editable" placeholder="Alt text: what is in this picture?" $aria-label="'Alt text for ' + row.name" $data-key="row.key" @input="onAlt($event, row)" @blur="saveAlt(row)" @keydown="altKey($event)"></textarea>
85
+ <div class="up-meta" $show="row.meta.length || row.note">
86
+ <span $for="chip in row.meta" $key="chip">{{ chip }}</span>
87
+ <span class="plain" $show="row.note" $class="{ 'text-danger': row.noteFailed }">{{ row.note }}</span>
88
+ </div>
89
+ </div>
90
+ </div>
91
+ </div>
92
+
93
+ <div class="up-foot">
94
+ <button class="px-btn px-btn-primary" type="button" $disabled="!state.finished" @click="close">{{ state.finished ? 'Done' : 'Still uploading…' }}</button>
95
+ <button class="px-btn px-btn-secondary" type="button" $show="state.counts.need && state.finished" @click="describeRest">{{ state.describeLabel }}</button>
96
+ <button class="px-btn px-btn-ghost" type="button" @click="chooseFiles">Add more…</button>
97
+ <span class="px-subtle foot-note">Pictures are in the library as soon as they finish uploading. Words save as you go.</span>
98
+ </div>
99
+ </div>
100
+
101
+ <aside class="up-side" aria-label="Apply to picked">
102
+ <b class="side-title">{{ state.applyTitle }}</b>
103
+ <span class="px-subtle">Fill in what's the same for all of them. Each picture keeps anything you've typed for it.</span>
104
+ <div class="px-field">
105
+ <label class="px-label" for="batch-credit">Credit</label>
106
+ <input class="px-input" id="batch-credit" type="text" $model="state.credit" />
107
+ </div>
108
+ <div class="px-field">
109
+ <label class="px-label" for="batch-labels">Labels</label>
110
+ <input class="px-input" id="batch-labels" type="text" placeholder="Separated by commas" $model="state.labels" />
111
+ </div>
112
+ <div class="px-field">
113
+ <label class="px-label" for="batch-alt">Alt text starting point</label>
114
+ <input class="px-input" id="batch-alt" type="text" placeholder="For example: At the 2026 donor evening," $model="state.altStart" />
115
+ <span class="px-hint">Put at the start of the alt text of picked pictures that have none, for you to finish.</span>
116
+ </div>
117
+ <button class="px-btn px-btn-primary" type="button" $disabled="!state.canApply" @click="apply">{{ state.applyLabel }}</button>
118
+ <span class="px-hint" role="status">{{ state.applyNote }}</span>
119
+ </aside>
120
+ </div>
121
+ </div>
122
+ </view>
123
+
124
+ <logic lang="ts">
125
+ import { reactive, onMounted, onUnmounted, shared, defineRefs } from '@lightspeed-js/core'
126
+ import { getLibrary, thumbnailUrl, canWrite, CAPABILITIES, CHANGED, PATCHED, RUN, SENTENCE, UPLOAD, UPLOAD_TYPES, UPLOAD_LIMIT } from '../config.ts'
127
+
128
+ /**
129
+ * Adding pictures: drop them anywhere, then one screen to describe and label
130
+ * the batch while they upload.
131
+ *
132
+ * A picture is in the library the moment its upload finishes; this screen is
133
+ * where the batch gets its words, not a gate before it is added. A likely
134
+ * duplicate is a question on its row, and the rest carry on while it waits.
135
+ */
136
+ const refs = defineRefs()
137
+
138
+ const UPLOAD_GROUP_KEY = 'pseudolux:upload-group'
139
+ const EXTENSION = /\.([a-z0-9]+)$/i
140
+
141
+ const state = reactive({
142
+ open: false,
143
+ dragging: false,
144
+ dropLabel: '',
145
+ typesHint: '',
146
+ accept: 'image/*',
147
+ title: '',
148
+ progressText: '',
149
+ pct: 0,
150
+ barStyle: '',
151
+ counts: { ready: 0, active: 0, questions: 0, need: 0, failed: 0, needLabel: '' },
152
+ finished: false,
153
+ rows: [],
154
+ writeGroups: [],
155
+ manyGroups: false,
156
+ canConfirm: false,
157
+ held: false,
158
+ heldGroup: '',
159
+ heldAction: '',
160
+ credit: '',
161
+ labels: '',
162
+ altStart: '',
163
+ applyTitle: 'Apply to the picked pictures',
164
+ applyLabel: 'Apply',
165
+ canApply: false,
166
+ applyNote: '',
167
+ describeLabel: '',
168
+ })
169
+
170
+ const capabilities = shared(CAPABILITIES)
171
+ const changed = shared(CHANGED)
172
+ const patched = shared(PATCHED)
173
+ const run = shared(RUN)
174
+ const sentence = shared(SENTENCE)
175
+ const upload = shared(UPLOAD)
176
+
177
+ const plural = (n, one, many) => n + ' ' + (n === 1 ? one : many)
178
+
179
+ let canUpload = false
180
+ let uploadTypes = UPLOAD_TYPES
181
+ let uploadLimit = UPLOAD_LIMIT
182
+ let presets = []
183
+ let uploads = []
184
+ let nextKey = 0
185
+ let heldFiles = []
186
+ let opener = null
187
+ const files = new Map()
188
+
189
+ function megabytes(bytes) {
190
+ const mb = bytes / (1024 * 1024)
191
+ if (mb < 1) return Math.max(1, Math.round(bytes / 1024)) + ' KB'
192
+ return (mb >= 10 ? Math.round(mb) : Math.round(mb * 10) / 10) + ' MB'
193
+ }
194
+
195
+ function typeList(types) {
196
+ const names = types.map((one) => one.replace(/^image\//, '').replace('jpeg', 'jpg').replace('svg+xml', 'svg').toUpperCase())
197
+ return names.length > 1 ? names.slice(0, -1).join(', ') + ' or ' + names[names.length - 1] : names[0]
198
+ }
199
+
200
+ capabilities.subscribe((value) => {
201
+ if (!value) return
202
+ const port = getLibrary()
203
+ canUpload = Boolean(value.upload) && typeof port.upload === 'function' && canWrite()
204
+ state.canConfirm = typeof port.confirmUpload === 'function'
205
+ state.writeGroups = value.writeGroups && value.writeGroups.length ? value.writeGroups : value.writeGroup ? [value.writeGroup] : []
206
+ state.manyGroups = state.writeGroups.length > 1
207
+ uploadTypes = value.uploadTypes && value.uploadTypes.length ? value.uploadTypes : UPLOAD_TYPES
208
+ uploadLimit = value.uploadLimit || UPLOAD_LIMIT
209
+ presets = value.presets || []
210
+ state.accept = uploadTypes.join(',')
211
+ state.typesHint = typeList(uploadTypes) + ' · up to ' + megabytes(uploadLimit) + ' each'
212
+ })
213
+
214
+ // --- the rows -------------------------------------------------------------------------
215
+
216
+ const ACTIVE = ['waiting', 'uploading', 'processing']
217
+ const ORDER = { question: 0, held: 1, waiting: 1, uploading: 1, processing: 1, failed: 2, done: 3, pending: 3, skipped: 4 }
218
+
219
+ function patchUpload(key, patch) {
220
+ uploads = uploads.map((one) => (one.key === key ? { ...one, ...patch } : one))
221
+ draw()
222
+ }
223
+
224
+ const find = (key) => uploads.find((one) => one.key === key)
225
+
226
+ function draw() {
227
+ const count = (...statuses) => uploads.filter((one) => statuses.includes(one.status)).length
228
+ const ready = count('done', 'pending')
229
+ const active = count(...ACTIVE)
230
+ const questions = count('question')
231
+ const failed = count('failed')
232
+ const need = uploads.filter((one) => one.status === 'done' && !one.alt.trim()).length
233
+ const settled = uploads.length - active - count('held')
234
+ state.counts = { ready, active, questions, failed, need, needLabel: need + (need === 1 ? ' needs words' : ' need words') }
235
+ state.finished = uploads.length > 0 && active === 0 && questions === 0 && !state.held
236
+ state.pct = uploads.length ? Math.round((settled / uploads.length) * 100) : 0
237
+ state.barStyle = 'width: ' + state.pct + '%'
238
+ const groups = [...new Set(uploads.map((one) => one.group).filter(Boolean))]
239
+ const into = groups.length === 1 ? ' to ' + groups[0] : ''
240
+ const wanted = uploads.length - failed - count('skipped')
241
+ state.title = state.finished ? 'Added ' + plural(ready, 'picture', 'pictures') + into : 'Adding ' + plural(wanted, 'picture', 'pictures') + into
242
+ state.progressText = state.held ? 'Choose where they go' : state.finished ? 'All uploaded' : settled + ' of ' + uploads.length + ' uploaded'
243
+ state.describeLabel = 'Describe the ' + need + ' without words one by one'
244
+
245
+ const pickedCount = uploads.filter((one) => one.picked).length
246
+ state.applyTitle = pickedCount ? 'Apply to ' + pickedCount + ' picked' : 'Apply to the picked pictures'
247
+ state.applyLabel = pickedCount ? 'Apply to ' + plural(pickedCount, 'picture', 'pictures') : 'Apply'
248
+ state.canApply = pickedCount > 0
249
+
250
+ state.rows = uploads
251
+ .slice()
252
+ .sort((a, b) => ORDER[a.status] - ORDER[b.status] || a.key - b.key)
253
+ .map((one) => ({
254
+ ...one,
255
+ question: one.status === 'question',
256
+ active: ACTIVE.includes(one.status),
257
+ failed: one.status === 'failed',
258
+ skipped: one.status === 'skipped',
259
+ editable: !['failed', 'skipped', 'question'].includes(one.status),
260
+ pickable: !['failed', 'skipped'].includes(one.status),
261
+ barStyle: 'width: ' + one.pct + '%',
262
+ pctLabel: one.status === 'waiting' ? 'Waiting' : one.status === 'processing' ? 'Processing…' : one.pct + '%',
263
+ meta: [one.credit ? 'Credit: ' + one.credit : '', ...one.labels].filter(Boolean),
264
+ }))
265
+ }
266
+
267
+ /** Why a file will not be taken, as a sentence and what to do about it. */
268
+ function refusal(file) {
269
+ if (!uploadTypes.includes(file.type)) {
270
+ const ext = (file.name.match(EXTENSION) || [])[1]
271
+ return {
272
+ message: ext ? 'is a ' + ext.toUpperCase() + " file, which the library can't take." : "isn't a picture the library can take.",
273
+ help: 'Save it as ' + typeList(uploadTypes) + ' and add it again.',
274
+ }
275
+ }
276
+ if (uploadLimit && file.size > uploadLimit) {
277
+ return {
278
+ message: 'is ' + megabytes(file.size) + ', more than the library takes in one go (' + megabytes(uploadLimit) + ').',
279
+ help: 'Export it smaller and add it again.',
280
+ }
281
+ }
282
+ return null
283
+ }
284
+
285
+ /** Its pixel size once the browser has read it, and whether that is too
286
+ * small for a shape the sites show it at. */
287
+ function measure(key, preview, bytes) {
288
+ const probe = new Image()
289
+ probe.onload = () => {
290
+ if (!probe.naturalWidth) return
291
+ const short = presets.filter((one) => one.minWidth && probe.naturalWidth < one.minWidth)
292
+ patchUpload(key, {
293
+ sizeLabel: probe.naturalWidth + ' × ' + probe.naturalHeight + ' · ' + bytes,
294
+ small: short.length ? 'Too small for ' + (short.length === presets.filter((one) => one.minWidth).length ? 'every shape' : short.map((one) => one.label.toLowerCase()).join(', ')) : '',
295
+ smallTitle: short.length ? short.map((one) => one.label + ' is shown up to ' + one.minWidth + ' px wide').join('; ') + '. This is ' + probe.naturalWidth + ' px.' : '',
296
+ })
297
+ }
298
+ probe.src = preview
299
+ }
300
+
301
+ function queueFile(file, group, status) {
302
+ const key = ++nextKey
303
+ files.set(key, file)
304
+ const entry = {
305
+ key,
306
+ group: group || '',
307
+ name: file.name,
308
+ preview: URL.createObjectURL(file),
309
+ sizeLabel: megabytes(file.size),
310
+ status,
311
+ pct: 0,
312
+ id: '',
313
+ alt: '',
314
+ savedAlt: '',
315
+ credit: '',
316
+ labels: [],
317
+ owed: null,
318
+ picked: true,
319
+ small: '',
320
+ smallTitle: '',
321
+ note: '',
322
+ noteFailed: false,
323
+ message: '',
324
+ help: '',
325
+ retryable: false,
326
+ exact: false,
327
+ matchId: '',
328
+ matchName: '',
329
+ matchMeta: '',
330
+ matchThumb: '',
331
+ token: '',
332
+ }
333
+ const refused = refusal(file)
334
+ if (refused) Object.assign(entry, { status: 'failed', picked: false, ...refused })
335
+ uploads = uploads.concat([entry])
336
+ if (!refused) measure(key, entry.preview, entry.sizeLabel)
337
+ return entry
338
+ }
339
+
340
+ // --- sending ----------------------------------------------------------------------------
341
+
342
+ // One at a time. The store converts and hashes each picture as it arrives,
343
+ // and several large files at once would race each other for the same
344
+ // minutes; a queue finishes sooner and reports in order.
345
+ let sending = Promise.resolve()
346
+
347
+ function send(key) {
348
+ const port = getLibrary()
349
+ sending = sending.then(async () => {
350
+ const entry = find(key)
351
+ const file = files.get(key)
352
+ if (!entry || !file || entry.status !== 'waiting') return
353
+ patchUpload(key, { status: 'uploading', pct: 0 })
354
+ try {
355
+ const outcome = await port.upload(file, {
356
+ ...(entry.group ? { group: entry.group } : {}),
357
+ onProgress: (fraction) => {
358
+ const pct = Math.round(fraction * 100)
359
+ patchUpload(key, { pct, status: pct < 100 ? 'uploading' : 'processing' })
360
+ },
361
+ })
362
+ settle(key, outcome)
363
+ } catch (err) {
364
+ patchUpload(key, {
365
+ status: 'failed',
366
+ picked: false,
367
+ message: err && err.message ? "didn't upload: " + err.message + '.' : "didn't reach the library.",
368
+ help: 'Try again, or come back to it later.',
369
+ retryable: true,
370
+ })
371
+ }
372
+ })
373
+ }
374
+
375
+ function settle(key, outcome) {
376
+ if (outcome && outcome.token) {
377
+ const exact = Boolean(outcome.duplicateOf && outcome.duplicateOf.length)
378
+ const match = exact ? outcome.duplicateOf[0] : outcome.similar && outcome.similar[0] && outcome.similar[0].id
379
+ patchUpload(key, {
380
+ status: 'question',
381
+ pct: 100,
382
+ exact,
383
+ token: outcome.token,
384
+ matchId: match || '',
385
+ matchName: match || 'a picture',
386
+ matchThumb: match ? thumbnailUrl(match) : '',
387
+ })
388
+ if (match) describeMatch(key, match)
389
+ return
390
+ }
391
+ if (outcome && outcome.pending) {
392
+ patchUpload(key, { status: 'pending', pct: 100, note: 'Still processing; it will appear in the library shortly.' })
393
+ setTimeout(() => (changed.value = (changed.value || 0) + 1), 20000)
394
+ return
395
+ }
396
+ patchUpload(key, { status: 'done', pct: 100, id: outcome.id, token: '' })
397
+ changed.value = (changed.value || 0) + 1
398
+ settleWords(key)
399
+ }
400
+
401
+ /** Words typed, or details applied, while the picture was still uploading. */
402
+ async function settleWords(key) {
403
+ const entry = find(key)
404
+ if (!entry || !entry.id) return
405
+ if (entry.owed) {
406
+ const owed = entry.owed
407
+ patchUpload(key, { owed: null })
408
+ await describe(key, owed)
409
+ }
410
+ if (find(key) && find(key).alt.trim() !== find(key).savedAlt) saveAlt(find(key))
411
+ }
412
+
413
+ async function describeMatch(key, id) {
414
+ const port = getLibrary()
415
+ try {
416
+ const [detail, usage] = await Promise.all([
417
+ port.detail(id),
418
+ typeof port.usage === 'function' ? port.usage(id).catch(() => null) : Promise.resolve(null),
419
+ ])
420
+ const pages = usage ? new Set(usage.placements.map((one) => one.site + '|' + one.page)).size : -1
421
+ const parts = [(detail.tags || []).length ? 'in ' + detail.tags.join(', ') : '', pages > 0 ? 'used on ' + plural(pages, 'page', 'pages') : ''].filter(Boolean)
422
+ patchUpload(key, { matchName: detail.filename || id, matchMeta: parts.length ? ' (' + parts.join(' and ') + ')' : '' })
423
+ } catch {
424
+ // The question still stands with the identifier alone.
425
+ }
426
+ }
427
+
428
+ async function uploadAnyway(row) {
429
+ const port = getLibrary()
430
+ if (!row.token || typeof port.confirmUpload !== 'function') return
431
+ patchUpload(row.key, { status: 'processing', token: '' })
432
+ try {
433
+ settle(row.key, await port.confirmUpload(row.token))
434
+ } catch (err) {
435
+ patchUpload(row.key, {
436
+ status: 'failed',
437
+ picked: false,
438
+ message: err && err.message ? "didn't upload: " + err.message + '.' : "didn't reach the library.",
439
+ help: 'Add the file again to start over.',
440
+ retryable: false,
441
+ })
442
+ }
443
+ }
444
+
445
+ function skipUpload(row) {
446
+ patchUpload(row.key, { status: 'skipped', token: '', picked: false })
447
+ }
448
+
449
+ function retryUpload(row) {
450
+ patchUpload(row.key, { status: 'waiting', pct: 0, message: '', help: '', retryable: false, picked: true })
451
+ send(row.key)
452
+ }
453
+
454
+ function forget(one) {
455
+ if (one.preview) URL.revokeObjectURL(one.preview)
456
+ files.delete(one.key)
457
+ }
458
+
459
+ function dismiss(row) {
460
+ const entry = find(row.key)
461
+ if (entry) forget(entry)
462
+ uploads = uploads.filter((one) => one.key !== row.key)
463
+ if (!uploads.length) return close()
464
+ draw()
465
+ }
466
+
467
+ // --- taking files in -------------------------------------------------------------------
468
+
469
+ /** The group in the sentence if it can be uploaded to, else the last one
470
+ * chosen, else this side's own. */
471
+ function likelyGroup() {
472
+ const groups = state.writeGroups
473
+ const browsing = sentence.value && sentence.value.group
474
+ if (groups.includes(browsing)) return browsing
475
+ let last = ''
476
+ try {
477
+ last = localStorage.getItem(UPLOAD_GROUP_KEY) || ''
478
+ } catch {}
479
+ return groups.includes(last) ? last : groups[0] || ''
480
+ }
481
+
482
+ function take(list) {
483
+ if (!canUpload || !list.length) return
484
+ if (!state.open) {
485
+ opener = document.activeElement
486
+ state.open = true
487
+ document.documentElement.style.overflow = 'hidden'
488
+ requestAnimationFrame(() => refs.close && refs.close.focus())
489
+ }
490
+ if (state.manyGroups) {
491
+ if (!state.held) state.heldGroup = likelyGroup()
492
+ heldFiles = heldFiles.concat(list.map((file) => queueFile(file, '', 'held').key))
493
+ state.held = true
494
+ state.heldAction = 'Upload ' + plural(heldFiles.filter((key) => find(key) && find(key).status === 'held').length, 'picture', 'pictures')
495
+ draw()
496
+ return
497
+ }
498
+ for (const file of list) {
499
+ const entry = queueFile(file, state.writeGroups[0] || '', 'waiting')
500
+ if (entry.status === 'waiting') send(entry.key)
501
+ }
502
+ draw()
503
+ }
504
+
505
+ function sendHeld() {
506
+ const group = state.heldGroup
507
+ if (!state.writeGroups.includes(group)) return
508
+ try {
509
+ localStorage.setItem(UPLOAD_GROUP_KEY, group)
510
+ } catch {}
511
+ const keys = heldFiles
512
+ heldFiles = []
513
+ state.held = false
514
+ for (const key of keys) {
515
+ const entry = find(key)
516
+ if (!entry || entry.status !== 'held') continue
517
+ patchUpload(key, { status: 'waiting', group })
518
+ send(key)
519
+ }
520
+ draw()
521
+ }
522
+
523
+ function chooseFiles() {
524
+ if (canUpload && refs.fileInput) refs.fileInput.click()
525
+ }
526
+
527
+ function filesChosen(event) {
528
+ const input = event && event.target
529
+ if (!input || !input.files) return
530
+ take(Array.from(input.files))
531
+ input.value = ''
532
+ }
533
+
534
+ const carriesFiles = (event) => event.dataTransfer && Array.from(event.dataTransfer.types || []).includes('Files')
535
+
536
+ function onDragOver(event) {
537
+ if (!canUpload || !carriesFiles(event)) return
538
+ event.preventDefault()
539
+ const n = event.dataTransfer.items ? event.dataTransfer.items.length : 0
540
+ const what = n ? plural(n, 'picture', 'pictures') : 'pictures'
541
+ const one = state.manyGroups ? likelyGroup() : state.writeGroups[0]
542
+ state.dropLabel = state.manyGroups
543
+ ? 'Drop ' + what + ' to add ' + (n === 1 ? 'it' : 'them') + ', then choose the group'
544
+ : one
545
+ ? 'Drop ' + what + ' to add ' + (n === 1 ? 'it' : 'them') + ' to ' + one
546
+ : 'Drop ' + what + ' to add ' + (n === 1 ? 'it' : 'them')
547
+ state.dragging = true
548
+ }
549
+
550
+ function onDragLeave(event) {
551
+ if (event.relatedTarget && document.body.contains(event.relatedTarget)) return
552
+ state.dragging = false
553
+ }
554
+
555
+ function onDrop(event) {
556
+ state.dragging = false
557
+ if (!canUpload || !event.dataTransfer || !event.dataTransfer.files || !event.dataTransfer.files.length) return
558
+ event.preventDefault()
559
+ // Everything dropped gets a row, pictures or not: a file that is silently
560
+ // left out is a file somebody thinks is in the library.
561
+ take(Array.from(event.dataTransfer.files))
562
+ }
563
+
564
+ function onPaste(event) {
565
+ if (!canUpload || !event.clipboardData) return
566
+ const target = event.target
567
+ if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return
568
+ const pasted = Array.from(event.clipboardData.files || [])
569
+ if (pasted.length) take(pasted)
570
+ }
571
+
572
+ // --- words for each, and for all picked ---------------------------------------------
573
+
574
+ function togglePick(row) {
575
+ patchUpload(row.key, { picked: !row.picked })
576
+ }
577
+
578
+ function pick(which) {
579
+ uploads = uploads.map((one) => {
580
+ const pickable = !['failed', 'skipped'].includes(one.status)
581
+ return { ...one, picked: pickable && (which === 'all' || (which === 'need' && !one.alt.trim())) }
582
+ })
583
+ draw()
584
+ }
585
+
586
+ function onAlt(event, row) {
587
+ // Kept without a redraw: redrawing the list on each key would fight the typing.
588
+ const entry = find(row.key)
589
+ if (entry) entry.alt = event.target.value
590
+ }
591
+
592
+ async function saveAlt(row) {
593
+ const entry = find(row.key)
594
+ if (!entry || !entry.id) {
595
+ draw()
596
+ return
597
+ }
598
+ const value = entry.alt.trim()
599
+ if (value === entry.savedAlt) return
600
+ patchUpload(entry.key, { note: 'Saving…', noteFailed: false })
601
+ try {
602
+ await getLibrary().describe(entry.id, { altText: value || null })
603
+ patchUpload(entry.key, { savedAlt: value, note: 'Saved' })
604
+ patched.value = { id: entry.id, patch: { altText: value || undefined } }
605
+ } catch (err) {
606
+ patchUpload(entry.key, { note: "Couldn't save: " + (err && err.message ? err.message : 'no answer from the library') + '. Your words are still in the box.', noteFailed: true })
607
+ }
608
+ }
609
+
610
+ /** Tab to the next picture's alt text, not the next button: the list is for
611
+ * going down a column of descriptions. */
612
+ function altKey(event) {
613
+ if (event.key !== 'Tab' || !refs.root) return
614
+ const boxes = Array.from(refs.root.querySelectorAll('textarea.alt'))
615
+ const next = boxes[boxes.indexOf(event.target) + (event.shiftKey ? -1 : 1)]
616
+ if (!next) return
617
+ event.preventDefault()
618
+ next.focus()
619
+ }
620
+
621
+ async function describe(key, details) {
622
+ const entry = find(key)
623
+ if (!entry || !entry.id) return false
624
+ try {
625
+ await getLibrary().describe(entry.id, {
626
+ ...(details.credit ? { credit: details.credit } : {}),
627
+ ...(details.labels.length ? { labels: details.labels.map((term) => ({ term })) } : {}),
628
+ })
629
+ patched.value = {
630
+ id: entry.id,
631
+ patch: { ...(details.credit ? { credit: details.credit } : {}), ...(details.labels.length ? { labels: details.labels.map((term) => ({ term })) } : {}) },
632
+ }
633
+ return true
634
+ } catch (err) {
635
+ patchUpload(key, { note: "Couldn't apply: " + (err && err.message ? err.message : 'no answer from the library'), noteFailed: true })
636
+ return false
637
+ }
638
+ }
639
+
640
+ async function apply() {
641
+ const credit = state.credit.trim()
642
+ const terms = [...new Set(state.labels.split(',').map((one) => one.trim().toLowerCase().replace(/\s+/g, ' ')).filter(Boolean))]
643
+ const start = state.altStart.trim()
644
+ const targets = uploads.filter((one) => one.picked)
645
+ if (!targets.length || !(credit || terms.length || start)) {
646
+ state.applyNote = targets.length ? 'Nothing to apply yet: fill in a credit, labels or a starting point.' : ''
647
+ return
648
+ }
649
+ let applied = 0
650
+ for (const target of targets) {
651
+ const labels = [...new Set(target.labels.concat(terms))]
652
+ const details = { credit: credit || target.credit, labels }
653
+ const alt = start && !target.alt.trim() ? start + ' ' : target.alt
654
+ patchUpload(target.key, { credit: details.credit, labels, alt, ...(target.id ? {} : { owed: details }) })
655
+ if (alt !== target.alt) {
656
+ const box = refs.root && refs.root.querySelector('textarea.alt[data-key="' + target.key + '"]')
657
+ if (box) box.value = alt
658
+ }
659
+ if (target.id) {
660
+ if (await describe(target.key, details)) applied++
661
+ if (alt !== target.alt) saveAlt(find(target.key))
662
+ } else applied++
663
+ }
664
+ state.applyNote = 'Applied to ' + plural(applied, 'picture', 'pictures') + '.'
665
+ }
666
+
667
+ function describeRest() {
668
+ const need = uploads.filter((one) => one.status === 'done' && one.id && !one.alt.trim())
669
+ if (!need.length) return
670
+ const items = need.map((one) => ({ id: one.id, label: one.name, filename: one.name, altText: '', altView: '', tags: one.group ? [one.group] : [], labels: one.labels.map((term) => ({ term })) }))
671
+ close()
672
+ run.value = { items }
673
+ }
674
+
675
+ // --- the screen ---------------------------------------------------------------------------
676
+
677
+ function close() {
678
+ // Uploads still going carry on; the screen comes back with the next file,
679
+ // or from the Upload button.
680
+ state.open = false
681
+ document.documentElement.style.overflow = ''
682
+ if (state.finished) {
683
+ uploads.forEach(forget)
684
+ uploads = []
685
+ state.rows = []
686
+ state.credit = ''
687
+ state.labels = ''
688
+ state.altStart = ''
689
+ state.applyNote = ''
690
+ }
691
+ if (opener && document.contains(opener) && opener.focus) opener.focus()
692
+ opener = null
693
+ }
694
+
695
+ function onKey(event) {
696
+ if (event.key !== 'Escape') return
697
+ event.preventDefault()
698
+ close()
699
+ }
700
+
701
+ let lastAsk = upload.value
702
+ upload.subscribe((value) => {
703
+ if (value === lastAsk) return
704
+ lastAsk = value
705
+ // With a batch in hand, the button brings its screen back; otherwise it
706
+ // opens the file chooser.
707
+ if (uploads.length && !state.open) {
708
+ opener = document.activeElement
709
+ state.open = true
710
+ document.documentElement.style.overflow = 'hidden'
711
+ } else chooseFiles()
712
+ })
713
+
714
+ function onShortcut(event) {
715
+ const target = event.target
716
+ const typing = target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT' || target.isContentEditable)
717
+ if (typing || event.metaKey || event.ctrlKey || event.altKey || state.open) return
718
+ if ((event.key === 'u' || event.key === 'U') && canUpload && !document.querySelector('[aria-modal="true"]:not([hidden])')?.offsetParent) {
719
+ event.preventDefault()
720
+ chooseFiles()
721
+ }
722
+ }
723
+
724
+ // A file the browser cannot draw (a TIFF, say) still uploads fine; its
725
+ // thumbnail is left blank rather than broken. `error` does not bubble.
726
+ function previewFailed(event) {
727
+ const target = event.target
728
+ if (target && target.closest && target.closest('.up-th, .up-q')) target.style.visibility = 'hidden'
729
+ }
730
+
731
+ onMounted(() => {
732
+ document.addEventListener('error', previewFailed, true)
733
+ document.addEventListener('dragover', onDragOver)
734
+ document.addEventListener('dragleave', onDragLeave)
735
+ document.addEventListener('drop', onDrop)
736
+ document.addEventListener('paste', onPaste)
737
+ document.addEventListener('keydown', onShortcut)
738
+ })
739
+
740
+ onUnmounted(() => {
741
+ document.removeEventListener('error', previewFailed, true)
742
+ document.removeEventListener('dragover', onDragOver)
743
+ document.removeEventListener('dragleave', onDragLeave)
744
+ document.removeEventListener('drop', onDrop)
745
+ document.removeEventListener('paste', onPaste)
746
+ document.removeEventListener('keydown', onShortcut)
747
+ uploads.forEach(forget)
748
+ if (state.open) document.documentElement.style.overflow = ''
749
+ })
750
+ </logic>
751
+
752
+ <style>
753
+ .file-input {
754
+ position: absolute;
755
+ width: 1px;
756
+ height: 1px;
757
+ opacity: 0;
758
+ pointer-events: none;
759
+ }
760
+
761
+ .up-drop {
762
+ position: fixed;
763
+ inset: 14px;
764
+ z-index: 60;
765
+ border: 3px dashed var(--px-accent);
766
+ border-radius: 20px;
767
+ background: color-mix(in srgb, var(--px-accent-soft) 92%, transparent);
768
+ color: var(--px-text);
769
+ display: flex;
770
+ flex-direction: column;
771
+ align-items: center;
772
+ justify-content: center;
773
+ gap: 12px;
774
+ padding: 24px;
775
+ text-align: center;
776
+ pointer-events: none;
777
+ }
778
+
779
+ .up-drop h2 {
780
+ font-size: clamp(22px, 2.4vw, 30px);
781
+ letter-spacing: -.02em;
782
+ }
783
+
784
+ .up-b {
785
+ position: fixed;
786
+ inset: 0;
787
+ z-index: 42;
788
+ display: grid;
789
+ grid-template-columns: minmax(0, 1fr) 380px;
790
+ background: var(--px-bg);
791
+ color: var(--px-text);
792
+ }
793
+
794
+ .up-main {
795
+ display: flex;
796
+ flex-direction: column;
797
+ min-width: 0;
798
+ min-height: 0;
799
+ }
800
+
801
+ .up-head {
802
+ padding: 18px 28px 12px;
803
+ display: flex;
804
+ flex-direction: column;
805
+ gap: 10px;
806
+ border-bottom: 1px solid var(--px-border);
807
+ background: var(--px-surface);
808
+ }
809
+
810
+ .head-row {
811
+ gap: 10px;
812
+ align-items: baseline;
813
+ }
814
+
815
+ .head-row h2 {
816
+ font-size: var(--px-fs-h);
817
+ }
818
+
819
+ .close {
820
+ margin-left: auto;
821
+ }
822
+
823
+ .hold {
824
+ display: flex;
825
+ align-items: center;
826
+ flex-wrap: wrap;
827
+ gap: 10px 14px;
828
+ padding: 10px 12px;
829
+ border: 1px solid var(--px-accent);
830
+ border-radius: var(--px-r-l);
831
+ background: var(--px-accent-soft);
832
+ }
833
+
834
+ .hold-into {
835
+ display: flex;
836
+ align-items: center;
837
+ gap: 8px;
838
+ font-weight: 600;
839
+ }
840
+
841
+ .hold .px-btn {
842
+ margin-left: auto;
843
+ }
844
+
845
+ .up-prog {
846
+ height: 6px;
847
+ border-radius: 3px;
848
+ background: var(--px-surface-2);
849
+ overflow: hidden;
850
+ }
851
+
852
+ .up-prog span {
853
+ display: block;
854
+ height: 100%;
855
+ background: var(--px-accent);
856
+ transition: width .2s;
857
+ }
858
+
859
+ .badges {
860
+ gap: 6px;
861
+ flex-wrap: wrap;
862
+ min-height: 22px;
863
+ }
864
+
865
+ .up-tools {
866
+ display: flex;
867
+ gap: 6px;
868
+ align-items: center;
869
+ flex-wrap: wrap;
870
+ font-size: var(--px-fs-s);
871
+ }
872
+
873
+ .tab-note {
874
+ margin-left: auto;
875
+ }
876
+
877
+ .up-list {
878
+ flex: 1;
879
+ min-height: 0;
880
+ overflow: auto;
881
+ padding: 6px 28px 24px;
882
+ }
883
+
884
+ .up-r {
885
+ display: grid;
886
+ grid-template-columns: 28px 120px minmax(0, 1fr);
887
+ gap: 14px;
888
+ padding: 12px 0;
889
+ border-bottom: 1px solid var(--px-border);
890
+ align-items: start;
891
+ }
892
+
893
+ .up-r.is-on {
894
+ background: linear-gradient(90deg, var(--px-accent-soft), transparent 60%);
895
+ }
896
+
897
+ .tick {
898
+ width: 20px;
899
+ height: 20px;
900
+ margin: 30px 0 0 4px;
901
+ }
902
+
903
+ .up-th {
904
+ position: relative;
905
+ width: 120px;
906
+ height: 84px;
907
+ border-radius: var(--px-r-m);
908
+ overflow: hidden;
909
+ background: var(--px-surface-2);
910
+ }
911
+
912
+ .up-th img {
913
+ position: absolute;
914
+ inset: 0;
915
+ width: 100%;
916
+ height: 100%;
917
+ object-fit: cover;
918
+ }
919
+
920
+ .pg {
921
+ position: absolute;
922
+ inset: auto 6px 6px 6px;
923
+ height: 5px;
924
+ border-radius: 3px;
925
+ background: rgba(255, 255, 255, .35);
926
+ }
927
+
928
+ .pg span {
929
+ display: block;
930
+ height: 100%;
931
+ border-radius: 3px;
932
+ background: #fff;
933
+ }
934
+
935
+ .up-body {
936
+ display: flex;
937
+ flex-direction: column;
938
+ gap: 6px;
939
+ min-width: 0;
940
+ }
941
+
942
+ .name-row {
943
+ gap: 8px;
944
+ flex-wrap: wrap;
945
+ }
946
+
947
+ .row-name {
948
+ font-size: 14px;
949
+ overflow-wrap: anywhere;
950
+ }
951
+
952
+ .alt {
953
+ min-height: 44px;
954
+ }
955
+
956
+ .up-meta {
957
+ display: flex;
958
+ flex-wrap: wrap;
959
+ gap: 4px;
960
+ align-items: center;
961
+ }
962
+
963
+ .up-meta span {
964
+ font-size: 11.5px;
965
+ font-weight: 600;
966
+ padding: 2px 8px;
967
+ border-radius: 999px;
968
+ background: var(--px-surface-2);
969
+ color: var(--px-text-2);
970
+ }
971
+
972
+ .up-meta .plain {
973
+ background: transparent;
974
+ padding: 0;
975
+ font-weight: 500;
976
+ }
977
+
978
+ .up-q {
979
+ display: flex;
980
+ flex-wrap: wrap;
981
+ gap: 10px;
982
+ align-items: center;
983
+ padding: 8px 10px;
984
+ border-radius: 10px;
985
+ font-size: var(--px-fs-s);
986
+ background: var(--px-warn-soft);
987
+ border: 1px solid var(--px-warn);
988
+ }
989
+
990
+ .q-pic {
991
+ width: 48px;
992
+ height: 34px;
993
+ border-radius: 4px;
994
+ flex: 0 0 48px;
995
+ object-fit: cover;
996
+ }
997
+
998
+ .q-text {
999
+ flex: 1;
1000
+ min-width: 180px;
1001
+ }
1002
+
1003
+ .fail {
1004
+ margin: 0;
1005
+ font-size: var(--px-fs-s);
1006
+ }
1007
+
1008
+ .up-side {
1009
+ border-left: 1px solid var(--px-border);
1010
+ background: var(--px-surface);
1011
+ padding: 20px;
1012
+ display: flex;
1013
+ flex-direction: column;
1014
+ gap: 14px;
1015
+ overflow: auto;
1016
+ }
1017
+
1018
+ .side-title {
1019
+ font-size: 16px;
1020
+ }
1021
+
1022
+ .up-foot {
1023
+ display: flex;
1024
+ align-items: center;
1025
+ flex-wrap: wrap;
1026
+ gap: 10px;
1027
+ padding: 12px 28px;
1028
+ border-top: 1px solid var(--px-border);
1029
+ background: var(--px-surface);
1030
+ }
1031
+
1032
+ .foot-note {
1033
+ margin-left: auto;
1034
+ }
1035
+
1036
+ .text-danger {
1037
+ color: var(--px-danger);
1038
+ }
1039
+
1040
+ @media (max-width: 900px) {
1041
+ .up-b {
1042
+ display: flex;
1043
+ flex-direction: column;
1044
+ overflow: auto;
1045
+ }
1046
+
1047
+ .up-main {
1048
+ min-height: auto;
1049
+ }
1050
+
1051
+ .up-list {
1052
+ overflow: visible;
1053
+ padding: 6px 16px 16px;
1054
+ }
1055
+
1056
+ .up-head,
1057
+ .up-foot {
1058
+ padding-left: 16px;
1059
+ padding-right: 16px;
1060
+ }
1061
+
1062
+ .up-side {
1063
+ border-left: 0;
1064
+ border-top: 1px solid var(--px-border);
1065
+ overflow: visible;
1066
+ }
1067
+
1068
+ .up-r {
1069
+ grid-template-columns: 28px 84px minmax(0, 1fr);
1070
+ }
1071
+
1072
+ .up-th {
1073
+ width: 84px;
1074
+ height: 60px;
1075
+ }
1076
+ }
1077
+
1078
+ @media (prefers-reduced-motion: reduce) {
1079
+ .up-prog span {
1080
+ transition: none;
1081
+ }
1082
+ }
1083
+ </style>