From 97fa8e52b65561827fc3f461f3081cacf1a7e144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E5=9B=BD=E7=92=87?= Date: Sun, 8 Dec 2024 09:44:48 +0800 Subject: [PATCH] feat: optimize code --- frontend/src/hooks/metadata-status.js | 17 ++++- .../metadata-details/settings/index.js | 4 + .../src/metadata/hooks/metadata-details.js | 76 +++++++++---------- seahub/repo_metadata/apis.py | 19 +++-- seahub/repo_metadata/models.py | 1 + 5 files changed, 68 insertions(+), 49 deletions(-) diff --git a/frontend/src/hooks/metadata-status.js b/frontend/src/hooks/metadata-status.js index 1aad544533d..687f660da6d 100644 --- a/frontend/src/hooks/metadata-status.js +++ b/frontend/src/hooks/metadata-status.js @@ -17,6 +17,7 @@ export const MetadataStatusProvider = ({ repoID, currentRepoInfo, hideMetadataVi const [enableMetadata, setEnableMetadata] = useState(false); const [enableTags, setEnableTags] = useState(false); const [tagsLang, setTagsLang] = useState('en'); + const [detailsSettings, setDetailsSettings] = useState({}); const [isBeingBuilt, setIsBeingBuilt] = useState(false); const cancelMetadataURL = useCallback(() => { @@ -37,12 +38,13 @@ export const MetadataStatusProvider = ({ repoID, currentRepoInfo, hideMetadataVi return; } metadataAPI.getMetadataStatus(repoID).then(res => { - const { enabled: enableMetadata, tags_enabled: enableTags, tags_lang: tagsLang } = res.data; + const { enabled: enableMetadata, tags_enabled: enableTags, tags_lang: tagsLang, details_settings: detailsSettings } = res.data; if (!enableMetadata) { cancelMetadataURL(); } setEnableTags(enableTags); setTagsLang(tagsLang || 'en'); + setDetailsSettings(JSON.parse(detailsSettings)); setEnableMetadata(enableMetadata); setLoading(false); }).catch(error => { @@ -60,6 +62,7 @@ export const MetadataStatusProvider = ({ repoID, currentRepoInfo, hideMetadataVi cancelMetadataURL(); setEnableTags(false); } + setDetailsSettings({}); setIsBeingBuilt(newValue); setEnableMetadata(newValue); }, [enableMetadata, cancelMetadataURL]); @@ -74,6 +77,16 @@ export const MetadataStatusProvider = ({ repoID, currentRepoInfo, hideMetadataVi setTagsLang(lang); }, [enableTags, tagsLang, cancelMetadataURL, hideMetadataView]); + const modifyDetailsSettings = useCallback((update) => { + metadataAPI.modifyMetadataDetailsSettings(repoID, update).then(res => { + const newDetailsSettings = { ...detailsSettings, ...update }; + setDetailsSettings(newDetailsSettings); + }).catch(error => { + const newDetailsSettings = { ...detailsSettings, ...update }; + setDetailsSettings(newDetailsSettings); + }); + }, [repoID, detailsSettings]); + return ( {!isLoading && children} diff --git a/frontend/src/metadata/components/metadata-details/settings/index.js b/frontend/src/metadata/components/metadata-details/settings/index.js index c850f5b8c1e..a62ccf6b739 100644 --- a/frontend/src/metadata/components/metadata-details/settings/index.js +++ b/frontend/src/metadata/components/metadata-details/settings/index.js @@ -2,12 +2,14 @@ import React, { useMemo, useCallback, useState } from 'react'; import Icon from '../../../../components/icon'; import HideColumnPopover from '../../popover/hidden-column-popover'; import { useMetadataDetails } from '../../../hooks'; +import { useMetadataStatus } from '../../../../hooks'; import './index.css'; const Settings = () => { const [isShowSetter, setShowSetter] = useState(false); + const { enableMetadata } = useMetadataStatus(); const { modifyColumnOrder, modifyHiddenColumns, columns } = useMetadataDetails(); const hiddenColumns = useMemo(() => columns.filter(c => !c.shown).map(c => c.key), [columns]); @@ -16,6 +18,8 @@ const Settings = () => { }, [isShowSetter]); const target = useMemo(() => 'detail-control-settings-btn', []); + if (!enableMetadata) return null; + return ( <>
diff --git a/frontend/src/metadata/hooks/metadata-details.js b/frontend/src/metadata/hooks/metadata-details.js index e4d1c102292..0cdb3e9a1c6 100644 --- a/frontend/src/metadata/hooks/metadata-details.js +++ b/frontend/src/metadata/hooks/metadata-details.js @@ -12,22 +12,41 @@ import { getCellValueByColumn, getOptionName, getColumnOptionNamesByIds, getColu } from '../utils/cell'; import tagsAPI from '../../tag/api'; import { getColumnByKey, getColumnOptions, getColumnOriginName } from '../utils/column'; -import LocalStorage from '../utils/local-storage'; const MetadataDetailsContext = React.createContext(null); export const MetadataDetailsProvider = ({ repoID, repoInfo, path, dirent, direntDetail, direntType, children }) => { + const { enableMetadata, detailsSettings, modifyDetailsSettings } = useMetadataStatus(); + const [isLoading, setLoading] = useState(true); const [record, setRecord] = useState(null); - const [columns, setColumns] = useState([]); + const [originColumns, setOriginColumns] = useState([]); const permission = useMemo(() => repoInfo.permission !== 'admin' && repoInfo.permission !== 'rw' ? 'r' : 'rw', [repoInfo]); const allColumnsRef = useRef([]); - const localStorageRef = useRef(null); - const localStorageKeyRef = useRef('properties'); - const { enableMetadata } = useMetadataStatus(); + const columns = useMemo(() => { + const orderAndHiddenColumns = detailsSettings?.columns || []; + if (!Array.isArray(orderAndHiddenColumns) || orderAndHiddenColumns.length === 0) { + return originColumns.map(c => ({ ...c, shown: true })); + } + const oldColumnsMap = orderAndHiddenColumns.reduce((pre, cur) => { + pre[cur.key] = true; + return pre; + }, {}); + const columnsMap = originColumns.reduce((pre, cur) => { + pre[cur.key] = cur; + return pre; + }, {}); + const exitColumnsOrder = orderAndHiddenColumns.map(c => { + const column = columnsMap[c.key]; + if (column) return { ...c, ...column }; + return null; + }).filter(c => c); + const newColumns = originColumns.filter(c => !oldColumnsMap[c.key]).map(c => ({ ...c, shown: false })); + return [...exitColumnsOrder, ...newColumns]; + }, [originColumns, detailsSettings]); const localRecordChanged = useCallback((recordId, updates) => { if (getRecordIdFromRecord(record) !== recordId) return; @@ -36,7 +55,7 @@ export const MetadataDetailsProvider = ({ repoID, repoInfo, path, dirent, dirent }, [record]); const onChange = useCallback((fieldKey, newValue) => { - const field = getColumnByKey(columns, fieldKey); + const field = getColumnByKey(originColumns, fieldKey); const fileName = getColumnOriginName(field); const recordId = getRecordIdFromRecord(record); const fileObjId = getFileObjIdFromRecord(record); @@ -55,14 +74,14 @@ export const MetadataDetailsProvider = ({ repoID, repoInfo, path, dirent, dirent const errorMsg = Utils.getErrorMsg(error); toaster.danger(errorMsg); }); - }, [repoID, record, columns]); + }, [repoID, record, originColumns]); const modifyColumnData = useCallback((fieldKey, newData) => { - let newColumns = columns.slice(0); + let newColumns = originColumns.slice(0); let update; metadataAPI.modifyColumnData(repoID, fieldKey, newData).then(res => { const newColumn = new Column(res.data.column); - const fieldIndex = columns.findIndex(f => f.key === fieldKey); + const fieldIndex = originColumns.findIndex(f => f.key === fieldKey); newColumns[fieldIndex] = newColumn; return newColumn; }).then((newField) => { @@ -78,13 +97,13 @@ export const MetadataDetailsProvider = ({ repoID, repoInfo, path, dirent, dirent } return metadataAPI.modifyRecord(repoID, record._id, update, record._obj_id); }).then(res => { - setColumns(newColumns); + setOriginColumns(newColumns); setRecord({ ...record, ...update }); }).catch(error => { const errorMsg = Utils.getErrorMsg(error); toaster.danger(errorMsg); }); - }, [repoID, record, columns]); + }, [repoID, record, originColumns]); const updateFileTags = useCallback((updateRecords) => { const { record_id, tags } = updateRecords[0]; @@ -102,35 +121,9 @@ export const MetadataDetailsProvider = ({ repoID, repoInfo, path, dirent, dirent }); }, [repoID, record]); - const initColumns = useCallback((columns) => { - const orderAndHiddenColumns = localStorageRef.current.getItem(localStorageKeyRef.current); - if (!Array.isArray(orderAndHiddenColumns) || orderAndHiddenColumns.length === 0) { - const newColumns = columns.map(c => ({ ...c, shown: true })); - setColumns(newColumns); - return; - } - const oldColumnsMap = orderAndHiddenColumns.reduce((pre, cur) => { - pre[cur.key] = true; - return pre; - }, {}); - const columnsMap = columns.reduce((pre, cur) => { - pre[cur.key] = cur; - return pre; - }, {}); - const exitColumnsOrder = orderAndHiddenColumns.map(c => { - const column = columnsMap[c.key]; - if (column) return { ...c, ...column }; - return null; - }).filter(c => c); - const newColumns = columns.filter(c => !oldColumnsMap[c.key]).map(c => ({ ...c, shown: false })); - setColumns([...exitColumnsOrder, ...newColumns]); - }, []); - const saveColumns = useCallback((columns) => { - setColumns(columns); - const saveValue = columns.map(c => ({ key: c.key, shown: c.shown })); - localStorageRef.current.setItem(localStorageKeyRef.current, saveValue); - }, []); + modifyDetailsSettings({ columns: columns.map(c => ({ key: c.key, shown: c.shown })) }); + }, [modifyDetailsSettings]); const modifyHiddenColumns = useCallback((hiddenColumns) => { let newColumns = columns.slice(0); @@ -151,7 +144,7 @@ export const MetadataDetailsProvider = ({ repoID, repoInfo, path, dirent, dirent setLoading(true); if (!dirent || !direntDetail || !enableMetadata || SYSTEM_FOLDERS.find(folderPath => path.startsWith(folderPath))) { setRecord(null); - setColumns([]); + setOriginColumns([]); setLoading(false); return; } @@ -169,8 +162,7 @@ export const MetadataDetailsProvider = ({ repoID, repoInfo, path, dirent, dirent const columns = normalizeFields(metadata).map(field => new Column(field)); allColumnsRef.current = columns; setRecord(record); - localStorageRef.current = new LocalStorage(`sf-metadata-detail-settings-${repoID}`); - initColumns(columns); + setOriginColumns(columns); setLoading(false); }).catch(error => { const errMessage = Utils.getErrorMsg(error); diff --git a/seahub/repo_metadata/apis.py b/seahub/repo_metadata/apis.py index 9d51f0ea658..7f0a58d9147 100644 --- a/seahub/repo_metadata/apis.py +++ b/seahub/repo_metadata/apis.py @@ -69,7 +69,7 @@ def get(self, request, repo_id): 'enabled': is_enabled, 'tags_enabled': is_tags_enabled, 'tags_lang': tags_lang, - 'details_settings': json.dumps(details_settings) + 'details_settings': details_settings }) def put(self, request, repo_id): @@ -168,7 +168,7 @@ class MetadataDetailsSettingsView(APIView): permission_classes = (IsAuthenticated, ) throttle_classes = (UserRateThrottle, ) - def pu(self, request, repo_id): + def put(self, request, repo_id): settings = request.data.get('settings_data', {}) if not settings: error_msg = 'settings invalid.' @@ -177,7 +177,7 @@ def pu(self, request, repo_id): # resource check repo = seafile_api.get_repo(repo_id) if not repo: - error_msg = 'Library %s not found.' % repo_id + error_msg = f'Library {repo_id} not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) if not is_repo_admin(request.user.username, repo_id): @@ -190,13 +190,20 @@ def pu(self, request, repo_id): return api_error(status.HTTP_404_NOT_FOUND, error_msg) old_details_settings = metadata.details_settings + print('old_details_settings: ', old_details_settings) if not old_details_settings: old_details_settings = '{}' old_details_settings = json.loads(old_details_settings) - - details_settings = old_details_settings.update(settings) + if not old_details_settings: + old_details_settings = {} + + + print('old_details_settings: ', old_details_settings) + print('settings: ', settings) + + old_details_settings.update(settings) try: - metadata.details_settings = json.dumps(details_settings) + metadata.details_settings = json.dumps(old_details_settings) metadata.save() except Exception as e: logger.exception(e) diff --git a/seahub/repo_metadata/models.py b/seahub/repo_metadata/models.py index d2ed47b3587..c991be4084a 100644 --- a/seahub/repo_metadata/models.py +++ b/seahub/repo_metadata/models.py @@ -67,6 +67,7 @@ class RepoMetadata(models.Model): tags_enabled = models.BooleanField(db_index=True) tags_lang = models.CharField(max_length=36) last_face_cluster_time = models.DateTimeField(db_index=True, blank=True, null=True) + details_settings = models.TextField() objects = RepoMetadataManager()