File size: 7,001 Bytes
4e1096a | 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 | import { useEffect, useState } from 'react';
import { BookMetadata } from '@/libs/document';
import {
validateAndNormalizeDate,
validateAndNormalizeLanguage,
validateAndNormalizeSubjects,
validateISBN,
ValidationResult,
} from '@/utils/validation';
import { MetadataSource } from './SourceSelector';
import { searchMetadata } from '@/libs/metadata';
import { formatAuthors, formatTitle, getPrimaryLanguage } from '@/utils/book';
export const useMetadataEdit = (metadata: BookMetadata | null) => {
const [editedMeta, setEditedMeta] = useState<BookMetadata>({} as BookMetadata);
const [fieldSources, setFieldSources] = useState<Record<string, string>>({});
const [lockedFields, setLockedFields] = useState<Record<string, boolean>>({});
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [searchLoading, setSearchLoading] = useState(false);
const [showSourceSelection, setShowSourceSelection] = useState(false);
const [availableSources, setAvailableSources] = useState<MetadataSource[]>([]);
const lockableFields = [
'title',
'author',
'publisher',
'published',
'language',
'identifier',
'subject',
'description',
'subtitle',
'series',
'seriesIndex',
'seriesTotal',
'coverImageUrl',
];
useEffect(() => {
if (metadata) {
setEditedMeta({ ...metadata });
}
}, [metadata]);
useEffect(() => {
const initialLockedFields: Record<string, boolean> = {};
lockableFields.forEach((field) => {
initialLockedFields[field] = false;
});
setLockedFields(initialLockedFields);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleFieldChange = (field: string, value: string | undefined) => {
if (lockedFields[field]) {
return;
}
setEditedMeta((prevMeta) => {
const newMeta = { ...prevMeta } as { [key: string]: unknown };
switch (field) {
case 'subject':
newMeta['subject'] = value ? value.split(/,|;|,|、/).map((s) => s.trim()) : [];
break;
default:
newMeta[field] = value;
}
return newMeta as BookMetadata;
});
if (value !== undefined) {
handleFieldValidation(field, value);
}
if (fieldSources[field]) {
setFieldSources((prevSources) => {
const newSources = { ...prevSources };
delete newSources[field];
return newSources;
});
}
};
const handleFieldValidation = (field: string, value: string) => {
if (lockedFields[field]) {
return true;
}
let validationResult: ValidationResult<unknown>;
switch (field) {
case 'title':
case 'author':
if (!value.trim()) {
console.warn(`Field ${field} cannot be empty`);
setFieldErrors((prev) => ({ ...prev, [field]: 'This field is required' }));
return false;
}
break;
case 'published':
if (value.trim()) {
validationResult = validateAndNormalizeDate(value);
if (!validationResult.isValid) {
console.warn(`Invalid date for field ${field}:`, validationResult.error);
setFieldErrors((prev) => ({ ...prev, [field]: validationResult.error || '' }));
return false;
}
}
break;
case 'language':
if (value.trim()) {
validationResult = validateAndNormalizeLanguage(value);
if (!validationResult.isValid) {
console.warn(`Invalid language for field ${field}:`, validationResult.error);
setFieldErrors((prev) => ({ ...prev, [field]: validationResult.error || '' }));
return false;
}
}
break;
case 'subject':
if (value.trim()) {
validationResult = validateAndNormalizeSubjects(value);
if (!validationResult.isValid) {
console.warn(`Invalid subjects for field ${field}:`, validationResult.error);
setFieldErrors((prev) => ({ ...prev, [field]: validationResult.error || '' }));
return false;
}
}
break;
}
setFieldErrors((prev) => {
const newErrors = { ...prev };
delete newErrors[field];
return newErrors;
});
return true;
};
const handleToggleFieldLock = (field: string) => {
setLockedFields((prev) => ({
...prev,
[field]: !prev[field],
}));
};
const handleLockAll = () => {
const allLocked: Record<string, boolean> = {};
lockableFields.forEach((field) => {
allLocked[field] = true;
});
setLockedFields(allLocked);
};
const handleUnlockAll = () => {
const allUnlocked: Record<string, boolean> = {};
lockableFields.forEach((field) => {
allUnlocked[field] = false;
});
setLockedFields(allUnlocked);
};
const handleAutoRetrieve = async () => {
setSearchLoading(true);
try {
const isbnValidation = validateISBN(editedMeta.identifier || '');
const results = await searchMetadata({
title: formatTitle(editedMeta.title),
author: formatAuthors(editedMeta.author),
isbn: isbnValidation.isValid ? editedMeta.identifier : undefined,
language: getPrimaryLanguage(editedMeta.language),
});
const metadataSources = results.map((result) => ({
sourceName: result.providerName,
sourceLabel: result.providerLabel,
confidence: result.confidence,
data: result.metadata as BookMetadata,
}));
setAvailableSources(metadataSources);
setShowSourceSelection(true);
} catch (error) {
console.error('Failed to retrieve metadata:', error);
} finally {
setSearchLoading(false);
}
};
const handleSourceSelection = (selectedSource: MetadataSource) => {
const newMeta = { ...editedMeta } as { [key: string]: unknown };
const newSources = { ...fieldSources };
Object.entries(selectedSource.data).forEach(([key, value]) => {
if (lockedFields[key] || !value) {
return;
}
switch (key) {
default:
newMeta[key] = value;
}
newSources[key] = `${selectedSource.sourceName}-${selectedSource.confidence}`;
});
setEditedMeta(newMeta as BookMetadata);
setFieldSources(newSources);
setShowSourceSelection(false);
};
const handleCloseSourceSelection = () => {
setShowSourceSelection(false);
};
const resetToOriginal = () => {
if (metadata) {
setEditedMeta({ ...metadata });
}
setFieldSources({});
setShowSourceSelection(false);
handleUnlockAll();
};
return {
editedMeta,
fieldSources,
lockedFields,
fieldErrors,
searchLoading,
showSourceSelection,
availableSources,
handleFieldChange,
handleFieldValidation,
handleToggleFieldLock,
handleLockAll,
handleUnlockAll,
handleAutoRetrieve,
handleSourceSelection,
handleCloseSourceSelection,
resetToOriginal,
};
};
|