feat: implement localstorage trait

This commit is contained in:
xzdry 2022-03-07 09:59:52 +08:00
parent 85f88b5ec3
commit 630fc87ea6
2 changed files with 75 additions and 0 deletions

View File

@ -17,6 +17,7 @@ import CoreStyle from '../traits/core/Style';
import CoreHidden from '../traits/core/Hidden';
import CoreFetch from '../traits/core/Fetch';
import CoreValidation from '../traits/core/Validation';
import CoreLocalStorage from '../traits/core/LocalStorage';
// utilMethods
import ScrollIntoComponentUtilMethod from '../utilMethods/ScrollIntoComponent';
@ -204,6 +205,7 @@ export function initRegistry(
registry.registerTrait(CoreHidden);
registry.registerTrait(CoreFetch);
registry.registerTrait(CoreValidation);
registry.registerTrait(CoreLocalStorage);
registry.registerUtilMethod(ScrollIntoComponentUtilMethod);

View File

@ -0,0 +1,73 @@
import { Static, Type } from '@sinclair/typebox';
import { createTrait } from '@sunmao-ui/core';
import { isEqual } from 'lodash';
import { TraitImpl } from 'src/types';
function getLocalStorageValue(key: string) {
try {
const json = localStorage.getItem(key);
if (json) {
return JSON.parse(json);
}
return '';
} catch (error) {
return '';
}
}
const HasInitializedMap = new Map<string, boolean>();
const PrevValueCache: Record<string, unknown> = {};
const PropsSchema = Type.Object({
key: Type.String(),
value: Type.Any(),
});
const LocalStorageTraitImpl: TraitImpl<Static<typeof PropsSchema>> = ({
key,
value,
componentId,
mergeState,
}) => {
const hashId = `#${componentId}@${key}`;
const hasInitialized = HasInitializedMap.get(hashId);
if (key) {
if (!hasInitialized) {
PrevValueCache[key] = getLocalStorageValue(hashId);
mergeState({
[key]: PrevValueCache[key],
});
HasInitializedMap.set(hashId, true);
} else {
if (!isEqual(PrevValueCache[key], value)) {
PrevValueCache[key] = value;
mergeState({
[key]: value,
});
localStorage.setItem(hashId, JSON.stringify(value));
}
}
}
return {
props: null,
};
};
export default {
...createTrait({
version: 'core/v1',
metadata: {
name: 'localStorage',
description: 'localStorage trait',
},
spec: {
properties: PropsSchema,
state: Type.Object({}),
methods: [],
},
}),
impl: LocalStorageTraitImpl,
};