feat: manually mirror opencoze's code from bytedance
Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
const { defineConfig } = require('@coze-arch/stylelint-config');
|
||||
|
||||
module.exports = defineConfig({
|
||||
extends: [],
|
||||
});
|
||||
68
frontend/packages/foundation/local-storage/README.md
Normal file
68
frontend/packages/foundation/local-storage/README.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# @coze-foundation/local-storage
|
||||
|
||||
global local storage service
|
||||
|
||||
## Overview
|
||||
|
||||
This package is part of the Coze Studio monorepo and provides architecture functionality. It includes hook, service.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Installation
|
||||
|
||||
Add this package to your `package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"dependencies": {
|
||||
"@coze-foundation/local-storage": "workspace:*"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
rush update
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```typescript
|
||||
import { /* exported functions/components */ } from '@coze-foundation/local-storage';
|
||||
|
||||
// Example usage
|
||||
// TODO: Add specific usage examples
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- Hook
|
||||
- Service
|
||||
|
||||
## API Reference
|
||||
|
||||
### Exports
|
||||
|
||||
- `localStorageService`
|
||||
- `useValue as useLocalStorageValue`
|
||||
|
||||
|
||||
For detailed API documentation, please refer to the TypeScript definitions.
|
||||
|
||||
## Development
|
||||
|
||||
This package is built with:
|
||||
|
||||
- TypeScript
|
||||
- Modern JavaScript
|
||||
- Vitest for testing
|
||||
- ESLint for code quality
|
||||
|
||||
## Contributing
|
||||
|
||||
This package is part of the Coze Studio monorepo. Please follow the monorepo contribution guidelines.
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
|
||||
import { localStorageService } from '../../src/core';
|
||||
|
||||
const LOCAL_STORAGE_KEY = '__coz_biz_cache__';
|
||||
|
||||
describe('LocalStorageService', () => {
|
||||
beforeEach(() => {
|
||||
// 清除 localStorage
|
||||
localStorage.clear();
|
||||
// 重置 userId
|
||||
localStorageService.setUserId(undefined);
|
||||
});
|
||||
|
||||
describe('永久存储', () => {
|
||||
const permanentKey = 'workflow-toolbar-role-onboarding-hidden';
|
||||
|
||||
it('应该能正确设置和获取永久存储的值', () => {
|
||||
const value = 'test-value';
|
||||
|
||||
localStorageService.setValue(permanentKey, value);
|
||||
expect(localStorageService.getValue(permanentKey)).toBe(value);
|
||||
});
|
||||
|
||||
it('应该能正确删除永久存储的值', () => {
|
||||
localStorageService.setValue(permanentKey, 'test-value');
|
||||
localStorageService.setValue(permanentKey, undefined);
|
||||
expect(localStorageService.getValue(permanentKey)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('应该将数据持久化到 localStorage', async () => {
|
||||
const value = 'test-value';
|
||||
|
||||
localStorageService.setValue(permanentKey, value);
|
||||
|
||||
// 等待 throttle
|
||||
await new Promise(resolve => setTimeout(resolve, 400));
|
||||
|
||||
const storedData = JSON.parse(
|
||||
localStorage.getItem(LOCAL_STORAGE_KEY) || '{}',
|
||||
);
|
||||
expect(storedData.permanent?.[permanentKey]).toBe(value);
|
||||
});
|
||||
});
|
||||
|
||||
describe('用户相关存储', () => {
|
||||
const userId = 'test-user-id';
|
||||
const userBindKey = 'coachmark';
|
||||
|
||||
beforeEach(() => {
|
||||
localStorageService.setUserId(userId);
|
||||
});
|
||||
|
||||
it('应该能正确设置和获取用户相关的值', () => {
|
||||
const value = 'test-value';
|
||||
|
||||
localStorageService.setValue(userBindKey, value);
|
||||
expect(localStorageService.getValue(userBindKey)).toBe(value);
|
||||
});
|
||||
|
||||
it('在没有设置 userId 时不应该设置用户相关的值', () => {
|
||||
vi.stubGlobal('IS_DEV_MODE', false);
|
||||
localStorageService.setUserId(undefined);
|
||||
|
||||
localStorageService.setValue(userBindKey, 'test-value');
|
||||
expect(localStorageService.getValue(userBindKey)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('切换用户时应该能访问对应用户的数据', () => {
|
||||
const value1 = 'user1-value';
|
||||
const value2 = 'user2-value';
|
||||
const userId2 = 'test-user-id-2';
|
||||
|
||||
// 第一个用户的数据
|
||||
localStorageService.setValue(userBindKey, value1);
|
||||
|
||||
// 切换到第二个用户
|
||||
localStorageService.setUserId(userId2);
|
||||
localStorageService.setValue(userBindKey, value2);
|
||||
expect(localStorageService.getValue(userBindKey)).toBe(value2);
|
||||
|
||||
// 切回第一个用户
|
||||
localStorageService.setUserId(userId);
|
||||
expect(localStorageService.getValue(userBindKey)).toBe(value1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('事件监听', () => {
|
||||
const permanentKey = 'workflow-toolbar-role-onboarding-hidden';
|
||||
|
||||
it('值变化时应该触发 change 事件', async () => {
|
||||
const value = 'test-value';
|
||||
const changeHandler = vi.fn();
|
||||
|
||||
localStorageService.on('change', changeHandler);
|
||||
localStorageService.setValue(permanentKey, value);
|
||||
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
expect(changeHandler).toHaveBeenCalled();
|
||||
|
||||
localStorageService.off('change', changeHandler);
|
||||
});
|
||||
|
||||
it('设置 userId 时应该触发 setUserId 事件', () => {
|
||||
const userId = 'test-user-id';
|
||||
const setUserIdHandler = vi.fn();
|
||||
|
||||
localStorageService.on('setUserId', setUserIdHandler);
|
||||
localStorageService.setUserId(userId);
|
||||
|
||||
expect(setUserIdHandler).toHaveBeenCalledWith(userId);
|
||||
|
||||
localStorageService.off('setUserId', setUserIdHandler);
|
||||
});
|
||||
});
|
||||
|
||||
describe('异步获取值', () => {
|
||||
const permanentKey = 'workflow-toolbar-role-onboarding-hidden';
|
||||
|
||||
it('对于非用户绑定的值应该直接返回', async () => {
|
||||
const value = 'test-value';
|
||||
|
||||
localStorageService.setValue(permanentKey, value);
|
||||
const result = await localStorageService.getValueSync(permanentKey);
|
||||
expect(result).toBe(value);
|
||||
}, 10000);
|
||||
|
||||
it('对于用户绑定的值,应该等待 userId 设置后再返回', async () => {
|
||||
const userId = 'test-user-id';
|
||||
const value = 'test-value';
|
||||
|
||||
// 先设置值
|
||||
localStorageService.setUserId(userId);
|
||||
localStorageService.setValue('coachmark', value);
|
||||
localStorageService.setUserId(undefined);
|
||||
|
||||
// 异步获取值
|
||||
const valuePromise = localStorageService.getValueSync('coachmark');
|
||||
|
||||
// 设置 userId
|
||||
setTimeout(() => {
|
||||
localStorageService.setUserId(userId);
|
||||
}, 0);
|
||||
|
||||
const result = await valuePromise;
|
||||
expect(result).toBe(value);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
|
||||
import { useValue } from '../../src/hooks/use-value';
|
||||
import { localStorageService } from '../../src/core';
|
||||
|
||||
describe('useValue', () => {
|
||||
const permanentKey = 'workflow-toolbar-role-onboarding-hidden';
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
localStorageService.setUserId(undefined);
|
||||
});
|
||||
|
||||
it('应该返回存储的值', async () => {
|
||||
const value = 'test-value';
|
||||
localStorageService.setValue(permanentKey, value);
|
||||
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
const { result } = renderHook(() => useValue(permanentKey));
|
||||
expect(result.current).toBe(value);
|
||||
});
|
||||
|
||||
it('当值改变时应该更新', async () => {
|
||||
const { result } = renderHook(() => useValue(permanentKey));
|
||||
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
await act(async () => {
|
||||
localStorageService.setValue(permanentKey, 'new-value');
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
expect(result.current).toBe('new-value');
|
||||
});
|
||||
|
||||
it('当值被删除时应该返回 undefined', async () => {
|
||||
localStorageService.setValue(permanentKey, 'test-value');
|
||||
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
const { result } = renderHook(() => useValue(permanentKey));
|
||||
|
||||
await act(async () => {
|
||||
localStorageService.setValue(permanentKey, undefined);
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
expect(result.current).toBeUndefined();
|
||||
});
|
||||
|
||||
it('卸载时应该清理事件监听', async () => {
|
||||
const { unmount } = renderHook(() => useValue(permanentKey));
|
||||
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
unmount();
|
||||
|
||||
// 确保不会触发已卸载组件的状态更新
|
||||
localStorageService.setValue(permanentKey, 'new-value');
|
||||
// 如果事件监听没有被清理,这里会抛出 React 警告
|
||||
});
|
||||
|
||||
describe('用户相关的值', () => {
|
||||
// 使用一个确定绑定了用户的 key
|
||||
const userBindKey = 'coachmark' as const;
|
||||
const userId = 'test-user-id';
|
||||
|
||||
beforeEach(() => {
|
||||
localStorageService.setUserId(userId);
|
||||
});
|
||||
|
||||
it('应该返回当前用户的值', async () => {
|
||||
localStorageService.setValue(userBindKey, 'user-value');
|
||||
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
const { result } = renderHook(() => useValue(userBindKey));
|
||||
expect(result.current).toBe('user-value');
|
||||
});
|
||||
|
||||
it('切换用户时应该更新值', async () => {
|
||||
const userId2 = 'test-user-id-2';
|
||||
localStorageService.setValue(userBindKey, 'user1-value');
|
||||
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
const { result } = renderHook(() => useValue(userBindKey));
|
||||
expect(result.current).toBe('user1-value');
|
||||
|
||||
await act(async () => {
|
||||
localStorageService.setUserId(userId2);
|
||||
localStorageService.setValue(userBindKey, 'user2-value');
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
expect(result.current).toBe('user2-value');
|
||||
|
||||
await act(async () => {
|
||||
localStorageService.setUserId(userId);
|
||||
// 等待事件触发
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
expect(result.current).toBe('user1-value');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import { paseLocalStorageValue, filterCacheData } from '../../src/utils/parse';
|
||||
import { type LocalStorageCacheData } from '../../src/types';
|
||||
|
||||
describe('解析工具函数', () => {
|
||||
describe('paseLocalStorageValue', () => {
|
||||
it('应该返回空对象当输入为 null', () => {
|
||||
expect(paseLocalStorageValue(null)).toEqual({});
|
||||
});
|
||||
|
||||
it('应该返回空对象当输入不是有效的 JSON', () => {
|
||||
expect(paseLocalStorageValue('invalid json')).toEqual({});
|
||||
});
|
||||
|
||||
it('应该返回空对象当输入的 JSON 不符合缓存数据格式', () => {
|
||||
expect(paseLocalStorageValue('{"invalid": "data"}')).toEqual({
|
||||
invalid: 'data',
|
||||
});
|
||||
});
|
||||
|
||||
it('应该正确解析永久缓存数据', () => {
|
||||
const data = {
|
||||
permanent: {
|
||||
'workspace-spaceId': 'test-space-id',
|
||||
},
|
||||
};
|
||||
expect(paseLocalStorageValue(JSON.stringify(data))).toEqual(data);
|
||||
});
|
||||
|
||||
it('应该正确解析用户相关缓存数据', () => {
|
||||
const data = {
|
||||
userRelated: {
|
||||
'user-1': {
|
||||
'workspace-spaceId': 'test-space-id',
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(paseLocalStorageValue(JSON.stringify(data))).toEqual(data);
|
||||
});
|
||||
|
||||
it('应该正确解析同时包含永久和用户相关的缓存数据', () => {
|
||||
const data = {
|
||||
permanent: {
|
||||
'workspace-spaceId': 'test-space-id',
|
||||
},
|
||||
userRelated: {
|
||||
'user-1': {
|
||||
'workspace-subMenu': 'test-menu',
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(paseLocalStorageValue(JSON.stringify(data))).toEqual(data);
|
||||
});
|
||||
|
||||
it('应该返回空对象当永久缓存数据格式无效', () => {
|
||||
const data = {
|
||||
permanent: {
|
||||
key: 123, // 应该是字符串
|
||||
},
|
||||
};
|
||||
expect(paseLocalStorageValue(JSON.stringify(data))).toEqual({});
|
||||
});
|
||||
|
||||
it('应该返回空对象当用户相关缓存数据格式无效', () => {
|
||||
const data = {
|
||||
userRelated: {
|
||||
'user-1': {
|
||||
key: 123, // 应该是字符串
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(paseLocalStorageValue(JSON.stringify(data))).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterCacheData', () => {
|
||||
it('应该过滤掉永久缓存中的无效键', () => {
|
||||
const data: LocalStorageCacheData = {
|
||||
permanent: {
|
||||
'workspace-spaceId': 'valid-value',
|
||||
'invalid-key': 'invalid-value',
|
||||
},
|
||||
};
|
||||
|
||||
const filtered = filterCacheData(data);
|
||||
expect(filtered.permanent?.['workspace-spaceId']).toBe('valid-value');
|
||||
expect(filtered.permanent?.['invalid-key']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('应该过滤掉用户相关缓存中的无效键', () => {
|
||||
const data: LocalStorageCacheData = {
|
||||
userRelated: {
|
||||
'user-1': {
|
||||
'workspace-spaceId': 'valid-value',
|
||||
'invalid-key': 'invalid-value',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const filtered = filterCacheData(data);
|
||||
expect(filtered.userRelated?.['user-1']?.['workspace-spaceId']).toBe(
|
||||
'valid-value',
|
||||
);
|
||||
expect(filtered.userRelated?.['user-1']?.['invalid-key']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('应该保持用户 ID 不变', () => {
|
||||
const data: LocalStorageCacheData = {
|
||||
userRelated: {
|
||||
'user-1': {
|
||||
'workspace-spaceId': 'value-1',
|
||||
},
|
||||
'user-2': {
|
||||
'workspace-spaceId': 'value-2',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const filtered = filterCacheData(data);
|
||||
expect(Object.keys(filtered.userRelated || {})).toEqual([
|
||||
'user-1',
|
||||
'user-2',
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"operationSettings": [
|
||||
{
|
||||
"operationName": "test:cov",
|
||||
"outputFolderNames": ["coverage"]
|
||||
},
|
||||
{
|
||||
"operationName": "ts-check",
|
||||
"outputFolderNames": ["./dist"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
const { defineConfig } = require('@coze-arch/eslint-config');
|
||||
|
||||
module.exports = defineConfig({
|
||||
packageRoot: __dirname,
|
||||
preset: 'web',
|
||||
rules: {},
|
||||
});
|
||||
43
frontend/packages/foundation/local-storage/package.json
Normal file
43
frontend/packages/foundation/local-storage/package.json
Normal file
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "@coze-foundation/local-storage",
|
||||
"version": "0.0.1",
|
||||
"description": "global local storage service",
|
||||
"license": "Apache-2.0",
|
||||
"author": "duwenhan@bytedance.com",
|
||||
"maintainers": [],
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"build": "exit 0",
|
||||
"lint": "eslint ./ --cache",
|
||||
"test": "vitest --run --passWithNoTests",
|
||||
"test:cov": "npm run test -- --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"eventemitter3": "^5.0.1",
|
||||
"lodash-es": "^4.17.21"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@coze-arch/bot-typings": "workspace:*",
|
||||
"@coze-arch/eslint-config": "workspace:*",
|
||||
"@coze-arch/stylelint-config": "workspace:*",
|
||||
"@coze-arch/ts-config": "workspace:*",
|
||||
"@coze-arch/vitest-config": "workspace:*",
|
||||
"@testing-library/jest-dom": "^6.1.5",
|
||||
"@testing-library/react": "^14.1.2",
|
||||
"@testing-library/react-hooks": "^8.0.1",
|
||||
"@types/lodash-es": "^4.17.10",
|
||||
"@types/react": "18.2.37",
|
||||
"@types/react-dom": "18.2.15",
|
||||
"@vitest/coverage-v8": "~3.0.5",
|
||||
"react": "~18.2.0",
|
||||
"react-dom": "~18.2.0",
|
||||
"stylelint": "^15.11.0",
|
||||
"vite-plugin-svgr": "~3.3.0",
|
||||
"vitest": "~3.0.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18.2.0",
|
||||
"react-dom": ">=18.2.0"
|
||||
}
|
||||
}
|
||||
|
||||
63
frontend/packages/foundation/local-storage/src/config.ts
Normal file
63
frontend/packages/foundation/local-storage/src/config.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { type LocalStorageCacheConfig } from './types';
|
||||
|
||||
// 统一维护 key 定义避免出现冲突
|
||||
export const LOCAL_STORAGE_CACHE_KEYS = [
|
||||
'coachmark',
|
||||
'workspace-spaceId',
|
||||
'workspace-subMenu',
|
||||
'workspace-develop-filters',
|
||||
'workspace-library-filters',
|
||||
'workspace-ocean-project-filters',
|
||||
'coze-home-session-area-hidden-key',
|
||||
'template-purchase-agreement-checked',
|
||||
'coze-promptkit-recommend-pannel-hidden-key',
|
||||
'workflow-toolbar-role-onboarding-hidden',
|
||||
'coze-project-entity-hidden-key',
|
||||
'enterpriseId',
|
||||
'resourceCopyTaskIds',
|
||||
'coze-create-enterprise-success',
|
||||
'coze-show-product-matrix-tips',
|
||||
] as const satisfies readonly string[];
|
||||
|
||||
export type LocalStorageCacheKey = (typeof LOCAL_STORAGE_CACHE_KEYS)[number];
|
||||
|
||||
export type LocalStorageCacheConfigMap = {
|
||||
[key in LocalStorageCacheKey]?: LocalStorageCacheConfig;
|
||||
};
|
||||
|
||||
export const cacheConfig: LocalStorageCacheConfigMap = {
|
||||
coachmark: {
|
||||
bindAccount: true,
|
||||
},
|
||||
'workspace-spaceId': {
|
||||
bindAccount: true,
|
||||
},
|
||||
'workspace-subMenu': {
|
||||
bindAccount: true,
|
||||
},
|
||||
'template-purchase-agreement-checked': {
|
||||
bindAccount: true,
|
||||
},
|
||||
enterpriseId: {
|
||||
bindAccount: true,
|
||||
},
|
||||
resourceCopyTaskIds: {
|
||||
bindAccount: true,
|
||||
},
|
||||
};
|
||||
154
frontend/packages/foundation/local-storage/src/core/index.ts
Normal file
154
frontend/packages/foundation/local-storage/src/core/index.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { throttle } from 'lodash-es';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
|
||||
import { filterCacheData, paseLocalStorageValue } from '../utils/parse';
|
||||
import { type LocalStorageCacheData } from '../types';
|
||||
import { cacheConfig, type LocalStorageCacheKey } from '../config';
|
||||
|
||||
const LOCAL_STORAGE_KEY = '__coz_biz_cache__';
|
||||
|
||||
const throttleWait = 300;
|
||||
|
||||
class LocalStorageService extends EventEmitter {
|
||||
#state: LocalStorageCacheData = {};
|
||||
#userId: string | undefined;
|
||||
#saveState: () => void;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.#saveState = throttle(() => {
|
||||
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.#state));
|
||||
}, throttleWait);
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
/**
|
||||
* 页签进入后台后,通过操作其它页签,可能导致 #state 状态不是最新的
|
||||
* 所以页签重新激活后需要同步一次 localStorage 的数据
|
||||
*/
|
||||
if (document.visibilityState === 'visible') {
|
||||
this.#initState();
|
||||
}
|
||||
});
|
||||
this.#initState();
|
||||
}
|
||||
|
||||
#initState() {
|
||||
this.#state = filterCacheData(
|
||||
paseLocalStorageValue(localStorage.getItem(LOCAL_STORAGE_KEY)),
|
||||
);
|
||||
this.emit('change');
|
||||
}
|
||||
|
||||
#setPermanent(key: LocalStorageCacheKey, value?: string) {
|
||||
if (value) {
|
||||
this.#state.permanent = {
|
||||
...this.#state.permanent,
|
||||
[key]: value,
|
||||
};
|
||||
} else if (this.#state.permanent) {
|
||||
delete this.#state.permanent[key];
|
||||
}
|
||||
this.#saveState();
|
||||
}
|
||||
|
||||
#setUserRelated(key: LocalStorageCacheKey, value?: string) {
|
||||
if (!this.#userId) {
|
||||
return;
|
||||
}
|
||||
if (value) {
|
||||
this.#state.userRelated = {
|
||||
...this.#state.userRelated,
|
||||
[this.#userId]: {
|
||||
...this.#state.userRelated?.[this.#userId],
|
||||
[key]: value,
|
||||
},
|
||||
};
|
||||
} else if (this.#state.userRelated?.[this.#userId]?.[key]) {
|
||||
delete this.#state.userRelated?.[this.#userId]?.[key];
|
||||
}
|
||||
this.#saveState();
|
||||
}
|
||||
|
||||
#getPermanent(key: LocalStorageCacheKey) {
|
||||
return this.#state.permanent?.[key];
|
||||
}
|
||||
|
||||
#getUserRelated(key: LocalStorageCacheKey) {
|
||||
if (!this.#userId) {
|
||||
if (IS_DEV_MODE) {
|
||||
throw Error(
|
||||
'需要确保在 userId 初始化后再调用此方法 或者使用 getValueSync',
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
return this.#state.userRelated?.[this.#userId]?.[key];
|
||||
}
|
||||
|
||||
#waitUserId() {
|
||||
return new Promise<string | undefined>(r => {
|
||||
const callback = (userId: string) => {
|
||||
if (userId) {
|
||||
r(this.#userId);
|
||||
this.off('setUserId', callback);
|
||||
}
|
||||
};
|
||||
this.on('setUserId', callback);
|
||||
});
|
||||
}
|
||||
|
||||
setUserId(userId?: string) {
|
||||
this.#userId = userId;
|
||||
this.emit('change');
|
||||
this.emit('setUserId', userId);
|
||||
}
|
||||
|
||||
setValue(key: LocalStorageCacheKey, value?: string) {
|
||||
const { bindAccount } = cacheConfig[key] ?? {};
|
||||
if (bindAccount) {
|
||||
if (!this.#userId) {
|
||||
return;
|
||||
}
|
||||
this.#setUserRelated(key, value);
|
||||
} else {
|
||||
this.#setPermanent(key, value);
|
||||
}
|
||||
this.emit('change');
|
||||
}
|
||||
|
||||
getValue(key: LocalStorageCacheKey): string | undefined {
|
||||
const { bindAccount } = cacheConfig[key] ?? {};
|
||||
if (bindAccount) {
|
||||
return this.#getUserRelated(key);
|
||||
}
|
||||
return this.#getPermanent(key);
|
||||
}
|
||||
|
||||
async getValueSync(key: LocalStorageCacheKey): Promise<string | undefined> {
|
||||
const { bindAccount } = cacheConfig[key] ?? {};
|
||||
if (bindAccount) {
|
||||
if (!this.#userId) {
|
||||
await this.#waitUserId();
|
||||
}
|
||||
return this.#getUserRelated(key);
|
||||
}
|
||||
return this.#getPermanent(key);
|
||||
}
|
||||
}
|
||||
|
||||
export const localStorageService = new LocalStorageService();
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { localStorageService } from '../core';
|
||||
import { type LocalStorageCacheKey } from '../config';
|
||||
|
||||
export const useValue = (key: LocalStorageCacheKey): string | undefined => {
|
||||
const [value, setValue] = useState(() => localStorageService.getValue(key));
|
||||
|
||||
useEffect(() => {
|
||||
const callback = () => {
|
||||
setValue(localStorageService.getValue(key));
|
||||
};
|
||||
localStorageService.on('change', callback);
|
||||
return () => {
|
||||
localStorageService.off('change', callback);
|
||||
};
|
||||
}, [key]);
|
||||
return value;
|
||||
};
|
||||
19
frontend/packages/foundation/local-storage/src/index.ts
Normal file
19
frontend/packages/foundation/local-storage/src/index.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export { localStorageService } from './core';
|
||||
|
||||
export { useValue as useLocalStorageValue } from './hooks/use-value';
|
||||
28
frontend/packages/foundation/local-storage/src/types.ts
Normal file
28
frontend/packages/foundation/local-storage/src/types.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export interface LocalStorageCacheConfig {
|
||||
bindAccount?: boolean;
|
||||
}
|
||||
|
||||
export interface CacheDataItems {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
export interface LocalStorageCacheData {
|
||||
permanent?: CacheDataItems;
|
||||
userRelated?: Record<string, CacheDataItems>;
|
||||
}
|
||||
17
frontend/packages/foundation/local-storage/src/typings.d.ts
vendored
Normal file
17
frontend/packages/foundation/local-storage/src/typings.d.ts
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/// <reference types='@coze-arch/bot-typings' />
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { type CacheDataItems, type LocalStorageCacheData } from '../types';
|
||||
import { LOCAL_STORAGE_CACHE_KEYS } from '../config';
|
||||
|
||||
const isValidDataItem = (data: unknown): data is CacheDataItems => {
|
||||
if (!data || typeof data !== 'object') {
|
||||
return false;
|
||||
}
|
||||
return Object.values(data).every(value => typeof value === 'string');
|
||||
};
|
||||
|
||||
const isObject = (value: unknown): value is object =>
|
||||
!!value && typeof value === 'object' && value !== null;
|
||||
|
||||
// 判断本地缓存中的值是否与 LocalStorageCacheData 类型定义匹配
|
||||
const isValidCacheData = (value: unknown): value is LocalStorageCacheData => {
|
||||
if (!isObject(value)) {
|
||||
return false;
|
||||
}
|
||||
if ('permanent' in value && !isValidDataItem(value.permanent)) {
|
||||
return false;
|
||||
}
|
||||
if ('userRelated' in value) {
|
||||
const { userRelated } = value;
|
||||
if (!isObject(userRelated)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
Object.values(userRelated).some(dateItem => !isValidDataItem(dateItem))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
export const paseLocalStorageValue = (value: string | null) => {
|
||||
if (!value) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
const raw = JSON.parse(value);
|
||||
return isValidCacheData(raw) ? raw : ({} satisfies LocalStorageCacheData);
|
||||
} catch (e) {
|
||||
return {} satisfies LocalStorageCacheData;
|
||||
}
|
||||
};
|
||||
|
||||
const filterDataItems = (data: CacheDataItems): CacheDataItems =>
|
||||
Object.entries(data).reduce((res, [key, item]) => {
|
||||
if ((LOCAL_STORAGE_CACHE_KEYS as unknown as string[]).includes(key)) {
|
||||
return {
|
||||
...res,
|
||||
[key]: item,
|
||||
};
|
||||
}
|
||||
return res;
|
||||
}, {});
|
||||
|
||||
export const filterCacheData = (
|
||||
cacheData: LocalStorageCacheData,
|
||||
): LocalStorageCacheData => {
|
||||
if (cacheData.permanent) {
|
||||
cacheData.permanent = filterDataItems(cacheData.permanent);
|
||||
}
|
||||
if (cacheData.userRelated) {
|
||||
cacheData.userRelated = Object.entries(cacheData.userRelated).reduce(
|
||||
(res, [key, value]) => ({
|
||||
...res,
|
||||
[key]: filterDataItems(value),
|
||||
}),
|
||||
{},
|
||||
);
|
||||
}
|
||||
return cacheData;
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"extends": "@coze-arch/ts-config/tsconfig.web.json",
|
||||
"compilerOptions": {
|
||||
"types": [],
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true,
|
||||
"rootDir": "./src",
|
||||
"outDir": "./dist",
|
||||
"tsBuildInfoFile": "./dist/tsconfig.build.tsbuildinfo"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../arch/bot-typings/tsconfig.build.json"
|
||||
},
|
||||
{
|
||||
"path": "../../../config/eslint-config/tsconfig.build.json"
|
||||
},
|
||||
{
|
||||
"path": "../../../config/stylelint-config/tsconfig.build.json"
|
||||
},
|
||||
{
|
||||
"path": "../../../config/ts-config/tsconfig.build.json"
|
||||
},
|
||||
{
|
||||
"path": "../../../config/vitest-config/tsconfig.build.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
15
frontend/packages/foundation/local-storage/tsconfig.json
Normal file
15
frontend/packages/foundation/local-storage/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"compilerOptions": {
|
||||
"composite": true
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.build.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.misc.json"
|
||||
}
|
||||
],
|
||||
"exclude": ["**/*"]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "@coze-arch/ts-config/tsconfig.web.json",
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"include": ["__tests__", "stories", "vitest.config.ts", "tailwind.config.ts"],
|
||||
"exclude": ["./dist"],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.build.json"
|
||||
}
|
||||
],
|
||||
"compilerOptions": {
|
||||
"rootDir": "./",
|
||||
"outDir": "./dist",
|
||||
"types": ["vitest/globals"],
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true
|
||||
}
|
||||
}
|
||||
22
frontend/packages/foundation/local-storage/vitest.config.ts
Normal file
22
frontend/packages/foundation/local-storage/vitest.config.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { defineConfig } from '@coze-arch/vitest-config';
|
||||
|
||||
export default defineConfig({
|
||||
dirname: __dirname,
|
||||
preset: 'web',
|
||||
});
|
||||
Reference in New Issue
Block a user