Skip to content

Commit

Permalink
store generation refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
SKarolFolio committed Dec 11, 2024
1 parent 501d6d7 commit 0c2aec4
Show file tree
Hide file tree
Showing 24 changed files with 267 additions and 156 deletions.
4 changes: 2 additions & 2 deletions src/common/hooks/useCommonStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { UserNotificationFactory } from '@common/services/userNotification';
import { useStatusState } from '@src/store';

export const useCommonStatus = () => {
const { addStatusMessage } = useStatusState();
const { addStatusMessagesItem } = useStatusState();

return {
set: (l10nId: string, type: StatusType) => {
addStatusMessage?.(UserNotificationFactory.createMessage(type, l10nId));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(type, l10nId));
},
};
};
4 changes: 2 additions & 2 deletions src/common/hooks/useFetchSearchData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const useFetchSearchData = () => {
} = useSearchContext();
const { setIsLoading } = useLoadingState();
const { setMessage, data, setData, resetData, setPageMetadata } = useSearchState();
const { addStatusMessage, resetStatusMessages } = useStatusState();
const { addStatusMessagesItem, resetStatusMessages } = useStatusState();

const validateAndNormalizeQuery = useCallback(
(type: SearchIdentifiers, query: string) => {
Expand Down Expand Up @@ -177,7 +177,7 @@ export const useFetchSearchData = () => {
setData(content);
setPageMetadata({ totalPages, totalElements: totalRecords, prev, next });
} catch {
addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
} finally {
setIsLoading(false);
}
Expand Down
4 changes: 2 additions & 2 deletions src/common/hooks/useMarcData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useLoadingState, useStatusState } from '@src/store';

export const useMarcData = (setMarcPreviewData: (value: any) => void) => {
const { setIsLoading } = useLoadingState();
const { addStatusMessage } = useStatusState();
const { addStatusMessagesItem } = useStatusState();

const fetchMarcData = async (recordId?: string, endpointUrl?: string): Promise<MarcDTO | undefined> => {
if (!recordId) return undefined;
Expand All @@ -19,7 +19,7 @@ export const useMarcData = (setMarcPreviewData: (value: any) => void) => {

setMarcPreviewData(marcData);
} catch (error) {
addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantLoadMarc'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantLoadMarc'));
} finally {
setIsLoading(false);
}
Expand Down
6 changes: 3 additions & 3 deletions src/common/hooks/useProcessedRecordAndSchema.hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type IGetProcessedRecordAndSchema = {
};

export const useProcessedRecordAndSchema = () => {
const { addStatusMessage } = useStatusState();
const { addStatusMessagesItem } = useStatusState();
const { setRecord } = useInputsState();
const { formatMessage } = useIntl();
const { userValuesService, schemaWithDuplicatesService, recordNormalizingService, recordToSchemaMappingService } =
Expand Down Expand Up @@ -72,7 +72,7 @@ export const useProcessedRecordAndSchema = () => {
} catch (error) {
console.error(error);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorLoadingResource'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorLoadingResource'));
}

