-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathImagesIndexPage.tsx
671 lines (641 loc) · 20.9 KB
/
ImagesIndexPage.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react"
import {
Button,
Flex,
Input,
Mentions,
Popconfirm,
Popover,
Table,
Upload,
notification,
} from "antd"
import { AdminLayout } from "./AdminLayout.js"
import { AdminAppContext } from "./AdminAppContext.js"
import { DbEnrichedImageWithUserId, DbPlainUser } from "@ourworldindata/types"
import { Timeago } from "./Forms.js"
import { ColumnsType } from "antd/es/table/InternalTable.js"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
faClose,
faRobot,
faSave,
faUpload,
} from "@fortawesome/free-solid-svg-icons"
import { RcFile } from "antd/es/upload/interface.js"
import { CLOUDFLARE_IMAGES_URL } from "../settings/clientSettings.js"
import { Dictionary, keyBy } from "lodash"
import cx from "classnames"
import { NotificationInstance } from "antd/es/notification/interface.js"
type ImageMap = Record<string, DbEnrichedImageWithUserId>
type UserMap = Record<string, DbPlainUser>
type UsageInfo = {
title: string
id: string
}
type ImageEditorApi = {
getUsage: () => void
getAltText: (id: number) => Promise<{ altText: string; success: boolean }>
patchImage: (
image: DbEnrichedImageWithUserId,
patch: Partial<DbEnrichedImageWithUserId>
) => void
putImage: (
id: number,
payload: {
filename: string
content?: string
type: string
}
) => void
postImage: (payload: {
filename: string
content?: string
type: string
}) => void
deleteImage: (image: DbEnrichedImageWithUserId) => void
getImages: () => void
getUsers: () => void
postUserImage: (user: DbPlainUser, image: DbEnrichedImageWithUserId) => void
deleteUserImage: (
user: DbPlainUser,
image: DbEnrichedImageWithUserId
) => void
}
function AltTextEditor({
image,
text,
patchImage,
getAltText,
}: {
image: DbEnrichedImageWithUserId
text: string
patchImage: ImageEditorApi["patchImage"]
getAltText: ImageEditorApi["getAltText"]
}) {
const [value, setValue] = useState(text)
const [shouldAutosize, setShouldAutosize] = useState(false)
const saveAltText = useCallback(() => {
const trimmed = value.trim()
patchImage(image, { defaultAlt: trimmed })
}, [image, patchImage, value])
const handleGetAltText = useCallback(async () => {
const response = await getAltText(image.id)
setValue(response.altText)
// Only autoexpand the textarea if the user generates alt text
setShouldAutosize(true)
}, [image.id, getAltText])
return (
<div className="ImageIndexPage__alt-text-editor">
<textarea
className={cx({
"ImageIndexPage__alt-text-editor--should-autosize":
shouldAutosize,
})}
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<Button onClick={handleGetAltText} type="text">
<FontAwesomeIcon icon={faRobot} />
</Button>
<Button type="text" onClick={saveAltText} disabled={value === text}>
<FontAwesomeIcon icon={faSave} />
</Button>
{value !== text && (
<span className="ImageIndexPage__unsaved-chip">Unsaved</span>
)}
</div>
)
}
function UserSelect({
usersMap,
initialValue = "",
onUserSelect,
}: {
usersMap: UserMap
initialValue?: string
onUserSelect: (user: DbPlainUser) => void
}) {
const [isSetting, setIsSetting] = useState(false)
const { admin } = useContext(AdminAppContext)
const [value, setValue] = useState(initialValue)
const [filteredOptions, setFilteredOptions] = useState(() =>
Object.values(usersMap).map((user) => ({
value: user.fullName,
label: user.fullName,
}))
)
const handleChange = (value: string) => {
setValue(value)
const lowercaseValue = value.toLowerCase()
setFilteredOptions(
Object.values(usersMap)
.filter((user) =>
user.fullName.toLowerCase().includes(lowercaseValue)
)
.map((user) => ({
value: String(user.id),
label: user.fullName,
}))
)
}
const handleSelect = async (option: { value?: string; label?: string }) => {
// iterating because we only have the label when using the admin context
const selectedUser = Object.values(usersMap).find(
(user) => user.fullName === option.label
)
if (selectedUser) {
setValue(selectedUser.fullName)
await onUserSelect(selectedUser)
}
}
if (isSetting) {
return (
<Mentions
prefix=""
autoFocus
allowClear
value={value}
onKeyDown={(e) => {
if (e.key === "Escape") setIsSetting(false)
}}
onChange={handleChange}
onSelect={handleSelect}
options={filteredOptions}
/>
)
}
return (
<div>
<Button
type="text"
onClick={() => handleSelect({ label: admin.username })}
>
+ {admin.username}
</Button>
<Button type="text" onClick={() => setIsSetting(true)}>
+ Someone else
</Button>
</div>
)
}
function UsageViewer({ usage }: { usage: UsageInfo[] | undefined }) {
const content = (
<div>
{usage ? (
<ul className="ImageIndexPage__usage-list">
{usage.map((use) => (
<li key={use.id}>
<a href={`/admin/gdocs/${use.id}/preview`}>
{use.title}
</a>
</li>
))}
</ul>
) : null}
</div>
)
return (
<Popover
content={content}
title="Published posts that reference this image"
trigger="click"
>
<Button type="text" disabled={!usage || !usage.length}>
See usage
{usage ? (
<span className="ImageIndexPage__usage-chip">
{usage.length}
</span>
) : null}
</Button>
</Popover>
)
}
function createColumns({
api,
users,
usage,
notificationApi,
}: {
api: ImageEditorApi
users: UserMap
usage: Dictionary<UsageInfo[]>
notificationApi: NotificationInstance
}): ColumnsType<DbEnrichedImageWithUserId> {
return [
{
title: "Preview",
dataIndex: "cloudflareId",
width: 100,
key: "cloudflareId",
render: (cloudflareId, { originalWidth, originalHeight }) => {
const srcFor = (w: number) =>
`${CLOUDFLARE_IMAGES_URL}/${encodeURIComponent(
cloudflareId
)}/w=${w}`
return (
<div style={{ height: 100, width: 100 }} key={cloudflareId}>
<a
target="_blank"
href={`${srcFor(originalWidth!)}`}
rel="noopener"
>
<img
src={`${srcFor(200)}`}
width="100"
height={
(originalHeight! / originalWidth!) * 100
}
/>
</a>
</div>
)
},
},
{
title: "Filename",
dataIndex: "filename",
key: "filename",
width: 200,
},
{
title: "Alt text",
dataIndex: "defaultAlt",
key: "defaultAlt",
width: "auto",
sorter: (a, b) =>
a.defaultAlt && b.defaultAlt
? a.defaultAlt.localeCompare(b.defaultAlt)
: 0,
render: (text, image) => (
<AltTextEditor
key={image.cloudflareId}
text={text}
image={image}
patchImage={api.patchImage}
getAltText={api.getAltText}
/>
),
},
{
title: "Width",
dataIndex: "originalWidth",
key: "originalWidth",
sorter: (a, b) =>
a.originalWidth && b.originalWidth
? a.originalWidth - b.originalWidth
: 0,
width: 50,
},
{
title: "Height",
dataIndex: "originalHeight",
key: "originalHeight",
sorter: (a, b) =>
a.originalHeight && b.originalHeight
? a.originalHeight - b.originalHeight
: 0,
width: 50,
},
{
title: "Last updated",
dataIndex: "updatedAt",
key: "updatedAt",
width: 50,
defaultSortOrder: "descend",
sorter: (a, b) =>
a.updatedAt && b.updatedAt ? a.updatedAt - b.updatedAt : 0,
render: (time) => <Timeago time={time} />,
},
{
title: "Owner",
key: "userId",
width: 100,
filters: [
{
text: "Unassigned",
value: null as any,
},
...Object.values(users)
.map((user) => ({
text: user.fullName,
value: user.id,
}))
.sort((a, b) => a.text.localeCompare(b.text)),
],
onFilter: (value, record) => record.userId === value,
render: (_, image) => {
const user = users[image.userId]
if (!user)
return (
<UserSelect
usersMap={users}
onUserSelect={(user) =>
api.postUserImage(user, image)
}
/>
)
return (
<div>
{user.fullName}
<button
className="ImageIndexPage__delete-user-button"
onClick={() => api.deleteUserImage(user, image)}
>
<FontAwesomeIcon icon={faClose} />
</button>
</div>
)
},
},
{
title: "Action",
key: "action",
width: 50,
render: (_, image) => {
const isDeleteDisabled = !!(usage && usage[image.id]?.length)
return (
<Flex vertical>
<UsageViewer usage={usage && usage[image.id]} />
<PutImageButton
putImage={api.putImage}
notificationApi={notificationApi}
id={image.id}
/>
<Popconfirm
title="Are you sure?"
description="This will delete the image being used in production."
onConfirm={() => api.deleteImage(image)}
okText="Yes"
cancelText="No"
>
<Button
type="text"
danger
disabled={isDeleteDisabled}
title={
isDeleteDisabled
? "This image is being used in production"
: undefined
}
>
Delete
</Button>
</Popconfirm>
</Flex>
)
},
},
]
}
type File = string | Blob | RcFile
type FileToBase64Result = {
filename: string
content: string
type: string
}
/**
* Uploading as base64, because otherwise we'd need multipart/form-data parsing middleware in the server.
* This seems easier as a one-off.
**/
function fileToBase64(file: File): Promise<FileToBase64Result | null> {
if (typeof file === "string") return Promise.resolve(null)
return new Promise((resolve) => {
const reader = new FileReader()
reader.onload = () => {
resolve({
filename: file.name,
content: reader.result?.toString() ?? "",
type: file.type,
})
}
reader.readAsDataURL(file)
})
}
function PostImageButton({
postImage,
}: {
postImage: ImageEditorApi["postImage"]
}) {
async function uploadImage({ file }: { file: File }) {
const result = await fileToBase64(file)
if (result) {
postImage(result)
}
}
return (
<Upload
accept="image/*"
showUploadList={false}
customRequest={uploadImage}
>
<Button type="primary">
<FontAwesomeIcon icon={faUpload} /> Upload
</Button>
</Upload>
)
}
function PutImageButton({
putImage,
id,
notificationApi,
}: {
putImage: ImageEditorApi["putImage"]
id: number
notificationApi: NotificationInstance
}) {
async function uploadImage({ file }: { file: File }) {
const result = await fileToBase64(file)
if (result) {
await putImage(id, result)
notificationApi.info({
message: "Image replaced!",
description:
"Make sure you update the alt text if your revision has substantive changes",
placement: "bottomRight",
})
}
}
return (
<>
<Upload
accept="image/*"
showUploadList={false}
customRequest={uploadImage}
>
<Button
className="ImageIndexPage__update-image-button"
type="text"
>
Upload new version
</Button>
</Upload>
</>
)
}
const NotificationContext = createContext(null)
export function ImageIndexPage() {
const { admin } = useContext(AdminAppContext)
const [notificationApi, notificationContextHolder] =
notification.useNotification()
const [images, setImages] = useState<ImageMap>({})
const [users, setUsers] = useState<UserMap>({})
const [usage, setUsage] = useState<Dictionary<UsageInfo[]>>({})
const [filenameSearchValue, setFilenameSearchValue] = useState("")
const api = useMemo(
(): ImageEditorApi => ({
getUsage: async () => {
const usage = await admin.requestJSON<{
success: true
usage: Dictionary<UsageInfo[]>
}>(`/api/images/usage`, {}, "GET")
setUsage(usage.usage)
},
getAltText: (id) => {
return admin.requestJSON<{
success: true
altText: string
}>(`/api/gpt/suggest-alt-text/${id}`, {}, "GET")
},
deleteImage: async (image) => {
await admin.requestJSON(`/api/images/${image.id}`, {}, "DELETE")
setImages((prevMap) => {
const newMap = { ...prevMap }
delete newMap[image.id]
return newMap
})
},
getImages: async () => {
const json = await admin.getJSON<{
images: DbEnrichedImageWithUserId[]
}>("/api/images.json")
setImages(keyBy(json.images, "id"))
},
getUsers: async () => {
const json = await admin.getJSON<{ users: DbPlainUser[] }>(
"/api/users.json"
)
setUsers(keyBy(json.users, "id"))
},
patchImage: async (image, patch) => {
const response = await admin.requestJSON<{
success: true
image: DbEnrichedImageWithUserId
}>(`/api/images/${image.id}`, patch, "PATCH")
if (response.success) {
setImages((prevMap) => ({
...prevMap,
[image.id]: response.image,
}))
}
},
postImage: async (image) => {
const response = await admin.requestJSON<{
success: true
image: DbEnrichedImageWithUserId
}>(`/api/images`, image, "POST")
if (response.success) {
setImages((prevMap) => ({
...prevMap,
[response.image.id]: response.image,
}))
}
},
putImage: async (id, payload) => {
const response = await admin.requestJSON<{
success: true
image: DbEnrichedImageWithUserId
}>(`/api/images/${id}`, payload, "PUT")
if (response.success) {
setImages((prevMap) => {
const nextMap = { ...prevMap }
delete nextMap[id]
return {
...nextMap,
[response.image.id]: response.image,
}
})
}
},
postUserImage: async (user, image) => {
const response = await admin.requestJSON(
`/api/users/${user.id}/images/${image.id}`,
{},
"POST"
)
if (response.success) {
setImages((prevMap) => ({
...prevMap,
[image.id]: { ...prevMap[image.id], userId: user.id },
}))
}
},
deleteUserImage: async (user, image) => {
const result = await admin.requestJSON(
`/api/users/${user.id}/images/${image.id}`,
{},
"DELETE"
)
if (result.success) {
setImages((prevMap) => ({
...prevMap,
[image.id]: { ...prevMap[image.id], userId: null },
}))
}
},
}),
[admin]
)
const filteredImages = useMemo(
() =>
Object.values(images).filter((image) =>
image.filename
.toLowerCase()
.includes(filenameSearchValue.toLowerCase())
),
[images, filenameSearchValue]
)
const columns = useMemo(
() => createColumns({ api, users, usage, notificationApi }),
[api, users, usage, notificationApi]
)
useEffect(() => {
void api.getImages()
void api.getUsers()
void api.getUsage()
}, [api])
return (
<AdminLayout title="Images">
<NotificationContext.Provider value={null}>
{notificationContextHolder}
<main className="ImageIndexPage">
<Flex justify="space-between">
<Input
placeholder="Search by filename"
value={filenameSearchValue}
onChange={(e) =>
setFilenameSearchValue(e.target.value)
}
style={{ width: 500, marginBottom: 20 }}
/>
<PostImageButton postImage={api.postImage} />
</Flex>
<Table
size="small"
columns={columns}
dataSource={filteredImages}
rowKey={(x) => x.id}
/>
</main>
</NotificationContext.Provider>
</AdminLayout>
)
}