Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎉 Cloudflare images authors #4238

Merged
merged 7 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
227 changes: 205 additions & 22 deletions adminSiteClient/ImagesIndexPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,54 @@ import React, {
useMemo,
useState,
} from "react"
import { Button, Flex, Input, Popconfirm, Space, Table, Upload } from "antd"

import {
Button,
Flex,
Input,
Mentions,
Popconfirm,
Space,
Table,
Upload,
} from "antd"
import { AdminLayout } from "./AdminLayout.js"
import { AdminAppContext } from "./AdminAppContext.js"
import { DbEnrichedImage } from "@ourworldindata/types"
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 { faUpload } from "@fortawesome/free-solid-svg-icons"
import { faClose, faUpload } from "@fortawesome/free-solid-svg-icons"
import { Admin } from "./Admin.js"
import { RcFile } from "antd/es/upload/interface.js"
import TextArea from "antd/es/input/TextArea.js"
import { CLOUDFLARE_IMAGES_URL } from "../settings/clientSettings.js"
import { keyBy } from "lodash"

type ImageMap = Record<string, DbEnrichedImageWithUserId>

type UserMap = Record<string, DbPlainUser>

type ImageEditorApi = {
patchImage: (
image: DbEnrichedImage,
patch: Partial<DbEnrichedImage>
image: DbEnrichedImageWithUserId,
patch: Partial<DbEnrichedImageWithUserId>
) => void
deleteImage: (image: DbEnrichedImage) => 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,
}: {
image: DbEnrichedImage
image: DbEnrichedImageWithUserId
text: string
patchImage: ImageEditorApi["patchImage"]
}) {
Expand All @@ -59,11 +78,87 @@ function AltTextEditor({
)
}

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 }) => {
const selectedUser = usersMap[option.value!]
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({ value: admin.username })}
>
+ {admin.username}
</Button>
<Button type="text" onClick={() => setIsSetting(true)}>
+ Someone else
</Button>
</div>
)
}

function createColumns({
api,
users,
}: {
api: ImageEditorApi
}): ColumnsType<DbEnrichedImage> {
users: UserMap
}): ColumnsType<DbEnrichedImageWithUserId> {
return [
{
title: "Preview",
Expand All @@ -72,7 +167,9 @@ function createColumns({
key: "cloudflareId",
render: (cloudflareId, { originalWidth }) => {
const srcFor = (w: number) =>
`${CLOUDFLARE_IMAGES_URL}/${encodeURIComponent(cloudflareId)}/w=${w}`
`${CLOUDFLARE_IMAGES_URL}/${encodeURIComponent(
cloudflareId
)}/w=${w}`
return (
<div style={{ height: 100, width: 100 }} key={cloudflareId}>
<a
Expand Down Expand Up @@ -142,6 +239,47 @@ function createColumns({
a.updatedAt && b.updatedAt ? a.updatedAt - b.updatedAt : 0,
render: (time) => <Timeago time={time} />,
},
{
title: "Owner",
key: "userId",
width: 200,
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",
Expand Down Expand Up @@ -169,7 +307,7 @@ function ImageUploadButton({
setImages,
admin,
}: {
setImages: React.Dispatch<React.SetStateAction<DbEnrichedImage[]>>
setImages: React.Dispatch<React.SetStateAction<ImageMap>>
admin: Admin
}) {
function uploadImage({ file }: { file: string | Blob | RcFile }) {
Expand All @@ -187,10 +325,13 @@ function ImageUploadButton({

const { image } = await admin.requestJSON<{
sucess: true
image: DbEnrichedImage
image: DbEnrichedImageWithUserId
}>("/api/image", payload, "POST")

setImages((images) => [image, ...images])
setImages((imagesMap) => ({
...imagesMap,
[image.id]: image,
}))
}
reader.readAsDataURL(file)
}
Expand All @@ -205,45 +346,87 @@ function ImageUploadButton({

export function ImageIndexPage() {
const { admin } = useContext(AdminAppContext)
const [images, setImages] = useState<DbEnrichedImage[]>([])
const [images, setImages] = useState<ImageMap>({})
const [users, setUsers] = useState<UserMap>({})
const [filenameSearchValue, setFilenameSearchValue] = useState("")

const api = useMemo(
(): ImageEditorApi => ({
deleteImage: async (image) => {
await admin.requestJSON(`/api/images/${image.id}`, {}, "DELETE")
setImages((images) => images.filter((i) => i.id !== image.id))
setImages((prevMap) => {
const newMap = { ...prevMap }
delete newMap[image.id]
return newMap
})
},
getImages: async () => {
const json = await admin.getJSON<{
images: DbEnrichedImage[]
images: DbEnrichedImageWithUserId[]
}>("/api/images.json")
setImages(json.images)
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: DbEnrichedImage
image: DbEnrichedImageWithUserId
}>(`/api/images/${image.id}`, patch, "PATCH")
setImages((images) =>
images.map((i) => (i.id === image.id ? response.image : i))
setImages((prevMap) => ({
...prevMap,
[image.id]: response.image,
}))
},
postUserImage: async (user, image) => {
const result = await admin.requestJSON(
`/api/users/${user.id}/image/${image.id}`,
{},
"POST"
)
if (result.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}/image/${image.id}`,
{},
"DELETE"
)
if (result.success) {
setImages((prevMap) => ({
...prevMap,
[image.id]: { ...prevMap[image.id], userId: null },
}))
}
},
}),
[admin]
)

const filteredImages = useMemo(
() =>
images.filter((image) =>
Object.values(images).filter((image) =>
image.filename
.toLowerCase()
.includes(filenameSearchValue.toLowerCase())
),
[images, filenameSearchValue]
)
const columns = useMemo(() => createColumns({ api }), [api])

const columns = useMemo(() => createColumns({ api, users }), [api, users])

useEffect(() => {
void api.getImages()
void api.getUsers()
}, [api])

return (
Expand Down
13 changes: 13 additions & 0 deletions adminSiteClient/admin.scss
Original file line number Diff line number Diff line change
Expand Up @@ -1207,3 +1207,16 @@ main:not(.ChartEditorPage):not(.GdocsEditPage) {
display: block;
}
}

.ImageIndexPage {
.ImageIndexPage__delete-user-button {
border-radius: 50%;
margin-left: 8px;
height: 16px;
font-size: 0.8em;
align-items: center;
display: inline-flex;
width: 16px;
vertical-align: -2px;
}
}
Loading
Loading