return {
Expand All @@ -87,7 +87,7 @@ export const useProcessedRecordAndSchema = () => {
recordToSchemaMappingService,
schemaWithDuplicatesService,
setRecord,
addStatusMessage,
addStatusMessagesItem,
userValuesService,
],
);
Expand Down
18 changes: 9 additions & 9 deletions src/common/hooks/useRecordControls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const useRecordControls = () => {
const { setSelectedProfile } = useProfileState();
const { setIsDuplicateImportedResourceModalOpen, setCurrentlyEditedEntityBfid, setCurrentlyPreviewedEntityBfid } =
useUIState();
const { setRecordStatus, setLastSavedRecordId, setIsEditedRecord: setIsEdited, addStatusMessage } = useStatusState();
const { setRecordStatus, setLastSavedRecordId, setIsEditedRecord: setIsEdited, addStatusMessagesItem } = useStatusState();
const profile = PROFILE_BFIDS.MONOGRAPH;
const currentRecordId = getRecordId(record);
const { getProfiles } = useConfig();
Expand Down Expand Up @@ -124,7 +124,7 @@ export const useRecordControls = () => {
dispatchUnblockEvent();
!asRefToNewRecord && setRecord(parsedResponse);

addStatusMessage?.(
addStatusMessagesItem?.(
UserNotificationFactory.createMessage(StatusType.success, recordId ? 'ld.rdUpdateSuccess' : 'ld.rdSaveSuccess'),
);

Expand Down Expand Up @@ -171,7 +171,7 @@ export const useRecordControls = () => {
} catch (error) {
console.error('Cannot save the resource description', error);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantSaveRd'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantSaveRd'));
} finally {
setIsLoading(false);
}
Expand Down Expand Up @@ -207,13 +207,13 @@ export const useRecordControls = () => {
await deleteRecordRequest(currentRecordId as unknown as string);
deleteRecordLocally(profile, currentRecordId as unknown as string);
discardRecord();
addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.success, 'ld.rdDeleted'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.success, 'ld.rdDeleted'));

navigate(ROUTES.SEARCH.uri);
} catch (error) {
console.error('Cannot delete the resource description', error);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantDeleteRd'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantDeleteRd'));
}
};

Expand All @@ -224,7 +224,7 @@ export const useRecordControls = () => {
const contents = record?.resource?.[uriSelector];

if (!contents) {
addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantSelectReferenceContents'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantSelectReferenceContents'));

return navigate(ROUTES.RESOURCE_CREATE.uri);
}
Expand All @@ -244,7 +244,7 @@ export const useRecordControls = () => {
} catch (e) {
console.error('Error fetching record and selecting entity values: ', e);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
}
};

Expand All @@ -262,7 +262,7 @@ export const useRecordControls = () => {

return recordData;
} catch (_err) {
addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, errorMessage ?? 'ld.errorFetching'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, errorMessage ?? 'ld.errorFetching'));
}
};

