@pseudolux-ui/media-library 0.0.0-stage → 0.1.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,1622 @@
1
+ <view>
2
+ <aside class="px-inspector inspector" aria-label="Selected picture" $ref="root" $show="state.open">
3
+ <div class="px-insp-head">
4
+ <div class="head-text">
5
+ <h3 class="title" $title="state.label">{{ state.label }}</h3>
6
+ <span class="px-mono px-subtle" $show="state.id">{{ state.id }}</span>
7
+ </div>
8
+ <button class="px-btn px-btn-ghost px-btn-sm px-btn-icon" type="button" @click="close" aria-label="Close">
9
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"></path></svg>
10
+ </button>
11
+ </div>
12
+
13
+ <div class="px-sec" $show="state.error">
14
+ <div class="px-callout px-callout-danger" role="alert"><span>{{ state.error }}</span></div>
15
+ </div>
16
+
17
+ <div class="px-sec" $show="state.ready && state.readOnly && !state.deletedAt">
18
+ <div class="px-callout">
19
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2"></rect><path d="M8 11V7a4 4 0 0 1 8 0v4"></path></svg>
20
+ <span $show="state.ownerGroups">You can see and use this picture. Only people who can change <b>{{ state.ownerGroups }}</b> can edit its words, crops and labels.</span>
21
+ <span $show="!state.ownerGroups">You can see and use this picture, but it can't be changed from here.</span>
22
+ </div>
23
+ </div>
24
+
25
+ <div class="px-sec" $show="state.id">
26
+ <div class="preview" $class="{ binned: state.deletedAt }">
27
+ <div class="preview-frame" $style="state.previewStyle">
28
+ <ResponsiveImage
29
+ $pid="state.id"
30
+ $alt="state.altText"
31
+ $standIn="state.standIn"
32
+ $aspectRatio="state.aspect"
33
+ width="100%"
34
+ fit="contain"
35
+ />
36
+ <div
37
+ class="focal-layer"
38
+ $ref="focalLayer"
39
+ $show="state.ready && !state.deletedAt"
40
+ $class="{ editable: state.canFocal, dragging: state.focalDragging }"
41
+ @pointerdown="grabFocal"
42
+ @pointermove="dragFocal"
43
+ @pointerup="dropFocal"
44
+ @pointercancel="dropFocal"
45
+ >
46
+ <span
47
+ class="px-focal focal"
48
+ $ref="focalMarker"
49
+ $class="{ 'is-default': !state.focalSet }"
50
+ $style="state.focalStyle"
51
+ $tabindex="state.focalTab"
52
+ $role="state.focalRole"
53
+ $aria-roledescription="state.focalRole ? 'focal point' : null"
54
+ $aria-label="state.focalAria"
55
+ $aria-hidden="state.focalRole ? null : 'true'"
56
+ @keydown="focalKeys"
57
+ ></span>
58
+ </div>
59
+ </div>
60
+ </div>
61
+
62
+ <div class="px-callout px-callout-warn" $show="state.deletedAt">
63
+ <span><b>In the bin since {{ state.deletedLabel }}.</b> {{ state.deletedDetail }} Pickers don't show it.</span>
64
+ </div>
65
+ <button class="px-btn px-btn-primary start" type="button" $show="state.deletedAt && !state.readOnly" $disabled="state.busy" @click="restore">
66
+ {{ state.restoreLabel }}
67
+ </button>
68
+
69
+ <p class="px-subtle" $show="state.ready && !state.deletedAt">{{ state.previewNote }}</p>
70
+ <div class="px-row" $show="state.ready && !state.deletedAt">
71
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" $show="state.canFocal && state.focalSet" @click="clearFocal">Use the default (centre)</button>
72
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" @click="copyImageUrl">Copy image URL</button>
73
+ <span class="px-subtle" role="status">{{ state.copyHint }}</span>
74
+ </div>
75
+ </div>
76
+
77
+ <section class="px-sec" aria-label="Words" $show="state.ready && !state.deletedAt">
78
+ <div class="px-sec-title">
79
+ <h4>Words</h4>
80
+ <span class="px-badge px-badge-neutral" $show="state.wordsMode === 'shared'">{{ state.sharedBadge }}</span>
81
+ </div>
82
+
83
+ <div class="px-seg start" role="radiogroup" aria-label="Which words" $show="state.canDescribeView" @keydown="wordsKey">
84
+ <button
85
+ type="button"
86
+ role="radio"
87
+ $aria-checked="state.wordsMode === 'shared'"
88
+ $tabindex="state.wordsMode === 'shared' ? 0 : -1"
89
+ data-words="shared"
90
+ @click="pickWords('shared')"
91
+ >Shared · all sites</button>
92
+ <button
93
+ type="button"
94
+ role="radio"
95
+ $aria-checked="state.wordsMode === 'local'"
96
+ $tabindex="state.wordsMode === 'local' ? 0 : -1"
97
+ data-words="local"
98
+ @click="pickWords('local')"
99
+ >This site only</button>
100
+ </div>
101
+
102
+ <div class="words" $show="state.wordsMode === 'shared'">
103
+ <label class="px-field">
104
+ <span class="px-label">Alt text</span>
105
+ <textarea
106
+ class="px-textarea"
107
+ rows="3"
108
+ $placeholder="state.readOnly ? 'No alt text yet' : 'What is in this picture?'"
109
+ $readonly="state.readOnly"
110
+ $model="state.altText"
111
+ ></textarea>
112
+ </label>
113
+ <label class="px-field">
114
+ <span class="px-label">Credit</span>
115
+ <input class="px-input" type="text" $placeholder="state.readOnly ? 'No credit yet' : 'Who to credit'" $readonly="state.readOnly" $model="state.credit" />
116
+ </label>
117
+ <div class="px-shared" $show="!state.readOnly">
118
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"></path></svg>
119
+ <span>Changes here show on every site that uses this picture.{{ state.sharedOthers }}</span>
120
+ </div>
121
+ </div>
122
+
123
+ <div class="words" $show="state.wordsMode === 'local'">
124
+ <label class="px-field">
125
+ <span class="px-label"><span>Alt text on {{ state.view }}</span></span>
126
+ <textarea
127
+ class="px-textarea"
128
+ rows="3"
129
+ $placeholder="state.altText || 'What is in this picture, here?'"
130
+ $model="state.viewAltText"
131
+ ></textarea>
132
+ </label>
133
+ <label class="px-field">
134
+ <span class="px-label"><span>Credit on {{ state.view }}</span></span>
135
+ <input class="px-input" type="text" $placeholder="state.credit || 'Who to credit, here'" $model="state.viewCredit" />
136
+ </label>
137
+ <div class="px-shared is-local">
138
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle><path d="M12 8v5M12 16h.01"></path></svg>
139
+ <span>{{ state.localNote }}</span>
140
+ </div>
141
+ <button class="px-btn px-btn-ghost px-btn-sm start" type="button" @click="useSharedWords">Use the shared words again</button>
142
+ </div>
143
+ </section>
144
+
145
+ <section class="px-sec" aria-label="Labels" $show="state.ready && !state.deletedAt">
146
+ <div class="px-sec-title"><h4>Labels</h4></div>
147
+ <div class="px-row chips">
148
+ <span
149
+ class="px-chip"
150
+ $for="one in state.labelChips"
151
+ $key="one.term"
152
+ $class="{ 'is-internal': one.internal, 'is-static': state.readOnly }"
153
+ $title="one.title"
154
+ >
155
+ {{ one.term }}
156
+ <button
157
+ type="button"
158
+ $show="!state.readOnly"
159
+ $aria-label="one.audienceLabel"
160
+ $aria-pressed="one.internal"
161
+ $title="one.audienceLabel"
162
+ @click="toggleAudience(one)"
163
+ ><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><rect x="5" y="11" width="14" height="10" rx="2"></rect><path d="M8 11V7a4 4 0 0 1 8 0v4"></path></svg></button>
164
+ <button type="button" $show="!state.readOnly" $aria-label="'Remove ' + one.term" @click="removeLabel(one)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"></path></svg></button>
165
+ </span>
166
+ <span class="px-subtle" $show="!state.labelChips.length">No labels yet.</span>
167
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" $show="!state.readOnly && !state.addingLabel" @click="startAddLabel">+ Add</button>
168
+ </div>
169
+ <div class="add-label" $show="state.addingLabel">
170
+ <label class="px-field grow">
171
+ <span class="px-label">New label</span>
172
+ <input
173
+ class="px-input"
174
+ $ref="labelInput"
175
+ type="text"
176
+ placeholder="A word somebody would search for"
177
+ $model="state.labelDraft"
178
+ @keydown="labelKey"
179
+ />
180
+ </label>
181
+ <label class="internal-check"><input type="checkbox" $model="state.labelInternal" /> Internal</label>
182
+ <button class="px-btn px-btn-secondary px-btn-sm" type="button" @click="addLabelDraft">Add</button>
183
+ </div>
184
+ <div class="suggested" $show="state.suggested.length">
185
+ <span class="px-subtle">Suggested · not applied until you accept</span>
186
+ <div class="px-row chips">
187
+ <span class="px-chip is-suggested" $for="one in state.suggested" $key="one.term" $title="one.title">
188
+ {{ one.term }}
189
+ <button type="button" $show="!state.readOnly" $aria-label="'Accept ' + one.term" @click="acceptLabel(one)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"></path></svg></button>
190
+ <button type="button" $show="!state.readOnly" $aria-label="'Reject ' + one.term" @click="rejectLabel(one)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"></path></svg></button>
191
+ </span>
192
+ </div>
193
+ </div>
194
+ <p class="px-hint" $show="state.hasInternal">Dashed outline: internal, only staff see it.</p>
195
+ </section>
196
+
197
+ <section class="px-sec" aria-label="Crops" $show="state.ready && !state.deletedAt && state.cropTiles.length">
198
+ <div class="px-sec-title">
199
+ <h4>Crops</h4>
200
+ <button class="px-btn px-btn-ghost px-btn-sm" type="button" $show="!state.readOnly" @click="startCustomCrop">Add a custom crop</button>
201
+ </div>
202
+ <div class="px-crops" role="list">
203
+ <div class="crop-item" role="listitem" $for="tile in state.cropTiles" $key="tile.name">
204
+ <button
205
+ class="px-crop"
206
+ type="button"
207
+ aria-haspopup="menu"
208
+ $data-crop="tile.name"
209
+ $class="{ 'is-current': tile.name === state.cropMenu }"
210
+ $aria-expanded="tile.name === state.cropMenu"
211
+ $aria-label="tile.aria"
212
+ @click="toggleCropMenu(tile)"
213
+ >
214
+ <span class="px-pic crop-cut" $style="tile.thumbStyle"></span>
215
+ <span class="px-crop-name">{{ tile.label }}</span>
216
+ <span class="crop-note" $show="!tile.adjusted">{{ tile.note }}</span>
217
+ <span class="px-badge px-badge-accent adjusted" $show="tile.adjusted">
218
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><path d="M4 20h4L19 9l-4-4L4 16z"></path></svg>{{ tile.note }}
219
+ </span>
220
+ </button>
221
+ </div>
222
+ </div>
223
+ <div class="px-dialog crop-menu" role="menu" $ref="cropMenu" $aria-label="state.cropMenuLabel" $show="state.cropMenu" @keydown="cropMenuKey">
224
+ <button class="px-btn px-btn-ghost menu-item" type="button" role="menuitem" $show="!state.readOnly" @click="editFromMenu">Edit crop</button>
225
+ <button class="px-btn px-btn-ghost menu-item two-line" type="button" role="menuitem" $show="!state.readOnly && state.cropMenuStored" $disabled="state.cropBusy" @click="resetFromMenu">
226
+ <span>{{ state.cropMenuResetLabel }}</span>
227
+ <span class="px-subtle">{{ state.cropMenuResetHint }}</span>
228
+ </button>
229
+ <button class="px-btn px-btn-ghost menu-item" type="button" role="menuitem" @click="copyFromMenu">Copy URL</button>
230
+ </div>
231
+ <p class="px-subtle">{{ state.cropNote }}</p>
232
+ </section>
233
+
234
+ <section class="px-sec" aria-label="Colours" $show="state.ready && !state.deletedAt">
235
+ <div class="px-sec-title"><h4>Colours</h4></div>
236
+ <div class="px-swatches" role="list" aria-label="Colours from the picture" $show="state.hasPalette">
237
+ <button
238
+ class="swatch"
239
+ type="button"
240
+ role="listitem"
241
+ $for="one in state.palette"
242
+ $key="one.hex"
243
+ $style="one.style"
244
+ $title="one.title"
245
+ $aria-label="'Copy ' + one.title"
246
+ @click="copy(one)"
247
+ ></button>
248
+ </div>
249
+ <p class="px-subtle" role="status" $show="state.hasPalette">{{ state.paletteHint }}</p>
250
+ <div class="px-swatches" aria-busy="true" $show="!state.hasPalette && state.enriching">
251
+ <span class="px-skel"></span><span class="px-skel"></span><span class="px-skel"></span><span class="px-skel"></span><span class="px-skel"></span>
252
+ </div>
253
+ <p class="px-subtle" role="status" $show="!state.hasPalette">{{ state.noPaletteHint }}</p>
254
+ <button class="px-btn px-btn-secondary px-btn-sm start" type="button" $show="!state.hasPalette && state.canEnrich && !state.enriching" @click="enrich">
255
+ Work out colours
256
+ </button>
257
+ </section>
258
+
259
+ <section class="px-sec" aria-label="Groups" $show="state.ready && state.groups.length">
260
+ <div class="px-sec-title"><h4>Groups</h4></div>
261
+ <div class="px-row groups">
262
+ <span
263
+ class="px-badge group"
264
+ $for="one in state.groups"
265
+ $key="one.name"
266
+ $class="{ 'px-badge-accent': one.canChange, 'px-badge-neutral': !one.canChange }"
267
+ >{{ one.label }}</span>
268
+ </div>
269
+ </section>
270
+
271
+ <section class="px-sec" aria-label="Used in" $show="state.ready && state.usageKnown">
272
+ <div class="px-sec-title"><h4>Used in</h4><span class="px-subtle">{{ state.usageSummary }}</span></div>
273
+ <p class="px-subtle" $show="state.usageLoading">Looking…</p>
274
+ <p class="px-subtle" $show="!state.usageLoading && !state.sites.length">No page has reported using this picture.</p>
275
+ <ul class="used-in" $show="state.sites.length">
276
+ <li $for="site in state.sites" $key="site.name">
277
+ <b>{{ site.name }}</b> ·
278
+ <span class="page" $for="page in site.pages" $key="page.key" $title="page.meta"><a $href="page.url" target="_blank" rel="noopener" $show="page.url">{{ page.title }}</a><span $show="!page.url">{{ page.title }}</span><span class="px-subtle" $show="page.draft"> (draft)</span><span $show="page.sep">, </span></span>
279
+ </li>
280
+ </ul>
281
+
282
+ <span class="px-eyebrow seen-title">Seen from</span>
283
+ <p class="px-subtle" $show="!state.usageLoading && state.seen.length === 0">Not requested from anywhere in the last 30 days.</p>
284
+ <ul class="used-in" $show="state.seen.length">
285
+ <li $for="one in state.seen" $key="one.origin">
286
+ <span>{{ one.label }}</span> <span class="px-subtle">· {{ one.meta }}</span>
287
+ </li>
288
+ </ul>
289
+ <p class="px-subtle" $show="state.copies.length">{{ state.copiesLabel }}</p>
290
+ </section>
291
+
292
+ <div class="px-sec bin-row" $show="state.ready && !state.readOnly && !state.deletedAt">
293
+ <button class="px-btn px-btn-danger-quiet px-btn-sm" type="button" @click="askToDelete">Move to bin…</button>
294
+ </div>
295
+
296
+ <div class="foot" $show="state.ready && !state.readOnly && !state.deletedAt">
297
+ <span class="px-subtle" role="status">{{ state.saveStatus }}</span>
298
+ <button class="px-btn px-btn-primary" type="button" $disabled="state.saving" @click="save">{{ state.saveLabel }}</button>
299
+ </div>
300
+
301
+ <CropEditor />
302
+ <BinDialog />
303
+ </aside>
304
+ </view>
305
+
306
+ <logic lang="ts">
307
+ import { reactive, onMounted, defineRefs } from '@lightspeed-js/core'
308
+ import { shared } from '@lightspeed-js/core'
309
+ import {
310
+ getLibrary,
311
+ canWrite,
312
+ cannotChange,
313
+ canDescribeView,
314
+ previewUrl,
315
+ SELECTED,
316
+ CHANGED,
317
+ VIEW,
318
+ PRESETS,
319
+ CROP_EDITOR,
320
+ BIN_DIALOG,
321
+ } from '../config.ts'
322
+ import { presetRect, cropRect } from '@pseudolux-ui/client'
323
+
324
+ /**
325
+ * One asset, up close.
326
+ *
327
+ * Reads the selection from a cell rather than a prop, so it does not need to
328
+ * be a child of the grid - which is what lets a picker arrange the two
329
+ * differently without either knowing.
330
+ */
331
+ const state = reactive({
332
+ open: false,
333
+ ready: false,
334
+ id: '',
335
+ label: '',
336
+ aspect: 0,
337
+ previewStyle: '',
338
+ previewNote: '',
339
+ standIn: 'var(--px-surface-2)',
340
+ altText: '',
341
+ credit: '',
342
+ labels: [],
343
+ labelChips: [],
344
+ suggested: [],
345
+ hasInternal: false,
346
+ addingLabel: false,
347
+ labelDraft: '',
348
+ labelInternal: false,
349
+ focalSet: false,
350
+ focalX: 50,
351
+ focalY: 50,
352
+ focalStyle: '',
353
+ focalAria: null,
354
+ focalRole: null,
355
+ focalTab: null,
356
+ focalDragging: false,
357
+ canFocal: false,
358
+ sourceWidth: 0,
359
+ sourceHeight: 0,
360
+ format: '',
361
+ createdLabel: '',
362
+ cropTiles: [],
363
+ cropMenu: '',
364
+ cropMenuLabel: '',
365
+ cropMenuStored: false,
366
+ cropMenuResetLabel: '',
367
+ cropMenuResetHint: '',
368
+ cropNote: '',
369
+ cropBusy: false,
370
+ copyHint: '',
371
+ usageKnown: false,
372
+ usageLoading: false,
373
+ usageSummary: '',
374
+ sites: [],
375
+ seen: [],
376
+ copies: [],
377
+ copiesLabel: '',
378
+ view: '',
379
+ canDescribeView: false,
380
+ wordsMode: 'shared',
381
+ sharedBadge: 'Shared',
382
+ sharedOthers: '',
383
+ localNote: '',
384
+ viewAltText: '',
385
+ viewCredit: '',
386
+ groups: [],
387
+ ownerGroups: '',
388
+ palette: [],
389
+ hasPalette: false,
390
+ paletteHint: '',
391
+ noPaletteHint: '',
392
+ canEnrich: false,
393
+ enriching: false,
394
+ saving: false,
395
+ saveStatus: '',
396
+ saveLabel: 'Save',
397
+ readOnly: false,
398
+ error: '',
399
+ deletedAt: '',
400
+ deletedLabel: '',
401
+ deletedDetail: '',
402
+ busy: false,
403
+ restoreLabel: 'Restore',
404
+ })
405
+
406
+ const selected = shared(SELECTED)
407
+ const changed = shared(CHANGED)
408
+ const view = shared(VIEW)
409
+ const presets = shared(PRESETS)
410
+ const cropEditor = shared(CROP_EDITOR)
411
+ const binDialog = shared(BIN_DIALOG)
412
+ const refs = defineRefs()
413
+
414
+ // The row as last seen, so a change of view can re-read its overrides.
415
+ let current = null
416
+
417
+ function presetsNow() {
418
+ return presets.value || []
419
+ }
420
+
421
+ function plural(n, one, many) {
422
+ return n + ' ' + (n === 1 ? one : many)
423
+ }
424
+
425
+ function pct(value) {
426
+ return Math.round(value * 1000) / 1000
427
+ }
428
+
429
+ function shortDate(iso) {
430
+ if (!iso) return ''
431
+ const date = new Date(iso)
432
+ if (Number.isNaN(date.getTime())) return iso.slice(0, 10)
433
+ const sameYear = date.getFullYear() === new Date().getFullYear()
434
+ return date.toLocaleDateString('en-AU', { day: 'numeric', month: 'short', ...(sameYear ? {} : { year: 'numeric' }) })
435
+ }
436
+
437
+ /** What the picture offers the crop helpers: its size, point and crops. */
438
+ function croppable() {
439
+ return {
440
+ dimensions: { width: state.sourceWidth, height: state.sourceHeight },
441
+ ...(state.focalSet ? { focal: { x: state.focalX, y: state.focalY } } : {}),
442
+ crops: (current && current.crops) || {},
443
+ }
444
+ }
445
+
446
+ // --- crops ---------------------------------------------------------------------
447
+
448
+ /**
449
+ * A tile showing one rectangle of the picture, cut with CSS from the panel's
450
+ * own preview rather than asked of the CDN. The tiles then cost nothing to
451
+ * redraw, which is what lets them follow the focal point as it moves.
452
+ */
453
+ const TILE_HEIGHT = 54
454
+ const TILE_MAX_WIDTH = 140
455
+
456
+ function cropThumbStyle(rect) {
457
+ const W = state.sourceWidth
458
+ const H = state.sourceHeight
459
+ const px = W > rect.width ? (rect.x / (W - rect.width)) * 100 : 0
460
+ const py = H > rect.height ? (rect.y / (H - rect.height)) * 100 : 0
461
+ const ratio = rect.width / rect.height
462
+ const width = Math.min(TILE_MAX_WIDTH, TILE_HEIGHT * ratio)
463
+ return [
464
+ 'width: ' + pct(width) + 'px',
465
+ 'height: ' + pct(width / ratio) + 'px',
466
+ 'background-image: url("' + previewUrl(state.id) + '")',
467
+ 'background-size: ' + pct((W / rect.width) * 100) + '% auto',
468
+ 'background-position: ' + pct(px) + '% ' + pct(py) + '%',
469
+ ].join(';')
470
+ }
471
+
472
+ function showCrops() {
473
+ if (!state.sourceWidth || !state.sourceHeight) {
474
+ state.cropTiles = []
475
+ return
476
+ }
477
+ const picture = croppable()
478
+ const list = presetsNow()
479
+ const tiles = list.map((preset) => {
480
+ const stored = picture.crops[preset.name]
481
+ const label = preset.label + ' ' + preset.ratioLabel
482
+ return {
483
+ name: preset.name,
484
+ label,
485
+ adjusted: Boolean(stored),
486
+ note: stored ? 'Adjusted' : 'From focal point',
487
+ aria: label + (stored ? ', adjusted by hand' : ', from the focal point'),
488
+ thumbStyle: cropThumbStyle(stored || presetRect(picture, preset)),
489
+ }
490
+ })
491
+ for (const name of Object.keys(picture.crops)) {
492
+ if (list.some((preset) => preset.name === name)) continue
493
+ const rect = picture.crops[name]
494
+ tiles.push({
495
+ name,
496
+ label: name,
497
+ adjusted: true,
498
+ note: 'Custom',
499
+ aria: name + ', custom crop, ' + rect.width + ' by ' + rect.height,
500
+ thumbStyle: cropThumbStyle(rect),
501
+ })
502
+ }
503
+ state.cropTiles = tiles
504
+ describeCropMenu()
505
+ }
506
+
507
+ // Pages that use each crop, from what pages reported.
508
+ let cropPages = {}
509
+
510
+ function describeCropMenu() {
511
+ const name = state.cropMenu
512
+ const tile = state.cropTiles.find((one) => one.name === name)
513
+ if (!tile) {
514
+ state.cropMenu = ''
515
+ state.cropNote = 'Crops are shared too: changing one changes it on every page that uses it.'
516
+ return
517
+ }
518
+ const isPreset = presetsNow().some((one) => one.name === name)
519
+ state.cropMenuLabel = tile.label
520
+ state.cropMenuStored = tile.adjusted
521
+ state.cropMenuResetLabel = isPreset ? 'Use the default' : 'Delete this crop'
522
+ state.cropMenuResetHint = isPreset ? 'Go back to following the focal point' : 'Pages asking for it by name get the whole picture'
523
+ const pages = cropPages[name] || 0
524
+ state.cropNote = pages
525
+ ? 'Crops are shared too: changing ' + tile.label + ' changes it on ' + (pages === 1 ? 'the 1 page that uses it.' : 'all ' + pages + ' pages that use it.')
526
+ : 'Crops are shared too: changing ' + tile.label + ' changes it everywhere it is used.'
527
+ }
528
+
529
+ function menuItems() {
530
+ const menu = refs.cropMenu
531
+ if (!menu || !menu.querySelectorAll) return []
532
+ return Array.from(menu.querySelectorAll('[role="menuitem"]')).filter(
533
+ (one) => !one.hasAttribute('data-lsp-hidden') && !one.disabled
534
+ )
535
+ }
536
+
537
+ function focusTile(name) {
538
+ const root = refs.root
539
+ const tile = root && root.querySelector ? root.querySelector('[data-crop="' + name + '"]') : null
540
+ if (tile) tile.focus()
541
+ }
542
+
543
+ function toggleCropMenu(tile) {
544
+ if (state.cropMenu === tile.name) {
545
+ state.cropMenu = ''
546
+ describeCropMenu()
547
+ return
548
+ }
549
+ state.cropMenu = tile.name
550
+ describeCropMenu()
551
+ setTimeout(() => {
552
+ const first = menuItems()[0]
553
+ if (first) first.focus()
554
+ }, 0)
555
+ }
556
+
557
+ function closeCropMenu(refocus) {
558
+ const name = state.cropMenu
559
+ state.cropMenu = ''
560
+ describeCropMenu()
561
+ if (refocus && name) focusTile(name)
562
+ }
563
+
564
+ function cropMenuKey(event) {
565
+ if (!event) return
566
+ if (event.key === 'Escape') {
567
+ event.preventDefault()
568
+ closeCropMenu(true)
569
+ return
570
+ }
571
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return
572
+ event.preventDefault()
573
+ const items = menuItems()
574
+ if (!items.length) return
575
+ const at = items.indexOf(document.activeElement)
576
+ const next = event.key === 'ArrowDown' ? (at + 1) % items.length : (at - 1 + items.length) % items.length
577
+ items[next].focus()
578
+ }
579
+
580
+ function openCropEditor(name) {
581
+ if (state.readOnly) return
582
+ cropEditor.value = {
583
+ id: state.id,
584
+ label: state.label,
585
+ width: state.sourceWidth,
586
+ height: state.sourceHeight,
587
+ ...(state.focalSet ? { focal: { x: state.focalX, y: state.focalY } } : {}),
588
+ crops: { ...((current && current.crops) || {}) },
589
+ presets: presetsNow(),
590
+ pages: { ...cropPages },
591
+ name,
592
+ }
593
+ }
594
+
595
+ function editFromMenu() {
596
+ const name = state.cropMenu
597
+ closeCropMenu(true)
598
+ if (name) openCropEditor(name)
599
+ }
600
+
601
+ function startCustomCrop() {
602
+ closeCropMenu(false)
603
+ openCropEditor('')
604
+ }
605
+
606
+ async function resetFromMenu() {
607
+ const name = state.cropMenu
608
+ if (!name || state.readOnly) return
609
+ state.cropBusy = true
610
+ state.error = ''
611
+ try {
612
+ const result = await getLibrary().removeCrop(state.id, name)
613
+ const rest = { ...((current && current.crops) || {}) }
614
+ delete rest[name]
615
+ closeCropMenu(true)
616
+ rememberCrops((result && result.crops) || rest)
617
+ } catch (err) {
618
+ state.error = err && err.message ? err.message : 'Could not go back to the default.'
619
+ } finally {
620
+ state.cropBusy = false
621
+ }
622
+ }
623
+
624
+ function copyFromMenu() {
625
+ const name = state.cropMenu
626
+ closeCropMenu(true)
627
+ if (name) copyCropUrl(name)
628
+ }
629
+
630
+ // The row carries the crops too, so the grid and the next opening agree.
631
+ function rememberCrops(crops) {
632
+ current = { ...current, crops }
633
+ const row = selected.value
634
+ if (row && row.id === state.id) selected.value = { ...row, crops }
635
+ showCrops()
636
+ }
637
+
638
+ // --- where it is used -------------------------------------------------------------
639
+
640
+ function relative(iso) {
641
+ if (!iso) return ''
642
+ const ms = Date.now() - new Date(iso).getTime()
643
+ const h = Math.round(ms / 3600000)
644
+ if (h < 1) return 'just now'
645
+ if (h < 24) return h + ' h ago'
646
+ const d = Math.round(h / 24)
647
+ return d === 1 ? 'yesterday' : d + ' days ago'
648
+ }
649
+
650
+ function isOwnOrigin(origin) {
651
+ return typeof location !== 'undefined' && origin === location.origin
652
+ }
653
+
654
+ function siteLabel(origin) {
655
+ if (origin === '-') return 'Direct, or no referrer'
656
+ // The library's own thumbnails are requests too; say so rather than list
657
+ // the library as a site that uses its own pictures.
658
+ if (isOwnOrigin(origin)) return 'This library'
659
+ return origin.replace(/^https?:\/\//, '')
660
+ }
661
+
662
+ let usageGeneration = 0
663
+ let placements = []
664
+ let externalOrigins = 0
665
+
666
+ function groupBySite(list) {
667
+ const sites = []
668
+ for (const one of list) {
669
+ const name = one.site || 'Unnamed site'
670
+ let site = sites.find((each) => each.name === name)
671
+ if (!site) {
672
+ site = { name, pages: [] }
673
+ sites.push(site)
674
+ }
675
+ const where = (one.uses || [])
676
+ .map((use) => [use.block, use.field].filter(Boolean).join(' · ') + (use.crop ? ' (' + use.crop + ')' : ''))
677
+ .filter(Boolean)
678
+ .join(', ')
679
+ site.pages.push({
680
+ key: one.site + '#' + one.page,
681
+ title: one.title || one.page,
682
+ url: one.url || '',
683
+ draft: one.status !== 'published',
684
+ meta: where,
685
+ sep: false,
686
+ })
687
+ }
688
+ for (const site of sites) site.pages.forEach((page, i) => { page.sep = i < site.pages.length - 1 })
689
+ return sites
690
+ }
691
+
692
+ async function loadUsage(id) {
693
+ const port = getLibrary()
694
+ state.usageKnown = typeof port.usage === 'function'
695
+ state.sites = []
696
+ state.seen = []
697
+ state.copies = []
698
+ state.copiesLabel = ''
699
+ state.usageSummary = ''
700
+ placements = []
701
+ externalOrigins = 0
702
+ cropPages = {}
703
+ if (!state.usageKnown) return
704
+ const mine = ++usageGeneration
705
+ state.usageLoading = true
706
+ try {
707
+ const usage = await port.usage(id)
708
+ if (mine !== usageGeneration || id !== state.id) return
709
+ placements = usage.placements || []
710
+ state.sites = groupBySite(placements)
711
+ for (const one of placements) {
712
+ const named = new Set((one.uses || []).map((use) => use.crop).filter(Boolean))
713
+ for (const name of named) cropPages[name] = (cropPages[name] || 0) + 1
714
+ }
715
+ state.usageSummary = placements.length
716
+ ? plural(placements.length, 'page', 'pages') + ', ' + plural(state.sites.length, 'site', 'sites')
717
+ : 'Not used'
718
+ state.seen = (usage.seen || []).map((one) => {
719
+ const total = Object.values(one.days || {}).reduce((sum, n) => sum + n, 0)
720
+ return {
721
+ origin: one.origin,
722
+ label: siteLabel(one.origin),
723
+ meta: plural(total, 'request', 'requests') + ' in 30 days, last ' + relative(one.lastSeenAt),
724
+ }
725
+ })
726
+ externalOrigins = (usage.seen || []).filter((one) => one.origin !== '-' && !isOwnOrigin(one.origin)).length
727
+ state.copies = usage.copies || []
728
+ if (state.copies.length) {
729
+ const last = state.copies[0]
730
+ state.copiesLabel =
731
+ 'URL copied ' + plural(state.copies.length, 'time', 'times') +
732
+ (last.actor ? ', last by ' + last.actor : '') + (last.crop ? ' (' + last.crop + ')' : '') +
733
+ ' ' + relative(last.at) + '.'
734
+ }
735
+ describeCropMenu()
736
+ describeWords()
737
+ } catch {
738
+ // Usage is a courtesy; the panel is still about the picture.
739
+ } finally {
740
+ if (mine === usageGeneration) state.usageLoading = false
741
+ }
742
+ }
743
+
744
+ const COPY_WIDTH = 1600
745
+
746
+ async function copyToClipboard(url, crop) {
747
+ try {
748
+ await navigator.clipboard.writeText(url)
749
+ state.copyHint = 'Copied.'
750
+ } catch {
751
+ state.copyHint = url
752
+ }
753
+ const port = getLibrary()
754
+ if (typeof port.copied === 'function') port.copied(state.id, crop).catch(() => {})
755
+ }
756
+
757
+ function copyCropUrl(name) {
758
+ const rect = cropRect(croppable(), name, presetsNow())
759
+ if (!rect) return
760
+ const preset = presetsNow().find((one) => one.name === name)
761
+ const width = Math.min(rect.width, (preset && preset.minWidth) || COPY_WIDTH)
762
+ const url = getLibrary().imageUrl(state.id, {
763
+ crop: rect,
764
+ width,
765
+ height: Math.max(1, Math.round((width * rect.height) / rect.width)),
766
+ })
767
+ copyToClipboard(url, name)
768
+ }
769
+
770
+ function copyImageUrl() {
771
+ copyToClipboard(getLibrary().imageUrl(state.id, { width: Math.min(COPY_WIDTH, state.sourceWidth || COPY_WIDTH) }))
772
+ }
773
+
774
+ // --- labels ---------------------------------------------------------------------
775
+
776
+ // What was loaded, so a save knows whether a field actually changed and a late
777
+ // response knows whether anyone is still looking at it.
778
+ let loaded = { id: '', altText: '', credit: '', viewAltText: '', viewCredit: '', focal: '', labels: '' }
779
+
780
+ // The person's labels as a list of { term, audience }, kept apart from what
781
+ // a model proposed so a save replaces only what the person said.
782
+ function personLabelsOf(labels) {
783
+ return (labels || [])
784
+ .filter((one) => (!one.source || one.source.kind === 'person') && one.status !== 'rejected')
785
+ .map((one) => ({ term: one.term, audience: one.audience === 'internal' ? 'internal' : 'public' }))
786
+ }
787
+
788
+ function labelsKey(list) {
789
+ return (list || []).map((one) => one.term + ':' + one.audience).join('\u0000')
790
+ }
791
+
792
+ function normaliseLabel(word) {
793
+ return String(word || '').trim().toLowerCase().replace(/\s+/g, ' ')
794
+ }
795
+
796
+ // Suggestions dismissed while this picture is open. Not recorded anywhere
797
+ // yet: the port has no way to say a model's word was rejected.
798
+ let rejected = []
799
+
800
+ function proposedLabels() {
801
+ return ((current && current.labels) || []).filter(
802
+ (one) =>
803
+ one.source && one.source.kind !== 'person' &&
804
+ (one.status === 'generated' || one.status === 'pending') &&
805
+ !rejected.includes(one.term)
806
+ )
807
+ }
808
+
809
+ function drawLabels() {
810
+ state.labelChips = state.labels.map((one) => ({
811
+ term: one.term,
812
+ internal: one.audience === 'internal',
813
+ audienceLabel: one.audience === 'internal' ? 'Make ' + one.term + ' public' : 'Make ' + one.term + ' internal',
814
+ title: one.audience === 'internal' ? 'Internal: only staff see this' : '',
815
+ }))
816
+ state.hasInternal = state.labels.some((one) => one.audience === 'internal')
817
+ state.suggested = proposedLabels()
818
+ .filter((one) => !state.labels.some((have) => have.term === one.term))
819
+ .map((one) => ({
820
+ term: one.term,
821
+ title:
822
+ 'Suggested by ' + (one.source.model || one.source.connector || 'a model') +
823
+ (typeof one.score === 'number' ? ', ' + Math.round(one.score * 100) + '% sure' : ''),
824
+ }))
825
+ }
826
+
827
+ function setLabels(list) {
828
+ state.labels = list
829
+ drawLabels()
830
+ }
831
+
832
+ function addLabel(word, audience) {
833
+ const clean = normaliseLabel(word)
834
+ if (!clean || clean.length > 50) return
835
+ if (state.labels.some((one) => one.term === clean)) return
836
+ if (state.labels.length >= 100) return
837
+ setLabels(state.labels.concat([{ term: clean, audience: audience || 'public' }]))
838
+ }
839
+
840
+ function addLabelDraft() {
841
+ // Read from the box itself as well as the model: a keydown arrives before
842
+ // the model has caught up with the last character typed.
843
+ const input = refs.labelInput
844
+ const draft = (input && typeof input.value === 'string' ? input.value : state.labelDraft) || ''
845
+ if (!draft) return
846
+ for (const part of draft.split(',')) addLabel(part, state.labelInternal ? 'internal' : 'public')
847
+ state.labelDraft = ''
848
+ if (input) input.value = ''
849
+ }
850
+
851
+ function startAddLabel() {
852
+ state.addingLabel = true
853
+ setTimeout(() => {
854
+ if (refs.labelInput && refs.labelInput.focus) refs.labelInput.focus()
855
+ }, 0)
856
+ }
857
+
858
+ function labelKey(event) {
859
+ if (!event) return
860
+ if (event.key === 'Enter' || event.key === ',') {
861
+ event.preventDefault()
862
+ addLabelDraft()
863
+ } else if (event.key === 'Escape') {
864
+ event.preventDefault()
865
+ state.addingLabel = false
866
+ state.labelDraft = ''
867
+ }
868
+ }
869
+
870
+ function removeLabel(chip) {
871
+ setLabels(state.labels.filter((one) => one.term !== chip.term))
872
+ }
873
+
874
+ function acceptLabel(chip) {
875
+ addLabel(chip.term, 'public')
876
+ }
877
+
878
+ function rejectLabel(chip) {
879
+ rejected = rejected.concat([chip.term])
880
+ drawLabels()
881
+ }
882
+
883
+ function toggleAudience(chip) {
884
+ setLabels(
885
+ state.labels.map((one) =>
886
+ one.term === chip.term ? { ...one, audience: one.audience === 'internal' ? 'public' : 'internal' } : one
887
+ )
888
+ )
889
+ }
890
+
891
+ // --- the focal point ---------------------------------------------------------------
892
+
893
+ function focalKey(point) {
894
+ return point ? point.x + 'x' + point.y : ''
895
+ }
896
+
897
+ /** The frame's width: the panel's, unless the height cap says less. With the
898
+ * aspect ratio on the frame, the height follows. */
899
+ const PREVIEW_MAX_HEIGHT = '55vh'
900
+
901
+ function sizePreview(aspect) {
902
+ state.aspect = aspect
903
+ state.previewStyle = aspect
904
+ ? 'width: min(100%, calc(' + PREVIEW_MAX_HEIGHT + ' * ' + aspect + ')); aspect-ratio: ' + aspect
905
+ : 'width: 100%; aspect-ratio: 1'
906
+ }
907
+
908
+ function describePreview() {
909
+ const facts = [
910
+ state.sourceWidth && state.sourceHeight ? state.sourceWidth + ' × ' + state.sourceHeight : '',
911
+ state.format ? state.format.toUpperCase() : '',
912
+ state.createdLabel ? 'added ' + state.createdLabel : '',
913
+ ].filter(Boolean).join(' · ')
914
+ const where = state.focalSet ? state.focalX + '% across, ' + state.focalY + '% down' : 'the centre'
915
+ const help = state.canFocal
916
+ ? 'Click the picture to set what matters most, or focus the marker and use the arrow keys (Shift for bigger steps). Every crop keeps it in view.'
917
+ : 'Focal point: ' + where + '.'
918
+ state.previewNote = (facts ? facts + ' · ' : '') + help
919
+ }
920
+
921
+ function showFocal(point) {
922
+ state.focalSet = Boolean(point)
923
+ state.focalX = point ? point.x : 50
924
+ state.focalY = point ? point.y : 50
925
+ state.focalStyle = 'left:' + state.focalX + '%;top:' + state.focalY + '%'
926
+ state.focalAria = state.canFocal
927
+ ? 'Focal point, ' + (point ? state.focalX + '% across, ' + state.focalY + '% down' : 'the default, the centre') +
928
+ '. Arrow keys to move, Shift for bigger steps.'
929
+ : null
930
+ describePreview()
931
+ // The default crops are cut around the point, so they move with it.
932
+ if (state.ready) showCrops()
933
+ }
934
+
935
+ function setFocalEditable(editable) {
936
+ state.canFocal = editable
937
+ state.focalTab = editable ? 0 : null
938
+ state.focalRole = editable ? 'application' : null
939
+ }
940
+
941
+ function pointToFocal(event) {
942
+ const layer = refs.focalLayer
943
+ if (!layer || !layer.getBoundingClientRect) return null
944
+ const box = layer.getBoundingClientRect()
945
+ if (!box.width || !box.height) return null
946
+ return {
947
+ x: Math.round(Math.min(Math.max((event.clientX - box.left) / box.width, 0), 1) * 100),
948
+ y: Math.round(Math.min(Math.max((event.clientY - box.top) / box.height, 0), 1) * 100),
949
+ }
950
+ }
951
+
952
+ // A press places the point under the pointer and holds it: moving while
953
+ // pressed drags it, letting go leaves it there.
954
+ function grabFocal(event) {
955
+ if (!state.canFocal || !event || event.button) return
956
+ const point = pointToFocal(event)
957
+ if (!point) return
958
+ if (event.preventDefault) event.preventDefault()
959
+ state.focalDragging = true
960
+ showFocal(point)
961
+ if (refs.focalMarker && refs.focalMarker.focus) refs.focalMarker.focus({ preventScroll: true })
962
+ const layer = refs.focalLayer
963
+ if (layer && layer.setPointerCapture && event.pointerId !== undefined) {
964
+ try { layer.setPointerCapture(event.pointerId) } catch { /* not pointer-capable */ }
965
+ }
966
+ }
967
+
968
+ function dragFocal(event) {
969
+ if (!state.focalDragging) return
970
+ const point = pointToFocal(event)
971
+ if (point) showFocal(point)
972
+ }
973
+
974
+ function dropFocal(event) {
975
+ if (!state.focalDragging) return
976
+ state.focalDragging = false
977
+ const layer = refs.focalLayer
978
+ if (layer && layer.releasePointerCapture && event && event.pointerId !== undefined) {
979
+ try { layer.releasePointerCapture(event.pointerId) } catch { /* already released */ }
980
+ }
981
+ }
982
+
983
+ const FOCAL_KEYS = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
984
+
985
+ function focalKeys(event) {
986
+ if (!state.canFocal || !event) return
987
+ const move = FOCAL_KEYS[event.key]
988
+ if (!move) return
989
+ event.preventDefault()
990
+ const step = event.shiftKey ? 10 : 1
991
+ const clamp = (n) => Math.min(100, Math.max(0, n))
992
+ showFocal({ x: clamp(state.focalX + move[0] * step), y: clamp(state.focalY + move[1] * step) })
993
+ }
994
+
995
+ function clearFocal() {
996
+ showFocal(null)
997
+ }
998
+
999
+ // --- shared words and this site's own ------------------------------------------------
1000
+
1001
+ function hasWords(override) {
1002
+ return Boolean(override && (override.altText || override.credit))
1003
+ }
1004
+
1005
+ function describeWords() {
1006
+ const views = (current && current.views) || {}
1007
+ const own = Object.keys(views).filter((name) => hasWords(views[name]))
1008
+ state.sharedBadge = state.sites.length ? 'Shared · ' + plural(state.sites.length, 'site', 'sites') : 'Shared'
1009
+ state.sharedOthers = !own.length
1010
+ ? ''
1011
+ : own.length === 1
1012
+ ? ' 1 site has its own words: ' + own[0] + '.'
1013
+ : ' ' + own.length + ' sites have their own words: ' + own.join(', ') + '.'
1014
+ state.localNote = state.altText
1015
+ ? 'Only ' + state.view + ' uses these words. Every other site keeps the shared alt text: “' + state.altText + '”.'
1016
+ : 'Only ' + state.view + ' uses these words. Every other site keeps the shared words, which have no alt text yet.'
1017
+ }
1018
+
1019
+ function showView(summary) {
1020
+ const name = view.value || ''
1021
+ const override = (summary && summary.views && summary.views[name]) || {}
1022
+ state.view = name
1023
+ // Only on a picture in that group: a view is what it means there, and a
1024
+ // picture that is not there has nothing to mean.
1025
+ state.canDescribeView =
1026
+ canDescribeView(name || undefined) && Boolean(summary && (summary.tags || []).includes(name))
1027
+ state.viewAltText = override.altText || ''
1028
+ state.viewCredit = override.credit || ''
1029
+ state.wordsMode = state.canDescribeView && hasWords(override) ? 'local' : 'shared'
1030
+ loaded = { ...loaded, viewAltText: state.viewAltText, viewCredit: state.viewCredit }
1031
+ describeWords()
1032
+ }
1033
+
1034
+ function pickWords(mode) {
1035
+ if (!state.canDescribeView) return
1036
+ state.wordsMode = mode
1037
+ describeWords()
1038
+ }
1039
+
1040
+ function wordsKey(event) {
1041
+ if (!event || !['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) return
1042
+ event.preventDefault()
1043
+ const next = state.wordsMode === 'shared' ? 'local' : 'shared'
1044
+ pickWords(next)
1045
+ const group = event.currentTarget
1046
+ const button = group && group.querySelector ? group.querySelector('[data-words="' + next + '"]') : null
1047
+ if (button) button.focus()
1048
+ }
1049
+
1050
+ function useSharedWords() {
1051
+ state.viewAltText = ''
1052
+ state.viewCredit = ''
1053
+ pickWords('shared')
1054
+ }
1055
+
1056
+ // --- groups ------------------------------------------------------------------------
1057
+
1058
+ function showGroups(tags) {
1059
+ const list = tags || []
1060
+ state.groups = list.map((name) => {
1061
+ const canChange = !cannotChange([name])
1062
+ return { name, canChange, label: name + (canChange ? ' · you can change' : ' · you can see') }
1063
+ })
1064
+ state.ownerGroups = list.join(' or ')
1065
+ }
1066
+
1067
+ // --- colours -----------------------------------------------------------------------
1068
+
1069
+ const DEFAULT_HINT = 'Click a colour to copy it.'
1070
+ const NO_PALETTE = 'Not worked out yet.'
1071
+
1072
+ function swatchesOf(palette) {
1073
+ if (!palette || !palette.length) return []
1074
+ return palette.map((one) => ({
1075
+ hex: one.hex,
1076
+ style: 'background:' + one.hex,
1077
+ title: one.hex + (one.name ? ' · ' + one.name : '') + ' · ' + Math.round((one.weight || 0) * 100) + '%',
1078
+ }))
1079
+ }
1080
+
1081
+ function showPalette(palette) {
1082
+ state.palette = swatchesOf(palette)
1083
+ state.hasPalette = state.palette.length > 0
1084
+ state.paletteHint = DEFAULT_HINT
1085
+ if (!state.hasPalette && !state.enriching) {
1086
+ state.noPaletteHint = NO_PALETTE
1087
+ state.canEnrich = !state.readOnly
1088
+ }
1089
+ }
1090
+
1091
+ // A derivation runs after the request returns, so the panel asks again for a
1092
+ // while. Stops as soon as colours arrive, or when it is clear they will not.
1093
+ let enrichTimer = null
1094
+
1095
+ function stopPolling() {
1096
+ if (enrichTimer) clearTimeout(enrichTimer)
1097
+ enrichTimer = null
1098
+ }
1099
+
1100
+ async function pollForPalette(id, remaining) {
1101
+ stopPolling()
1102
+ if (remaining <= 0 || id !== state.id) {
1103
+ state.enriching = false
1104
+ state.noPaletteHint = 'Still working. Check back in a moment.'
1105
+ return
1106
+ }
1107
+ try {
1108
+ const detail = await getLibrary().detail(id)
1109
+ if (id !== state.id) return
1110
+ if (detail.palette && detail.palette.length) {
1111
+ state.enriching = false
1112
+ showPalette(detail.palette)
1113
+ const row = selected.value
1114
+ if (row && row.id === id) selected.value = { ...row, palette: detail.palette }
1115
+ return
1116
+ }
1117
+ } catch {
1118
+ // A failed poll is not worth a banner; the next one may succeed.
1119
+ }
1120
+ enrichTimer = setTimeout(() => pollForPalette(id, remaining - 1), 3000)
1121
+ }
1122
+
1123
+ async function enrich() {
1124
+ state.enriching = true
1125
+ state.noPaletteHint = 'Working out colours…'
1126
+ state.error = ''
1127
+ try {
1128
+ const result = await getLibrary().enrich(state.id)
1129
+ if (result.wanted && !result.wanted.includes('palette')) {
1130
+ state.noPaletteHint = 'This library does not work out colours.'
1131
+ state.canEnrich = false
1132
+ state.enriching = false
1133
+ return
1134
+ }
1135
+ pollForPalette(state.id, 20)
1136
+ } catch (err) {
1137
+ state.enriching = false
1138
+ state.noPaletteHint = NO_PALETTE
1139
+ state.error = err && err.message ? err.message : 'Could not ask for the colours.'
1140
+ }
1141
+ }
1142
+
1143
+ async function copy(one) {
1144
+ try {
1145
+ await navigator.clipboard.writeText(one.hex)
1146
+ state.paletteHint = 'Copied ' + one.hex
1147
+ } catch {
1148
+ state.paletteHint = one.hex
1149
+ }
1150
+ }
1151
+
1152
+ // --- loading a picture ----------------------------------------------------------------
1153
+
1154
+ let generation = 0
1155
+
1156
+ function close() {
1157
+ selected.value = null
1158
+ }
1159
+
1160
+ function showDeleted(asset) {
1161
+ state.deletedAt = asset.deletedAt || ''
1162
+ state.deletedLabel = shortDate(asset.deletedAt)
1163
+ const reason = asset.deletedReason ? '“' + asset.deletedReason + '”' : ''
1164
+ state.deletedDetail = asset.deletedBy
1165
+ ? 'Moved by ' + asset.deletedBy + (reason ? ': ' + reason : '') + '.'
1166
+ : reason
1167
+ ? 'Reason: ' + reason + '.'
1168
+ : ''
1169
+ setFocalEditable(!state.readOnly && !state.deletedAt)
1170
+ }
1171
+
1172
+ // The same picture again - a crop saved, a move to the bin - refreshes what
1173
+ // changed without throwing away words being typed.
1174
+ function refresh(summary) {
1175
+ current = { ...current, ...summary }
1176
+ showDeleted(current)
1177
+ showFocal(state.focalSet ? { x: state.focalX, y: state.focalY } : null)
1178
+ showCrops()
1179
+ drawLabels()
1180
+ }
1181
+
1182
+ function onSelected(summary) {
1183
+ if (summary && state.open && state.id === summary.id && current) {
1184
+ refresh(summary)
1185
+ return
1186
+ }
1187
+ load(summary)
1188
+ }
1189
+
1190
+ async function load(summary) {
1191
+ stopPolling()
1192
+ state.enriching = false
1193
+ if (cropEditor.value) cropEditor.value = null
1194
+ if (binDialog.value) binDialog.value = null
1195
+ if (!summary) {
1196
+ state.open = false
1197
+ state.ready = false
1198
+ return
1199
+ }
1200
+
1201
+ const mine = ++generation
1202
+
1203
+ state.open = true
1204
+ state.ready = false
1205
+ state.error = ''
1206
+ state.saveStatus = ''
1207
+ state.id = summary.id
1208
+ state.label = summary.filename || summary.id
1209
+ sizePreview(summary.width && summary.height ? summary.width / summary.height : 0)
1210
+ state.standIn = summary.palette && summary.palette.length ? summary.palette[0].hex : 'var(--px-surface-2)'
1211
+
1212
+ state.altText = summary.altText || ''
1213
+ state.credit = summary.credit || ''
1214
+ state.labelDraft = ''
1215
+ state.addingLabel = false
1216
+ state.labelInternal = false
1217
+ state.cropMenu = ''
1218
+ rejected = []
1219
+ current = summary
1220
+ // Per picture: a host that writes to one group can use the others' pictures
1221
+ // but not change them, and the panel should say so before the button.
1222
+ state.readOnly = Boolean(cannotChange(summary.tags))
1223
+ setLabels(personLabelsOf(summary.labels))
1224
+ loaded = { ...loaded, labels: labelsKey(state.labels) }
1225
+ state.sourceWidth = summary.width || 0
1226
+ state.sourceHeight = summary.height || 0
1227
+ state.format = summary.format || ''
1228
+ state.createdLabel = shortDate(summary.createdAt)
1229
+ showDeleted(summary)
1230
+ showView(summary)
1231
+ showFocal(summary.focal || null)
1232
+ showCrops()
1233
+ state.copyHint = ''
1234
+ loadUsage(summary.id)
1235
+ loaded = { ...loaded, focal: focalKey(summary.focal) }
1236
+ showPalette(summary.palette)
1237
+ showGroups(summary.tags)
1238
+
1239
+ try {
1240
+ const detail = await getLibrary().detail(summary.id)
1241
+ if (mine !== generation) return
1242
+
1243
+ if (detail.width && detail.height) {
1244
+ sizePreview(detail.width / detail.height)
1245
+ state.sourceWidth = detail.width
1246
+ state.sourceHeight = detail.height
1247
+ }
1248
+ if (detail.crops && current) current = { ...current, crops: detail.crops }
1249
+ if (detail.labels && current) current = { ...current, labels: detail.labels }
1250
+ if (detail.format) state.format = detail.format
1251
+ if (detail.createdAt) state.createdLabel = shortDate(detail.createdAt)
1252
+ if (detail.palette) showPalette(detail.palette)
1253
+ showDeleted({ ...summary, ...detail })
1254
+ if (detail.tags) showGroups(detail.tags)
1255
+ drawLabels()
1256
+ // Deliberately not taken from the detail response. `/meta` is cacheable -
1257
+ // it is mostly facts derived from bytes, which do not change - while the
1258
+ // listing is not, so the row is the fresher of the two about anything a
1259
+ // person edits. Letting a cached detail win here showed an empty field
1260
+ // seconds after somebody filled it in.
1261
+ loaded = { ...loaded, id: summary.id, altText: state.altText, credit: state.credit }
1262
+ state.ready = true
1263
+ if (detail.focal && focalKey(detail.focal) !== loaded.focal) {
1264
+ loaded = { ...loaded, focal: focalKey(detail.focal) }
1265
+ showFocal(detail.focal)
1266
+ } else {
1267
+ showFocal(state.focalSet ? { x: state.focalX, y: state.focalY } : null)
1268
+ }
1269
+ describeWords()
1270
+ } catch (err) {
1271
+ if (mine !== generation) return
1272
+ state.error = err && err.message ? err.message : 'Could not load this picture.'
1273
+ }
1274
+ }
1275
+
1276
+ async function save() {
1277
+ if (state.readOnly) return
1278
+ // Only what changed. Sending both would let a panel opened and saved without
1279
+ // being read overwrite a field somebody else had just filled in.
1280
+ const patch = {}
1281
+ if (state.altText !== loaded.altText) patch.altText = state.altText || null
1282
+ if (state.credit !== loaded.credit) patch.credit = state.credit || null
1283
+ const focal = state.focalSet ? { x: state.focalX, y: state.focalY } : null
1284
+ if (focalKey(focal) !== loaded.focal) patch.focal = focal
1285
+ addLabelDraft()
1286
+ if (labelsKey(state.labels) !== loaded.labels) patch.labels = state.labels.map((one) => ({ ...one }))
1287
+
1288
+ // The view's own words, separately: a different write, with its own rules.
1289
+ // Emptied, the view goes back to reading the shared words.
1290
+ const viewPatch = {}
1291
+ let dropView = false
1292
+ if (state.view && state.canDescribeView) {
1293
+ const hadOwn = Boolean(loaded.viewAltText || loaded.viewCredit)
1294
+ if (hadOwn && !state.viewAltText && !state.viewCredit) {
1295
+ dropView = true
1296
+ } else {
1297
+ if (state.viewAltText !== loaded.viewAltText) viewPatch.altText = state.viewAltText || null
1298
+ if (state.viewCredit !== loaded.viewCredit) viewPatch.credit = state.viewCredit || null
1299
+ }
1300
+ }
1301
+
1302
+ if (!Object.keys(patch).length && !Object.keys(viewPatch).length && !dropView) {
1303
+ state.saveStatus = 'Nothing to save.'
1304
+ return
1305
+ }
1306
+
1307
+ state.saving = true
1308
+ state.saveLabel = 'Saving…'
1309
+ state.saveStatus = ''
1310
+ state.error = ''
1311
+
1312
+ try {
1313
+ if (Object.keys(patch).length) await getLibrary().describe(state.id, patch)
1314
+ let views = { ...((current && current.views) || {}) }
1315
+ if (dropView) {
1316
+ await getLibrary().removeView(state.id, state.view)
1317
+ delete views[state.view]
1318
+ } else if (Object.keys(viewPatch).length) {
1319
+ const result = await getLibrary().describe(state.id, viewPatch, { view: state.view })
1320
+ views = result && result.views
1321
+ ? result.views
1322
+ : { ...views, [state.view]: { altText: state.viewAltText, credit: state.viewCredit } }
1323
+ }
1324
+ loaded = {
1325
+ id: state.id,
1326
+ altText: state.altText,
1327
+ credit: state.credit,
1328
+ viewAltText: state.viewAltText,
1329
+ viewCredit: state.viewCredit,
1330
+ focal: focalKey(focal),
1331
+ labels: labelsKey(state.labels),
1332
+ }
1333
+ state.saveStatus = 'Saved.'
1334
+
1335
+ // The row in the grid carries these too, so it has to hear about it -
1336
+ // otherwise the list disagrees with the panel until a reload.
1337
+ const next = {
1338
+ ...(current || {}),
1339
+ altText: state.altText,
1340
+ credit: state.credit,
1341
+ views,
1342
+ labels: ((current && current.labels) || [])
1343
+ .filter((one) => one.source && one.source.kind !== 'person')
1344
+ .concat(state.labels.map((one) => ({ term: one.term, status: 'verified', source: { kind: 'person' }, audience: one.audience }))),
1345
+ }
1346
+ if (focal) next.focal = focal
1347
+ else delete next.focal
1348
+ current = next
1349
+ const row = selected.value
1350
+ if (row && row.id === state.id) {
1351
+ const merged = { ...row, ...next }
1352
+ if (!focal) delete merged.focal
1353
+ selected.value = merged
1354
+ }
1355
+ describeWords()
1356
+ } catch (err) {
1357
+ state.error = err && err.message ? err.message : 'Could not save.'
1358
+ } finally {
1359
+ state.saving = false
1360
+ state.saveLabel = 'Save'
1361
+ }
1362
+ }
1363
+
1364
+ function askToDelete() {
1365
+ state.error = ''
1366
+ binDialog.value = {
1367
+ id: state.id,
1368
+ label: state.label,
1369
+ usageKnown: state.usageKnown && !state.usageLoading,
1370
+ pages: placements.map((one) => ({ site: one.site, title: one.title || one.page })),
1371
+ seen: externalOrigins,
1372
+ }
1373
+ }
1374
+
1375
+ async function restore() {
1376
+ state.busy = true
1377
+ state.restoreLabel = 'Restoring…'
1378
+ state.error = ''
1379
+ try {
1380
+ await getLibrary().restore(state.id)
1381
+ const next = { ...current }
1382
+ delete next.deletedAt
1383
+ delete next.deletedReason
1384
+ delete next.deletedBy
1385
+ current = next
1386
+ const row = selected.value
1387
+ if (row && row.id === state.id) {
1388
+ const restored = { ...row }
1389
+ delete restored.deletedAt
1390
+ delete restored.deletedReason
1391
+ delete restored.deletedBy
1392
+ selected.value = restored
1393
+ }
1394
+ showDeleted(current)
1395
+ showFocal(state.focalSet ? { x: state.focalX, y: state.focalY } : null)
1396
+ changed.value = (changed.value || 0) + 1
1397
+ } catch (err) {
1398
+ state.error = err && err.message ? err.message : 'Could not restore.'
1399
+ } finally {
1400
+ state.busy = false
1401
+ state.restoreLabel = 'Restore'
1402
+ }
1403
+ }
1404
+
1405
+ selected.subscribe(onSelected)
1406
+ view.subscribe(() => {
1407
+ if (state.open && current) showView(current)
1408
+ })
1409
+ presets.subscribe(() => {
1410
+ if (state.open) showCrops()
1411
+ })
1412
+
1413
+ onMounted(() => {
1414
+ state.readOnly = !canWrite()
1415
+ if (selected.value) load(selected.value)
1416
+ })
1417
+ </logic>
1418
+
1419
+ <style>
1420
+ .inspector {
1421
+ overflow-y: auto;
1422
+ }
1423
+
1424
+ .head-text {
1425
+ flex: 1;
1426
+ min-width: 0;
1427
+ display: flex;
1428
+ flex-direction: column;
1429
+ }
1430
+
1431
+ .title {
1432
+ font-size: var(--px-fs-m);
1433
+ white-space: nowrap;
1434
+ overflow: hidden;
1435
+ text-overflow: ellipsis;
1436
+ }
1437
+
1438
+ .start {
1439
+ align-self: flex-start;
1440
+ }
1441
+
1442
+ .preview {
1443
+ /* The panel is a column of flex items and would shrink this one to fit the
1444
+ rest. The picture's height is the picture's; the panel scrolls. */
1445
+ flex: none;
1446
+ display: flex;
1447
+ justify-content: center;
1448
+ align-items: flex-start;
1449
+ background: var(--px-surface-2);
1450
+ border-radius: var(--px-r-m);
1451
+ overflow: hidden;
1452
+ }
1453
+
1454
+ .preview.binned .preview-frame {
1455
+ filter: grayscale(1);
1456
+ opacity: 0.5;
1457
+ }
1458
+
1459
+ .preview-frame {
1460
+ position: relative;
1461
+ }
1462
+
1463
+ .focal-layer {
1464
+ position: absolute;
1465
+ inset: 0;
1466
+ /* Above the picture, which the image component layers over its stand-in. */
1467
+ z-index: 3;
1468
+ touch-action: none;
1469
+ }
1470
+
1471
+ .focal-layer.editable {
1472
+ cursor: crosshair;
1473
+ }
1474
+
1475
+ .focal-layer.dragging {
1476
+ cursor: grabbing;
1477
+ }
1478
+
1479
+ .focal.is-default {
1480
+ opacity: 0.7;
1481
+ }
1482
+
1483
+ .words {
1484
+ display: flex;
1485
+ flex-direction: column;
1486
+ gap: 10px;
1487
+ }
1488
+
1489
+ .chips {
1490
+ gap: 6px;
1491
+ }
1492
+
1493
+ .px-chip.is-static {
1494
+ padding-right: 10px;
1495
+ }
1496
+
1497
+ .px-chip button[aria-pressed="false"] {
1498
+ opacity: 0.45;
1499
+ }
1500
+
1501
+ .add-label {
1502
+ display: flex;
1503
+ flex-wrap: wrap;
1504
+ align-items: flex-end;
1505
+ gap: 8px;
1506
+ }
1507
+
1508
+ .grow {
1509
+ flex: 1 1 160px;
1510
+ }
1511
+
1512
+ .internal-check {
1513
+ display: inline-flex;
1514
+ align-items: center;
1515
+ gap: 6px;
1516
+ min-height: 36px;
1517
+ font-size: var(--px-fs-s);
1518
+ }
1519
+
1520
+ .suggested {
1521
+ display: flex;
1522
+ flex-direction: column;
1523
+ gap: 6px;
1524
+ }
1525
+
1526
+ .crop-cut {
1527
+ display: block;
1528
+ background-repeat: no-repeat;
1529
+ background-color: var(--px-surface-2);
1530
+ }
1531
+
1532
+ .px-crop-name,
1533
+ .crop-note {
1534
+ white-space: nowrap;
1535
+ }
1536
+
1537
+ .crop-note {
1538
+ font-size: 11px;
1539
+ color: var(--px-text-3);
1540
+ }
1541
+
1542
+ .adjusted {
1543
+ align-self: flex-start;
1544
+ height: 18px;
1545
+ padding: 0 6px;
1546
+ font-size: 10px;
1547
+ }
1548
+
1549
+ .crop-menu {
1550
+ padding: 6px;
1551
+ }
1552
+
1553
+ .menu-item {
1554
+ justify-content: flex-start;
1555
+ }
1556
+
1557
+ .menu-item.two-line {
1558
+ flex-direction: column;
1559
+ align-items: flex-start;
1560
+ gap: 0;
1561
+ padding: 8px 16px;
1562
+ }
1563
+
1564
+ .menu-item.two-line .px-subtle {
1565
+ font-size: var(--px-fs-xs);
1566
+ font-weight: 400;
1567
+ }
1568
+
1569
+ .swatch {
1570
+ width: 32px;
1571
+ height: 32px;
1572
+ padding: 0;
1573
+ border: 1px solid var(--px-border);
1574
+ border-radius: var(--px-r-s);
1575
+ cursor: pointer;
1576
+ }
1577
+
1578
+ .px-swatches {
1579
+ flex-wrap: wrap;
1580
+ }
1581
+
1582
+ .groups {
1583
+ gap: 6px;
1584
+ }
1585
+
1586
+ .group {
1587
+ height: 26px;
1588
+ }
1589
+
1590
+ .used-in {
1591
+ margin: 0;
1592
+ padding: 0;
1593
+ list-style: none;
1594
+ display: flex;
1595
+ flex-direction: column;
1596
+ gap: 6px;
1597
+ font-size: 14px;
1598
+ }
1599
+
1600
+ .seen-title {
1601
+ margin-top: 4px;
1602
+ }
1603
+
1604
+ .bin-row {
1605
+ flex-direction: row;
1606
+ justify-content: flex-end;
1607
+ }
1608
+
1609
+ .foot {
1610
+ position: sticky;
1611
+ bottom: 0;
1612
+ z-index: 5;
1613
+ display: flex;
1614
+ align-items: center;
1615
+ justify-content: flex-end;
1616
+ gap: 12px;
1617
+ margin-top: auto;
1618
+ padding: 12px 16px;
1619
+ border-top: 1px solid var(--px-border);
1620
+ background: var(--px-surface);
1621
+ }
1622
+ </style>