1
0
Fork 0
freesewing/sites/shared/hooks/useGist.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

import useLocalStorage from './useLocalStorage';
import set from 'lodash.set'
import unset from 'lodash.unset'
import defaultSettings from 'shared/components/workbench/default-settings.js'
// Generates a default design gist to start from
const defaultGist = (design, locale='en') => {
const gist = {
design: design.config.name,
version: design.config.version,
...defaultSettings,
_state: {view: 'draft'}
}
if (locale) gist.locale = locale
return gist
}
2022-06-23 14:40:39 -05:00
// generate the gist state and its handlers
2022-06-23 14:37:11 -05:00
export function useGist(design, app) {
2022-06-23 14:40:39 -05:00
// get the localstorage state and setter
2022-06-23 14:37:11 -05:00
const [gist, _setGist, gistReady] = useLocalStorage(`${design.config.name}_gist`, defaultGist(design, app.locale));
2022-06-23 14:40:39 -05:00
/** apply new gist values onto existing gist */
2022-06-23 14:37:11 -05:00
const setGist = (newGist) => {
2022-06-23 14:40:39 -05:00
// setters that are passed a function always use the latest state value, so these don't need to be memoized
2022-06-23 14:37:11 -05:00
_setGist((gistState) => ({...gistState, ...newGist}))
}
2022-06-23 14:40:39 -05:00
/** update a single gist value */
2022-06-23 14:37:11 -05:00
const updateGist = (path, value) => {
_setGist((gistState) => {
const newGist = {...gistState};
set(newGist, path, value);
return newGist;
})
}
2022-06-23 14:40:39 -05:00
/** unset a single gist value */
const unsetGist = (path) => {
2022-06-23 14:37:11 -05:00
_setGist((gistState) => {
const newGist = {... gistState};
unset(newGist, path);
return newGist;
})
}
2022-06-23 14:40:39 -05:00
/** replace the entire gist with the given gist */
const replaceGist = (newGist) => {
2022-06-23 14:37:11 -05:00
_setGist(newGist);
}
2022-06-23 14:40:39 -05:00
/** reset to the default gist */
const clearGist = () => {
replaceGist(defaultGist(design, gist.locale))
}
2022-06-23 14:37:11 -05:00
return {gist, setGist, unsetGist, replaceGist, clearGist, gistReady, updateGist};
}