Expand All @@ -289,7 +289,7 @@ export const useRecordControls = () => {
if (checkHasErrorOfCodeType(err as ApiError, ApiErrorCodes.AlreadyExists)) {
setIsDuplicateImportedResourceModalOpen(true);
} else {
addStatusMessage?.(
addStatusMessagesItem?.(
UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetchingExternalResourceForEditing'),
);
}
Expand Down
6 changes: 3 additions & 3 deletions src/common/hooks/useSearchFiltersData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const DEFAULT_SEARCH_FACETS_QUERY = 'id=*';
export const useSearchFiltersData = () => {
const { selectedFacetsGroups, setSelectedFacetsGroups, resetSelectedFacetsGroups, setFacetsData, setSourceData } =
useSearchState();
const { addStatusMessage } = useStatusState();
const { addStatusMessagesItem } = useStatusState();

useEffect(() => {
return resetSelectedFacetsGroups();
Expand All @@ -37,7 +37,7 @@ export const useSearchFiltersData = () => {
} catch (error) {
console.error(error);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
}
};

Expand All @@ -56,7 +56,7 @@ export const useSearchFiltersData = () => {
} catch (error) {
console.error(error);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
}
};

Expand Down
4 changes: 2 additions & 2 deletions src/components/EditSection/EditSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const EditSection = memo(() => {
const { selectedEntriesService } = useServicesContext() as Required<ServicesParams>;
const { selectedProfile, initialSchemaKey } = useProfileState();
const resourceTemplates = selectedProfile?.json.Profile.resourceTemplates;
const { userValues, addUserValues, selectedRecordBlocks, record, selectedEntries, setSelectedEntries } =
const { userValues, addUserValuesItem, selectedRecordBlocks, record, selectedEntries, setSelectedEntries } =
useInputsState();
const { isEditedRecord: isEdited, setIsEditedRecord: setIsEdited } = useStatusState();
const { collapsedEntries, setCollapsedEntries, collapsibleEntries, currentlyEditedEntityBfid } = useUIState();
Expand Down Expand Up @@ -50,7 +50,7 @@ export const EditSection = memo(() => {

const debouncedAddUserValues = useRef(
debounce((value: UserValues) => {
addUserValues?.(value);
addUserValuesItem?.(value);
}, USER_INPUT_DELAY),
).current;

Expand Down
4 changes: 2 additions & 2 deletions src/components/SearchResultEntry/SearchResultEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export const SearchResultEntry: FC<SearchResultEntry> = ({ instances, ...restOfW
const { navigationState } = useSearchState();
const [isOpen, setIsOpen] = useState(true);
const { setIsLoading } = useLoadingState();
const { addStatusMessage } = useStatusState();
const { addStatusMessagesItem } = useStatusState();
const { previewContent } = useInputsState();
const toggleIsOpen = () => setIsOpen(!isOpen);
const { fetchRecord } = useRecordControls();
Expand All @@ -72,7 +72,7 @@ export const SearchResultEntry: FC<SearchResultEntry> = ({ instances, ...restOfW
} catch (error) {
console.error(error);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'));
} finally {
setIsLoading(false);
}
Expand Down
4 changes: 2 additions & 2 deletions src/components/SimpleLookupField/SimpleLookupField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const SimpleLookupField: FC<Props> = ({
const { getLookupData, loadLookupData } = useSimpleLookupData();
const loadedOptions = getLookupData()?.[uri] || [];
const options = filterLookupOptionsByParentBlock(loadedOptions, propertyUri, parentBlockUri);
const { addStatusMessage } = useStatusState();
const { addStatusMessagesItem } = useStatusState();
const { simpleLookupRef, forceDisplayOptionsAtTheTop } = useSimpleLookupObserver();

const [localValue, setLocalValue] = useState<MultiselectOption[]>(
Expand All @@ -65,7 +65,7 @@ export const SimpleLookupField: FC<Props> = ({
} catch (error) {
console.error('Cannot load data for the Lookup:', error);

addStatusMessage?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantLoadSimpleLookupData'));
addStatusMessagesItem?.(UserNotificationFactory.createMessage(StatusType.error, 'ld.cantLoadSimpleLookupData'));
} finally {
setIsLoading(false);
}
Expand Down
25 changes: 14 additions & 11 deletions src/store/stores/config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { LOCALES } from '@common/i18n/locales';
import { OKAPI_CONFIG } from '@common/constants/api.constants';
import { localStorageService } from '@common/services/storage';
import { createBaseSlice, SliceState } from '../utils/slice';
import { generateStore, type StateCreatorTyped } from '../utils/storeCreator';
import { type SliceState } from '../utils/slice';
import { createStoreFactory, type SliceConfigs } from '../utils/createStoreFactory';

type Locale = (typeof LOCALES)[keyof typeof LOCALES];
type CustomEvents = Record<string, string> | null;
Expand All @@ -13,13 +13,16 @@ export type ConfigState = SliceState<'locale', Locale> &

const STORE_NAME = 'Config';

const configStore: StateCreatorTyped<ConfigState> = (...args) => ({
...createBaseSlice(
{ basic: 'locale' },
localStorageService.deserialize(OKAPI_CONFIG)?.locale || LOCALES.ENGLISH_US,
)(...args),
...createBaseSlice({ basic: 'customEvents' }, null as CustomEvents)(...args),
...createBaseSlice({ basic: 'hasNavigationOrigin' }, false)(...args),
});
const sliceConfigs: SliceConfigs = {
locale: {
initialValue: localStorageService.deserialize(OKAPI_CONFIG)?.locale || LOCALES.ENGLISH_US,
},
customEvents: {
initialValue: null as CustomEvents,
},
hasNavigationOrigin: {
initialValue: false,
},
};

export const useConfigStore = generateStore(configStore, STORE_NAME);
export const useConfigStore = createStoreFactory<ConfigState, SliceConfigs>(sliceConfigs, STORE_NAME);
32 changes: 22 additions & 10 deletions src/store/stores/inputs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createBaseSlice, SliceState } from '../utils/slice';
import { generateStore, type StateCreatorTyped } from '../utils/storeCreator';
import { createStoreFactory, type SliceConfigs } from '../utils/createStoreFactory';
import { type SliceState } from '../utils/slice';

export type RecordState = RecordEntry | null;
export type SelectedRecordBlocksState = SelectedRecordBlocks | undefined;
Expand All @@ -13,12 +13,24 @@ export type InputsState = SliceState<'userValues', UserValues> &

const STORE_NAME = 'Inputs';

const inputsStore: StateCreatorTyped<InputsState> = (...args) => ({
...createBaseSlice({ basic: 'userValues' }, {} as UserValues, true)(...args),
...createBaseSlice({ basic: 'previewContent' }, [] as PreviewContent[])(...args),
...createBaseSlice({ basic: 'record' }, null as RecordState)(...args),
...createBaseSlice({ basic: 'selectedRecordBlocks' }, undefined as SelectedRecordBlocksState)(...args),
...createBaseSlice({ basic: 'selectedEntries' }, [] as SelectedEntriesState)(...args),
});
const sliceConfigs: SliceConfigs = {
userValues: {
initialValue: {},
canAddSingleItem: true,
singleItem: { type: {} as UserValue },
},
previewContent: {
initialValue: [],
},
record: {
initialValue: null,
},
selectedRecordBlocks: {
initialValue: undefined,
},
selectedEntries: {
initialValue: [],
},
};

export const useInputsStore = generateStore(inputsStore, STORE_NAME);
export const useInputsStore = createStoreFactory<InputsState, SliceConfigs>(sliceConfigs, STORE_NAME);
14 changes: 8 additions & 6 deletions src/store/stores/loadingState.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { createBaseSlice, SliceState } from '../utils/slice';
import { generateStore, type StateCreatorTyped } from '../utils/storeCreator';
import { createStoreFactory, type SliceConfigs } from '../utils/createStoreFactory';
import { type SliceState } from '../utils/slice';

export type LoadingState = SliceState<'isLoading', boolean>;

const STORE_NAME = 'Loading';

const loadingStateStore: StateCreatorTyped<LoadingState> = (...args) => ({
...createBaseSlice({ basic: 'isLoading' }, false)(...args),
});
const sliceConfigs: SliceConfigs = {
isLoading: {
initialValue: false,
},
};

export const useLoadingStateStore = generateStore(loadingStateStore, STORE_NAME);
export const useLoadingStateStore = createStoreFactory<LoadingState, SliceConfigs>(sliceConfigs, STORE_NAME);
22 changes: 14 additions & 8 deletions src/store/stores/marcPreview.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createBaseSlice, SliceState } from '../utils/slice';
import { generateStore, type StateCreatorTyped } from '../utils/storeCreator';
import { createStoreFactory, SliceConfigs } from '../utils/createStoreFactory';
import { type SliceState } from '../utils/slice';

type MarcPreviewData = MarcDTO | null;
type MarcPreviewMetaData = MarcPreviewMetadata | null;
Expand All @@ -10,10 +10,16 @@ export type MarcPreviewState = SliceState<'basicValue', any> &

const STORE_NAME = 'MarcPreview';

const marcPreviewStore: StateCreatorTyped<MarcPreviewState> = (...args) => ({
...createBaseSlice({ basic: 'basicValue' }, null)(...args),
...createBaseSlice({ basic: 'complexValue' }, null as MarcPreviewData)(...args),
...createBaseSlice({ basic: 'metaData' }, null as MarcPreviewMetaData)(...args),
});
const sliceConfigs: SliceConfigs = {
basicValue: {
initialValue: null,
},
complexValue: {
initialValue: null,
},
metaData: {
initialValue: null,
},
};

export const useMarcPreviewStore = generateStore(marcPreviewStore, STORE_NAME);
export const useMarcPreviewStore = createStoreFactory<MarcPreviewState, SliceConfigs>(sliceConfigs, STORE_NAME);
Loading

0 comments on commit 0c2aec4

Please sign in to comment.