import { Asset } from '../types/Asset'; import { customFields } from '../config'; import { formatDate, formatSize } from '../shared/utils'; import { LabelWithInput } from './LabelWithInput'; import { Modal } from './Modal'; import { DeleteModal } from './DeleteModal'; import client from 'part:@sanity/base/client'; import React, { FormEvent, useState, useEffect } from 'react'; import styled from 'styled-components'; import { Box, Stack, Button, Inline, Badge, Text, Spinner, Flex } from '@sanity/ui'; import { CheckmarkIcon, DocumentIcon, RemoveIcon } from '@sanity/icons'; interface Props { asset: Asset; loading: Boolean; handleError: (error: any) => void; onClose: () => void; onSaveComplete: () => void; setLoading: (value: Boolean) => void; } const StyledInputsContainer = styled.div` padding-right: 8px !important; max-height: 30vh; overflow: hidden scroll; `; export const AssetModal = ({ asset, loading, handleError, onClose, onSaveComplete, setLoading }: Props) => { const { _createdAt, _id, _type, alt, extension, metadata, originalFilename, size, tags, title, url, usedBy } = asset; const { height, width } = metadata?.dimensions || {}; const [isChanged, setIsChanged] = useState(false); const [checkDelete, setCheckDelete] = useState(false); const [localValues, setLocalValues] = useState<{ [key: string]: any }>({ alt, tags: tags?.join(','), title, }); useEffect(() => { customFields.map((field: any) => setLocalValues((values) => ({ ...values, [field.name]: asset[field.name] }))); }, []); const inputFields = [ { name: 'title', label: 'Title', placeholder: 'No title yet' }, { name: 'alt', label: 'Alt text', placeholder: 'No alt text yet' }, { name: 'tags', label: 'Tags', placeholder: 'No tags yet' }, ...customFields, ]; useEffect(() => { const hasChanges = Object.entries(localValues).some(([key, newValue]) => { const currentValue = asset[key]; if (newValue === '' && typeof currentValue === 'undefined') { return false; } return newValue !== currentValue; }); setIsChanged(hasChanges); }, [localValues]); async function handleSubmit(e: FormEvent | null) { try { e?.preventDefault(); if (loading) { return; } setLoading(true); if (!isChanged) { return onClose(); } const tags = localValues.tags?.split(',').map((v: string) => v.trim()); await client .patch(_id) .set({ ...localValues, tags }) .commit(); onSaveComplete(); } catch (e) { handleError(e); } finally { setLoading(false); } } return ( <> {checkDelete ? ( setCheckDelete(false)} handleError={handleError} onDeleteComplete={onSaveComplete} setLoading={setLoading} /> ) : (
{_type === 'sanity.imageAsset' ? ( {alt} ) : ( )} {usedBy && ( <> {usedBy.length === 0 ? ( Unused ) : ( Used by {usedBy.length} document{usedBy.length === 1 ? '' : 's'} )} )} {formatDate(_createdAt)} {width && height && ( {width} x {height}
)} {extension.toUpperCase()}, {formatSize(size)}
{inputFields.map(({ name, ...rest }) => ( setLocalValues({ ...localValues, [name]: value })} value={localValues[name]} {...rest} /> ))}