mirror of
https://github.com/smartxworks/sunmao-ui.git
synced 2024-11-27 08:39:59 +08:00
feat: implement localstorage trait
This commit is contained in:
parent
85f88b5ec3
commit
630fc87ea6
@ -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);
|
||||
|
||||
|
73
packages/runtime/src/traits/core/LocalStorage.tsx
Normal file
73
packages/runtime/src/traits/core/LocalStorage.tsx
Normal 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,
|
||||
};
|
Loading…
Reference in New Issue
Block a user