@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,436 @@
1
+ <view>
2
+ <div class="px-scrim scrim" $show="state.open" @click="backdrop">
3
+ <div class="px-dialog dialog" role="dialog" aria-modal="true" aria-labelledby="link-title" $ref="root" @keydown="onKey">
4
+ <div class="px-dialog-head">
5
+ <h3 id="link-title">Get a link or file · {{ state.label }}</h3>
6
+ </div>
7
+
8
+ <div class="body">
9
+ <div class="choices">
10
+ <fieldset class="set">
11
+ <legend class="px-label">Crop</legend>
12
+ <div class="px-row opts">
13
+ <button class="opt" type="button" $for="one in state.crops" $key="one.name" $aria-pressed="one.name === state.crop" @click="setCrop(one.name)">{{ one.label }}</button>
14
+ </div>
15
+ <div class="px-row custom" $show="state.crop === 'custom'">
16
+ <label for="link-w">Shape</label>
17
+ <input class="px-input num" id="link-w" type="number" min="1" max="100" aria-label="Shape, width part" $model="state.ratioW" @input="draw" />
18
+ <span aria-hidden="true">:</span>
19
+ <input class="px-input num" type="number" min="1" max="100" aria-label="Shape, height part" $model="state.ratioH" @input="draw" />
20
+ <span class="px-subtle">centred on the focal point</span>
21
+ </div>
22
+ </fieldset>
23
+
24
+ <fieldset class="set">
25
+ <legend class="px-label">Width</legend>
26
+ <div class="px-row opts">
27
+ <button class="opt" type="button" $for="one in state.widths" $key="one.key" $aria-pressed="one.key === state.width" $disabled="one.tooWide" $title="one.title" @click="setWidth(one.key)">{{ one.label }}</button>
28
+ </div>
29
+ <span class="px-hint">{{ state.widthNote }}</span>
30
+ </fieldset>
31
+
32
+ <fieldset class="set">
33
+ <legend class="px-label">Format</legend>
34
+ <div class="px-row opts">
35
+ <button class="opt" type="button" $for="one in state.formats" $key="one.key" $aria-pressed="one.key === state.format" @click="setFormat(one.key)">{{ one.label }}</button>
36
+ </div>
37
+ </fieldset>
38
+
39
+ <div class="px-row save" $show="state.crop === 'custom' && state.canSave">
40
+ <input class="px-input" type="text" aria-label="Name for this crop" placeholder="Name it to keep this crop on the picture" $model="state.saveName" />
41
+ <button class="px-btn px-btn-secondary px-btn-sm" type="button" $disabled="!state.saveName.trim() || state.saving" @click="saveCrop">Save crop</button>
42
+ </div>
43
+ </div>
44
+
45
+ <div class="result">
46
+ <div class="preview"><img $src="state.previewUrl" alt="" /></div>
47
+ <span class="px-subtle">{{ state.sizeNote }}</span>
48
+ <input class="px-input px-mono url" type="text" readonly aria-label="Link" $value="state.url" $ref="url" @focus="selectUrl" />
49
+ <span class="px-hint">Anyone with the link can see the picture. Alt text isn't part of a link: add it wherever the picture is used.</span>
50
+ <span class="px-hint" role="status" $class="{ 'text-danger': state.failed }">{{ state.note }}</span>
51
+ </div>
52
+ </div>
53
+
54
+ <div class="px-dialog-foot">
55
+ <button class="px-btn px-btn-ghost" type="button" @click="close">Close</button>
56
+ <button class="px-btn px-btn-secondary" type="button" @click="download">Download</button>
57
+ <button class="px-btn px-btn-primary" type="button" $ref="copy" @click="copy">Copy link</button>
58
+ </div>
59
+ </div>
60
+ </div>
61
+ </view>
62
+
63
+ <logic lang="ts">
64
+ import { reactive, shared, defineRefs } from '@lightspeed-js/core'
65
+ import { presetRect } from '@pseudolux-ui/client'
66
+ import { getLibrary, cannotChange, LINK, PRESETS, PATCHED } from '../config.ts'
67
+
68
+ /**
69
+ * A link or a file for any crop of a picture, at a width and in a format.
70
+ * The link is the picture's own address for that cut, so it follows the
71
+ * picture: a crop edited later changes what a preset's link would be, and a
72
+ * link already taken keeps showing what it showed.
73
+ */
74
+ const refs = defineRefs()
75
+
76
+ const WIDTHS = [1080, 1600, 800, 400]
77
+ const FORMATS = [
78
+ { key: '', label: 'Auto' },
79
+ { key: 'jpeg', label: 'JPEG' },
80
+ { key: 'webp', label: 'WebP' },
81
+ { key: 'avif', label: 'AVIF' },
82
+ { key: 'png', label: 'PNG' },
83
+ ]
84
+
85
+ const state = reactive({
86
+ open: false,
87
+ label: '',
88
+ crops: [],
89
+ crop: 'original',
90
+ ratioW: 3,
91
+ ratioH: 2,
92
+ widths: [],
93
+ width: '1080',
94
+ widthNote: '',
95
+ formats: FORMATS,
96
+ format: '',
97
+ previewUrl: '',
98
+ sizeNote: '',
99
+ url: '',
100
+ note: '',
101
+ failed: false,
102
+ canSave: false,
103
+ saveName: '',
104
+ saving: false,
105
+ })
106
+
107
+ const link = shared(LINK)
108
+ const presets = shared(PRESETS)
109
+ const patched = shared(PATCHED)
110
+
111
+ let asset = null
112
+ let opener = null
113
+
114
+ const picture = () => ({
115
+ dimensions: { width: asset.width || 0, height: asset.height || 0 },
116
+ ...(asset.focal ? { focal: asset.focal } : {}),
117
+ crops: asset.crops || {},
118
+ })
119
+
120
+ function rectNow() {
121
+ const W = asset.width || 0
122
+ const H = asset.height || 0
123
+ if (state.crop === 'original') return { x: 0, y: 0, width: W, height: H }
124
+ if (state.crop === 'custom') {
125
+ const w = Math.max(1, Number(state.ratioW) || 1)
126
+ const h = Math.max(1, Number(state.ratioH) || 1)
127
+ return presetRect(picture(), { ratio: w / h })
128
+ }
129
+ const stored = (asset.crops || {})[state.crop]
130
+ if (stored) return { x: stored.x, y: stored.y, width: stored.width, height: stored.height }
131
+ const preset = (presets.value || []).find((one) => one.name === state.crop)
132
+ return preset ? presetRect(picture(), preset) : { x: 0, y: 0, width: W, height: H }
133
+ }
134
+
135
+ function draw() {
136
+ if (!asset) return
137
+ const list = presets.value || []
138
+ state.crops = [{ name: 'original', label: 'Original' }]
139
+ .concat(list.map((one) => ({ name: one.name, label: one.label + ' ' + one.ratioLabel })))
140
+ .concat(Object.keys(asset.crops || {}).filter((name) => !list.some((one) => one.name === name)).map((name) => ({ name, label: name })))
141
+ .concat([{ name: 'custom', label: 'Custom shape…' }])
142
+
143
+ const rect = rectNow()
144
+ state.widths = WIDTHS.map((one) => ({
145
+ key: String(one),
146
+ label: one + ' px',
147
+ tooWide: one > rect.width,
148
+ title: one > rect.width ? 'This crop is only ' + rect.width + ' px wide' : '',
149
+ })).concat([{ key: 'full', label: 'Full size', tooWide: false, title: '' }])
150
+ // A width the crop cannot fill falls back to the widest that fits.
151
+ if (state.width !== 'full' && Number(state.width) > rect.width) {
152
+ const fits = WIDTHS.filter((one) => one <= rect.width).sort((a, b) => b - a)[0]
153
+ state.width = fits ? String(fits) : 'full'
154
+ }
155
+ const width = state.width === 'full' ? rect.width : Number(state.width)
156
+ const height = Math.max(1, Math.round((width * rect.height) / rect.width))
157
+ state.widthNote = rect.width < Math.max(...WIDTHS)
158
+ ? 'This crop is ' + rect.width.toLocaleString() + ' px wide. A link never enlarges a picture past its real size.'
159
+ : ''
160
+
161
+ const whole = state.crop === 'original'
162
+ const options = {
163
+ width,
164
+ ...(whole ? {} : { height, crop: rect }),
165
+ ...(state.format ? { format: state.format } : {}),
166
+ }
167
+ const port = getLibrary()
168
+ state.url = new URL(port.imageUrl(asset.id, options), location.href).href
169
+ state.previewUrl = port.imageUrl(asset.id, { ...options, width: Math.min(width, 800), ...(whole ? {} : { height: Math.max(1, Math.round((Math.min(width, 800) * rect.height) / rect.width)) }) })
170
+ state.sizeNote = width.toLocaleString() + ' × ' + height.toLocaleString() + ' px' + (state.format ? ' · ' + state.format.toUpperCase() : ' · the best format for each browser')
171
+ state.canSave = !cannotChange(asset.tags) && typeof port.setCrop === 'function'
172
+ }
173
+
174
+ function setCrop(name) {
175
+ state.crop = name
176
+ state.note = ''
177
+ draw()
178
+ }
179
+
180
+ function setWidth(key) {
181
+ state.width = key
182
+ draw()
183
+ }
184
+
185
+ function setFormat(key) {
186
+ state.format = key
187
+ draw()
188
+ }
189
+
190
+ function selectUrl(event) {
191
+ event.target.select()
192
+ }
193
+
194
+ async function copy() {
195
+ const port = getLibrary()
196
+ try {
197
+ await navigator.clipboard.writeText(state.url)
198
+ state.note = 'Link copied.'
199
+ state.failed = false
200
+ } catch {
201
+ state.note = "Couldn't copy. The link is in the box above."
202
+ state.failed = true
203
+ if (refs.url) refs.url.select()
204
+ }
205
+ if (typeof port.copied === 'function') port.copied(asset.id, state.crop === 'original' || state.crop === 'custom' ? undefined : state.crop).catch(() => {})
206
+ }
207
+
208
+ async function download() {
209
+ const name = (asset.filename || asset.id).replace(/\.[a-z0-9]+$/i, '') + (state.crop === 'original' ? '' : '-' + (state.crop === 'custom' ? state.ratioW + 'x' + state.ratioH : state.crop))
210
+ state.note = 'Getting the file…'
211
+ state.failed = false
212
+ try {
213
+ const response = await fetch(state.url)
214
+ if (!response.ok) throw new Error(String(response.status))
215
+ const blob = await response.blob()
216
+ const extension = (blob.type.split('/')[1] || 'jpg').replace('jpeg', 'jpg').replace('svg+xml', 'svg')
217
+ const href = URL.createObjectURL(blob)
218
+ const anchor = document.createElement('a')
219
+ anchor.href = href
220
+ anchor.download = name + '.' + extension
221
+ anchor.click()
222
+ setTimeout(() => URL.revokeObjectURL(href), 10000)
223
+ state.note = 'Downloaded ' + anchor.download + '.'
224
+ } catch {
225
+ // Another origin may not let the page read the file; the browser can
226
+ // still open it, and save from there.
227
+ window.open(state.url, '_blank', 'noopener')
228
+ state.note = 'Opened in a new tab: save it from there.'
229
+ }
230
+ }
231
+
232
+ async function saveCrop() {
233
+ const name = state.saveName.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
234
+ if (!name || !asset) return
235
+ if ((presets.value || []).some((one) => one.name === name)) {
236
+ state.note = 'That name is one of the standard shapes. Choose another.'
237
+ state.failed = true
238
+ return
239
+ }
240
+ const rect = rectNow()
241
+ state.saving = true
242
+ try {
243
+ await getLibrary().setCrop(asset.id, name, rect)
244
+ asset.crops = { ...(asset.crops || {}), [name]: { ...rect, savedAt: new Date().toISOString() } }
245
+ patched.value = { id: asset.id, replace: { crops: asset.crops } }
246
+ state.crop = name
247
+ state.saveName = ''
248
+ state.note = 'Saved as “' + name + '” on the picture.'
249
+ state.failed = false
250
+ draw()
251
+ } catch (err) {
252
+ state.note = "Couldn't save the crop: " + (err && err.message ? err.message : 'no answer from the library')
253
+ state.failed = true
254
+ } finally {
255
+ state.saving = false
256
+ }
257
+ }
258
+
259
+ function close() {
260
+ link.value = null
261
+ }
262
+
263
+ function backdrop(event) {
264
+ if (event.target && event.target.classList && event.target.classList.contains('scrim')) close()
265
+ }
266
+
267
+ function onKey(event) {
268
+ if (event.key === 'Escape') {
269
+ event.preventDefault()
270
+ event.stopPropagation()
271
+ close()
272
+ return
273
+ }
274
+ // Keys in here are for this dialog, not whatever is under it.
275
+ event.stopPropagation()
276
+ if (event.key !== 'Tab' || !refs.root) return
277
+ const stops = Array.from(refs.root.querySelectorAll('button, input')).filter((one) => !one.disabled && one.offsetParent !== null)
278
+ const first = stops[0]
279
+ const last = stops[stops.length - 1]
280
+ if (event.shiftKey && document.activeElement === first) {
281
+ event.preventDefault()
282
+ last.focus()
283
+ } else if (!event.shiftKey && document.activeElement === last) {
284
+ event.preventDefault()
285
+ first.focus()
286
+ }
287
+ }
288
+
289
+ link.subscribe((value) => {
290
+ if (!value) {
291
+ if (!state.open) return
292
+ state.open = false
293
+ asset = null
294
+ if (opener && document.contains(opener) && opener.focus) opener.focus()
295
+ opener = null
296
+ return
297
+ }
298
+ asset = JSON.parse(JSON.stringify(value))
299
+ opener = document.activeElement
300
+ state.label = asset.filename || asset.id
301
+ state.crop = 'original'
302
+ state.width = '1080'
303
+ state.format = ''
304
+ state.note = ''
305
+ state.failed = false
306
+ state.saveName = ''
307
+ state.open = true
308
+ draw()
309
+ requestAnimationFrame(() => refs.copy && refs.copy.focus())
310
+ })
311
+ </logic>
312
+
313
+ <style>
314
+ .scrim {
315
+ position: fixed;
316
+ inset: 0;
317
+ z-index: 55;
318
+ display: flex;
319
+ align-items: center;
320
+ justify-content: center;
321
+ padding: 24px;
322
+ background: var(--px-scrim);
323
+ }
324
+
325
+ .dialog {
326
+ display: flex;
327
+ flex-direction: column;
328
+ width: min(920px, 100%);
329
+ max-height: 100%;
330
+ color: var(--px-text);
331
+ }
332
+
333
+ .body {
334
+ display: grid;
335
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
336
+ gap: 24px;
337
+ padding: 20px;
338
+ overflow: auto;
339
+ }
340
+
341
+ .choices,
342
+ .result {
343
+ display: flex;
344
+ flex-direction: column;
345
+ gap: 16px;
346
+ min-width: 0;
347
+ }
348
+
349
+ .set {
350
+ border: 0;
351
+ margin: 0;
352
+ padding: 0;
353
+ display: flex;
354
+ flex-direction: column;
355
+ gap: 8px;
356
+ min-width: 0;
357
+ }
358
+
359
+ .set legend {
360
+ padding: 0;
361
+ margin-bottom: 8px;
362
+ }
363
+
364
+ .opts {
365
+ gap: 6px;
366
+ flex-wrap: wrap;
367
+ }
368
+
369
+ .opt {
370
+ min-height: 36px;
371
+ padding: 0 12px;
372
+ border-radius: 999px;
373
+ border: 1px solid var(--px-border);
374
+ background: var(--px-surface-2);
375
+ font: inherit;
376
+ font-size: var(--px-fs-s);
377
+ color: var(--px-text);
378
+ cursor: pointer;
379
+ }
380
+
381
+ .opt[aria-pressed="true"] {
382
+ background: var(--px-text);
383
+ color: var(--px-bg);
384
+ border-color: var(--px-text);
385
+ }
386
+
387
+ .opt:disabled {
388
+ opacity: .4;
389
+ cursor: default;
390
+ }
391
+
392
+ .custom,
393
+ .save {
394
+ gap: 8px;
395
+ flex-wrap: wrap;
396
+ }
397
+
398
+ .num {
399
+ width: 72px;
400
+ }
401
+
402
+ .save .px-input {
403
+ flex: 1;
404
+ min-width: 160px;
405
+ }
406
+
407
+ .preview {
408
+ display: grid;
409
+ place-items: center;
410
+ min-height: 180px;
411
+ max-height: 320px;
412
+ border-radius: var(--px-r-m);
413
+ background: var(--px-surface-2);
414
+ overflow: hidden;
415
+ }
416
+
417
+ .preview img {
418
+ max-width: 100%;
419
+ max-height: 320px;
420
+ display: block;
421
+ }
422
+
423
+ .url {
424
+ width: 100%;
425
+ }
426
+
427
+ .text-danger {
428
+ color: var(--px-danger);
429
+ }
430
+
431
+ @media (max-width: 720px) {
432
+ .body {
433
+ grid-template-columns: minmax(0, 1fr);
434
+ }
435
+ }
436
+ </style>