Skip to content

Commit

Permalink
feat: optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
杨国璇 committed Dec 8, 2024
1 parent 6425c0d commit 97fa8e5
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 49 deletions.
17 changes: 16 additions & 1 deletion frontend/src/hooks/metadata-status.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand All @@ -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 => {
Expand All @@ -60,6 +62,7 @@ export const MetadataStatusProvider = ({ repoID, currentRepoInfo, hideMetadataVi
cancelMetadataURL();
setEnableTags(false);
}
setDetailsSettings({});
setIsBeingBuilt(newValue);
setEnableMetadata(newValue);
}, [enableMetadata, cancelMetadataURL]);
Expand All @@ -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 (
<EnableMetadataContext.Provider
value={{
Expand All @@ -85,6 +98,8 @@ export const MetadataStatusProvider = ({ repoID, currentRepoInfo, hideMetadataVi
enableTags,
tagsLang,
updateEnableTags,
detailsSettings,
modifyDetailsSettings,
}}
>
{!isLoading && children}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]);

Expand All @@ -16,6 +18,8 @@ const Settings = () => {
}, [isShowSetter]);
const target = useMemo(() => 'detail-control-settings-btn', []);

if (!enableMetadata) return null;

return (
<>
<div className="detail-control mr-2" id={target} onClick={onSetterToggle}>
Expand Down
76 changes: 34 additions & 42 deletions frontend/src/metadata/hooks/metadata-details.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand All @@ -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) => {
Expand All @@ -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];
Expand All @@ -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);
Expand All @@ -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;
}
Expand All @@ -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);
Expand Down
19 changes: 13 additions & 6 deletions seahub/repo_metadata/apis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.'
Expand All @@ -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):
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions seahub/repo_metadata/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 97fa8e5

Please sign in to comment.