@56os/shared-utils 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,46 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @56os/shared-utils
2
+
3
+ 56os 业务仓共享工具包(本地联调优先,通过后再发 npm)。
4
+
5
+ ## 本地联调
6
+
7
+ ```bash
8
+ # 在业务仓目录
9
+ pnpm add @56os/shared-utils@file:../56os-shared-utils
10
+ # 或 npm
11
+ npm install file:../56os-shared-utils
12
+ ```
13
+
14
+ Vite 建议:
15
+
16
+ 1. `optimizeDeps.exclude` 加入 `@56os/shared-utils`(避免预构建吞掉 `import.meta.env`)
17
+ 2. 本地 `file:../56os-shared-utils` 联调时,在 `vite.config.ts` 的 `resolve.alias` 把 peer 指回本仓 `node_modules`(`vue` / `crypto-js` / `jsencrypt` / `vue-types`),否则 Rollup 会从仓外包目录解析失败
18
+
19
+ ## 子路径导出
20
+
21
+ | 路径 | 说明 |
22
+ |------|------|
23
+ | `@56os/shared-utils/auth` | Token 本地读写 |
24
+ | `@56os/shared-utils/crypto` | AES |
25
+ | `@56os/shared-utils/jsencrypt` | RSA(读应用 `VITE_APP_RSA_*`) |
26
+ | `@56os/shared-utils/errorCode` | HTTP 错误文案 |
27
+ | `@56os/shared-utils/propTypes` | vue-types 封装 |
28
+ | `@56os/shared-utils/validate` | 校验 |
29
+ | `@56os/shared-utils/scroll-to` | 平滑滚动 |
30
+ | `@56os/shared-utils/tableHeight` | 表格高度 |
31
+ | `@56os/shared-utils/officeFileViewer` | 附件预览 |
32
+ | `@56os/shared-utils/statusTag` | 状态 Tag 类型 |
33
+ | `@56os/shared-utils/officeMutateGuard` | 机构筛选下增删改守卫 |
34
+ | `@56os/shared-utils/tableHeaderConfig` | 用户表头配置 |
35
+ | `@56os/shared-utils/createCustomNameComponent` | 动态路由 name |
36
+ | `@56os/shared-utils/ruoyi` | parseTime / handleTree 等 |
37
+
38
+ 业务仓可保留 `src/utils/xxx.ts` 薄 re-export,无需改动全仓 import。
39
+
40
+ ## 不包含
41
+
42
+ `dict` / `permission`(store) / `request` / `constant` / `filters` / `websocket` / `sse` —— 有业务耦合或宿主专属。
43
+
44
+ ## 版本
45
+
46
+ 遵循 semver。变更只改本包,业务仓禁止再维护实现副本。
package/package.json CHANGED
@@ -1,6 +1,110 @@
1
1
  {
2
2
  "name": "@56os/shared-utils",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "56os shared utils for auth/crypto/validate/table helpers",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "module": "./src/index.ts",
8
+ "types": "./src/index.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./src/index.ts",
12
+ "import": "./src/index.ts",
13
+ "default": "./src/index.ts"
14
+ },
15
+ "./auth": {
16
+ "types": "./src/auth.ts",
17
+ "import": "./src/auth.ts",
18
+ "default": "./src/auth.ts"
19
+ },
20
+ "./crypto": {
21
+ "types": "./src/crypto.ts",
22
+ "import": "./src/crypto.ts",
23
+ "default": "./src/crypto.ts"
24
+ },
25
+ "./jsencrypt": {
26
+ "types": "./src/jsencrypt.ts",
27
+ "import": "./src/jsencrypt.ts",
28
+ "default": "./src/jsencrypt.ts"
29
+ },
30
+ "./errorCode": {
31
+ "types": "./src/errorCode.ts",
32
+ "import": "./src/errorCode.ts",
33
+ "default": "./src/errorCode.ts"
34
+ },
35
+ "./propTypes": {
36
+ "types": "./src/propTypes.ts",
37
+ "import": "./src/propTypes.ts",
38
+ "default": "./src/propTypes.ts"
39
+ },
40
+ "./validate": {
41
+ "types": "./src/validate.ts",
42
+ "import": "./src/validate.ts",
43
+ "default": "./src/validate.ts"
44
+ },
45
+ "./scroll-to": {
46
+ "types": "./src/scroll-to.ts",
47
+ "import": "./src/scroll-to.ts",
48
+ "default": "./src/scroll-to.ts"
49
+ },
50
+ "./tableHeight": {
51
+ "types": "./src/tableHeight.ts",
52
+ "import": "./src/tableHeight.ts",
53
+ "default": "./src/tableHeight.ts"
54
+ },
55
+ "./officeFileViewer": {
56
+ "types": "./src/officeFileViewer.ts",
57
+ "import": "./src/officeFileViewer.ts",
58
+ "default": "./src/officeFileViewer.ts"
59
+ },
60
+ "./statusTag": {
61
+ "types": "./src/statusTag.ts",
62
+ "import": "./src/statusTag.ts",
63
+ "default": "./src/statusTag.ts"
64
+ },
65
+ "./officeMutateGuard": {
66
+ "types": "./src/officeMutateGuard.ts",
67
+ "import": "./src/officeMutateGuard.ts",
68
+ "default": "./src/officeMutateGuard.ts"
69
+ },
70
+ "./tableHeaderConfig": {
71
+ "types": "./src/tableHeaderConfig.ts",
72
+ "import": "./src/tableHeaderConfig.ts",
73
+ "default": "./src/tableHeaderConfig.ts"
74
+ },
75
+ "./createCustomNameComponent": {
76
+ "types": "./src/createCustomNameComponent.tsx",
77
+ "import": "./src/createCustomNameComponent.tsx",
78
+ "default": "./src/createCustomNameComponent.tsx"
79
+ },
80
+ "./ruoyi": {
81
+ "types": "./src/ruoyi.ts",
82
+ "import": "./src/ruoyi.ts",
83
+ "default": "./src/ruoyi.ts"
84
+ }
85
+ },
86
+ "files": [
87
+ "src",
88
+ "README.md"
89
+ ],
90
+ "peerDependencies": {
91
+ "crypto-js": "^4.0.0",
92
+ "jsencrypt": "^3.0.0",
93
+ "vue": "^3.4.0",
94
+ "vue-types": "^5.0.0"
95
+ },
96
+ "peerDependenciesMeta": {
97
+ "vue-types": {
98
+ "optional": true
99
+ }
100
+ },
101
+ "keywords": [
102
+ "56os",
103
+ "shared-utils",
104
+ "qiankun"
105
+ ],
106
+ "license": "UNLICENSED",
107
+ "publishConfig": {
108
+ "access": "public"
109
+ }
110
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Token 本地读写(不发起 HTTP)。
3
+ * 使用原生 storage,避免共享包解析应用侧 @vueuse/core peer 失败。
4
+ */
5
+
6
+ const TokenKey = 'Admin-Token';
7
+ const OaTokenKey = 'Oa-Iframe-Token';
8
+ const AuthModeKey = 'Auth-Mode';
9
+
10
+ const readLocal = (key: string): string | null => {
11
+ if (typeof localStorage === 'undefined') {
12
+ return null;
13
+ }
14
+ const raw = localStorage.getItem(key);
15
+ if (raw == null || raw === '' || raw === 'null' || raw === 'undefined') {
16
+ return null;
17
+ }
18
+ // useStorage 默认 JSON 序列化字符串会带引号,兼容两种形态
19
+ try {
20
+ const parsed = JSON.parse(raw);
21
+ return typeof parsed === 'string' ? parsed : raw;
22
+ } catch {
23
+ return raw;
24
+ }
25
+ };
26
+
27
+ const writeLocal = (key: string, value: string | null) => {
28
+ if (typeof localStorage === 'undefined') {
29
+ return;
30
+ }
31
+ if (value == null) {
32
+ localStorage.removeItem(key);
33
+ return;
34
+ }
35
+ localStorage.setItem(key, JSON.stringify(value));
36
+ };
37
+
38
+ const readSession = (key: string): string | null => {
39
+ if (typeof sessionStorage === 'undefined') {
40
+ return null;
41
+ }
42
+ const raw = sessionStorage.getItem(key);
43
+ if (raw == null || raw === '' || raw === 'null' || raw === 'undefined') {
44
+ return null;
45
+ }
46
+ try {
47
+ const parsed = JSON.parse(raw);
48
+ return typeof parsed === 'string' ? parsed : raw;
49
+ } catch {
50
+ return raw;
51
+ }
52
+ };
53
+
54
+ const writeSession = (key: string, value: string | null) => {
55
+ if (typeof sessionStorage === 'undefined') {
56
+ return;
57
+ }
58
+ if (value == null) {
59
+ sessionStorage.removeItem(key);
60
+ return;
61
+ }
62
+ sessionStorage.setItem(key, JSON.stringify(value));
63
+ };
64
+
65
+ /** 读取主系统 Admin-Token */
66
+ export const getToken = () => readLocal(TokenKey);
67
+
68
+ /** 写入主系统 Admin-Token */
69
+ export const setToken = (access_token: string) => writeLocal(TokenKey, access_token);
70
+
71
+ /** 清除主系统 Admin-Token */
72
+ export const removeToken = () => writeLocal(TokenKey, null);
73
+
74
+ /** OA / iframe 场景专用 token,不覆盖主系统 Admin-Token */
75
+ export const getOaToken = () => readSession(OaTokenKey);
76
+
77
+ /** 写入 OA iframe token */
78
+ export const setOaToken = (access_token: string) => writeSession(OaTokenKey, access_token);
79
+
80
+ /** 清除 OA iframe token */
81
+ export const removeOaToken = () => writeSession(OaTokenKey, null);
82
+
83
+ /** 进入 OA iframe 鉴权模式 */
84
+ export const enterOaIframeMode = () => {
85
+ if (typeof sessionStorage !== 'undefined') {
86
+ sessionStorage.setItem(AuthModeKey, 'oa-iframe');
87
+ }
88
+ };
89
+
90
+ /** 退出 OA iframe 鉴权模式并清理 OA token */
91
+ export const exitOaIframeMode = () => {
92
+ if (typeof sessionStorage !== 'undefined') {
93
+ sessionStorage.removeItem(AuthModeKey);
94
+ }
95
+ removeOaToken();
96
+ };
97
+
98
+ /** 是否处于 OA iframe 鉴权模式 */
99
+ export const isOaIframeMode = () =>
100
+ typeof sessionStorage !== 'undefined' && sessionStorage.getItem(AuthModeKey) === 'oa-iframe';
101
+
102
+ /**
103
+ * 请求拦截器使用:OA iframe 内优先用 OA token,否则用主 token
104
+ */
105
+ export const getRequestToken = () => {
106
+ if (isOaIframeMode() && getOaToken()) {
107
+ return getOaToken();
108
+ }
109
+ return getToken();
110
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * 后台返回的路由动态生成name 解决缓存问题
3
+ * 感谢 @fourteendp
4
+ * 详见 https://github.com/vbenjs/vue-vben-admin/issues/3927
5
+ */
6
+ import { Component, defineComponent, h } from 'vue';
7
+
8
+ interface Options {
9
+ name?: string;
10
+ }
11
+
12
+ export function createCustomNameComponent(loader: () => Promise<any>, options: Options = {}): () => Promise<Component> {
13
+ const { name } = options;
14
+ let component: Component | null = null;
15
+
16
+ const load = async () => {
17
+ try {
18
+ const { default: loadedComponent } = await loader();
19
+ component = loadedComponent;
20
+ } catch (error) {
21
+ console.error(`Cannot resolve component ${name}, error:`, error);
22
+ }
23
+ };
24
+
25
+ return async () => {
26
+ if (!component) {
27
+ await load();
28
+ }
29
+
30
+ return Promise.resolve(
31
+ defineComponent({
32
+ name,
33
+ render() {
34
+ return h(component as Component);
35
+ }
36
+ })
37
+ );
38
+ };
39
+ }
package/src/crypto.ts ADDED
@@ -0,0 +1,66 @@
1
+ import CryptoJS from 'crypto-js';
2
+
3
+ /**
4
+ * 随机生成32位的字符串
5
+ * @returns {string}
6
+ */
7
+ const generateRandomString = () => {
8
+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
9
+ let result = '';
10
+ const charactersLength = characters.length;
11
+ for (let i = 0; i < 32; i++) {
12
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
13
+ }
14
+ return result;
15
+ };
16
+
17
+ /**
18
+ * 随机生成aes 密钥
19
+ * @returns {string}
20
+ */
21
+ export const generateAesKey = () => {
22
+ return CryptoJS.enc.Utf8.parse(generateRandomString());
23
+ };
24
+
25
+ /**
26
+ * 加密base64
27
+ * @returns {string}
28
+ */
29
+ export const encryptBase64 = (str: CryptoJS.lib.WordArray) => {
30
+ return CryptoJS.enc.Base64.stringify(str);
31
+ };
32
+
33
+ /**
34
+ * 解密base64
35
+ */
36
+ export const decryptBase64 = (str: string) => {
37
+ return CryptoJS.enc.Base64.parse(str);
38
+ };
39
+
40
+ /**
41
+ * 使用密钥对数据进行加密
42
+ * @param message
43
+ * @param aesKey
44
+ * @returns {string}
45
+ */
46
+ export const encryptWithAes = (message: string, aesKey: CryptoJS.lib.WordArray) => {
47
+ const encrypted = CryptoJS.AES.encrypt(message, aesKey, {
48
+ mode: CryptoJS.mode.ECB,
49
+ padding: CryptoJS.pad.Pkcs7
50
+ });
51
+ return encrypted.toString();
52
+ };
53
+
54
+ /**
55
+ * 使用密钥对数据进行解密
56
+ * @param message
57
+ * @param aesKey
58
+ * @returns {string}
59
+ */
60
+ export const decryptWithAes = (message: string, aesKey: CryptoJS.lib.WordArray) => {
61
+ const decrypted = CryptoJS.AES.decrypt(message, aesKey, {
62
+ mode: CryptoJS.mode.ECB,
63
+ padding: CryptoJS.pad.Pkcs7
64
+ });
65
+ return decrypted.toString(CryptoJS.enc.Utf8);
66
+ };
@@ -0,0 +1,7 @@
1
+ export const errorCode: any = {
2
+ '401': '认证失败,无法访问系统资源',
3
+ '403': '当前操作没有权限',
4
+ '404': '访问资源不存在',
5
+ default: '系统未知错误,请反馈给管理员'
6
+ };
7
+ export default errorCode;
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @56os/shared-utils 聚合导出。
3
+ * 业务仓推荐按子路径引入,例如 `@56os/shared-utils/auth`。
4
+ */
5
+ export * from './auth';
6
+ export * from './crypto';
7
+ export * from './jsencrypt';
8
+ export { errorCode, default as errorCodeDefault } from './errorCode';
9
+ export { propTypes, default as ProjectTypes } from './propTypes';
10
+ export * from './validate';
11
+ export * from './scroll-to';
12
+ export * from './tableHeight';
13
+ export * from './officeFileViewer';
14
+ export * from './statusTag';
15
+ export * from './officeMutateGuard';
16
+ export * from './tableHeaderConfig';
17
+ export * from './createCustomNameComponent';
18
+ export * from './ruoyi';
@@ -0,0 +1,21 @@
1
+ import JSEncrypt from 'jsencrypt';
2
+ // 密钥对生成 http://web.chacuo.net/netrsakeypair
3
+
4
+ const publicKey = import.meta.env.VITE_APP_RSA_PUBLIC_KEY;
5
+
6
+ // 前端不建议存放私钥 不建议解密数据 因为都是透明的意义不大
7
+ const privateKey = import.meta.env.VITE_APP_RSA_PRIVATE_KEY;
8
+
9
+ // 加密
10
+ export const encrypt = (txt: string) => {
11
+ const encryptor = new JSEncrypt();
12
+ encryptor.setPublicKey(publicKey); // 设置公钥
13
+ return encryptor.encrypt(txt); // 对数据进行加密
14
+ };
15
+
16
+ // 解密
17
+ export const decrypt = (txt: string) => {
18
+ const encryptor = new JSEncrypt();
19
+ encryptor.setPrivateKey(privateKey); // 设置私钥
20
+ return encryptor.decrypt(txt); // 对数据进行解密
21
+ };
@@ -0,0 +1,59 @@
1
+ /** 预览页支持的后缀(与 OfficeFileViewer demo accept 对齐) */
2
+ const PREVIEWABLE_EXTS = [
3
+ 'pdf',
4
+ 'doc',
5
+ 'docx',
6
+ 'xls',
7
+ 'xlsx',
8
+ 'ppt',
9
+ 'pptx',
10
+ 'txt',
11
+ 'md',
12
+ 'csv',
13
+ 'png',
14
+ 'jpg',
15
+ 'jpeg',
16
+ 'gif',
17
+ 'webp'
18
+ ];
19
+
20
+ /**
21
+ * 从文件 URL 解析文件名(去掉 query)。
22
+ * @param url 文件地址
23
+ */
24
+ export function getFileNameFromUrl(url: string): string {
25
+ if (!url) {
26
+ return 'office-file';
27
+ }
28
+ try {
29
+ const path = decodeURIComponent(String(url).split('?')[0]);
30
+ const name = path.substring(path.lastIndexOf('/') + 1);
31
+ return name || 'office-file';
32
+ } catch {
33
+ return 'office-file';
34
+ }
35
+ }
36
+
37
+ /**
38
+ * 判断 URL 是否可用 OfficeFileViewer 预览。
39
+ * @param url 文件地址
40
+ */
41
+ export function isOfficePreviewableUrl(url: string): boolean {
42
+ const name = getFileNameFromUrl(url).toLowerCase();
43
+ const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1) : '';
44
+ return PREVIEWABLE_EXTS.includes(ext);
45
+ }
46
+
47
+ /**
48
+ * 新窗口打开主应用预览页 /office-file-viewer(仅携带 url,文件名由预览页从 url 解析)。
49
+ * 使用当前域名 origin;预览路由挂在主应用根路径,不拼接子应用 CONTEXT_PATH(如 /bo/)。
50
+ * @param url 文件地址
51
+ */
52
+ export function openOfficeFileViewer(url: string): void {
53
+ if (!url) {
54
+ return;
55
+ }
56
+ const viewerUrl = new URL('/office-file-viewer', window.location.origin);
57
+ viewerUrl.searchParams.set('url', String(url));
58
+ window.open(viewerUrl.toString(), '_blank', 'noopener,noreferrer');
59
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * 筛选条件下的增删改守卫(officeId / providerId / memberEnterpriseId / contractDeptId 等)。
3
+ * - 供应商端:始终允许(不可切公司)
4
+ * - 管理端:仅当「当前列表已查询生效」的筛选值与登录默认值一致时允许增删改
5
+ * (勿直接绑下拉草稿值:切换未点查询时列表仍是旧公司数据,按钮应保持跟列表一致)
6
+ * 查询 / 导出 / 下载 / 表头筛选 / 查看 不受此限制
7
+ */
8
+ export function canMutateByOfficeFilter(
9
+ selectedOfficeId: string | number | null | undefined,
10
+ currentOfficeId: string | number | null | undefined,
11
+ platformtype?: string
12
+ ): boolean {
13
+ if (platformtype === 'supplier') {
14
+ return true;
15
+ }
16
+ if (selectedOfficeId === '' || selectedOfficeId == null) {
17
+ return false;
18
+ }
19
+ if (currentOfficeId === '' || currentOfficeId == null) {
20
+ return false;
21
+ }
22
+ return String(selectedOfficeId) === String(currentOfficeId);
23
+ }
@@ -0,0 +1,26 @@
1
+ import { CSSProperties } from 'vue';
2
+ import VueTypes, { createTypes, toValidableType, VueTypeValidableDef, VueTypesInterface } from 'vue-types';
3
+
4
+ type PropTypes = VueTypesInterface & {
5
+ readonly style: VueTypeValidableDef<CSSProperties>;
6
+ readonly fieldOption: VueTypeValidableDef<Array<FieldOption>>;
7
+ };
8
+
9
+ const propTypes = createTypes({
10
+ func: undefined,
11
+ bool: undefined,
12
+ string: undefined,
13
+ number: undefined,
14
+ object: undefined,
15
+ integer: undefined
16
+ }) as PropTypes;
17
+
18
+ export default class ProjectTypes extends VueTypes {
19
+ static get style() {
20
+ return toValidableType('style', {
21
+ type: [String, Object],
22
+ default: undefined
23
+ });
24
+ }
25
+ }
26
+ export { propTypes };
package/src/ruoyi.ts ADDED
@@ -0,0 +1,306 @@
1
+ // 日期格式化
2
+ export function parseTime(time: any, pattern?: string) {
3
+ if (arguments.length === 0 || !time) {
4
+ return null;
5
+ }
6
+ const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
7
+ let date;
8
+ if (typeof time === 'object') {
9
+ date = time;
10
+ } else {
11
+ if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
12
+ time = parseInt(time);
13
+ } else if (typeof time === 'string') {
14
+ time = time
15
+ .replace(new RegExp(/-/gm), '/')
16
+ .replace('T', ' ')
17
+ .replace(new RegExp(/\.[\d]{3}/gm), '');
18
+ }
19
+ if (typeof time === 'number' && time.toString().length === 10) {
20
+ time = time * 1000;
21
+ }
22
+ date = new Date(time);
23
+ }
24
+ const formatObj: { [key: string]: any } = {
25
+ y: date.getFullYear(),
26
+ m: date.getMonth() + 1,
27
+ d: date.getDate(),
28
+ h: date.getHours(),
29
+ i: date.getMinutes(),
30
+ s: date.getSeconds(),
31
+ a: date.getDay()
32
+ };
33
+ return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: string, key: string) => {
34
+ let value = formatObj[key];
35
+ // Note: getDay() returns 0 on Sunday
36
+ if (key === 'a') {
37
+ return ['日', '一', '二', '三', '四', '五', '六'][value];
38
+ }
39
+ if (result.length > 0 && value < 10) {
40
+ value = '0' + value;
41
+ }
42
+ return value || 0;
43
+ });
44
+ }
45
+
46
+ /**
47
+ * 添加日期范围
48
+ * @param params
49
+ * @param dateRange
50
+ * @param propName
51
+ */
52
+ export const addDateRange = (params: any, dateRange: any[], propName?: string) => {
53
+ const search = params;
54
+ search.params = typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
55
+ dateRange = Array.isArray(dateRange) ? dateRange : [];
56
+ if (typeof propName === 'undefined') {
57
+ search.params['beginTime'] = dateRange[0];
58
+ search.params['endTime'] = dateRange[1];
59
+ } else {
60
+ search.params['begin' + propName] = dateRange[0];
61
+ search.params['end' + propName] = dateRange[1];
62
+ }
63
+ return search;
64
+ };
65
+
66
+ // 回显数据字典
67
+ export const selectDictLabel = (datas: any, value: number | string) => {
68
+ if (value === undefined) {
69
+ return '';
70
+ }
71
+ const actions: Array<string | number> = [];
72
+ Object.keys(datas).some((key) => {
73
+ if (datas[key].value == '' + value) {
74
+ actions.push(datas[key].label);
75
+ return true;
76
+ }
77
+ });
78
+ if (actions.length === 0) {
79
+ actions.push(value);
80
+ }
81
+ return actions.join('');
82
+ };
83
+
84
+ // 回显数据字典(字符串数组)
85
+ export const selectDictLabels = (datas: any, value: any, separator: any) => {
86
+ if (value === undefined || value.length === 0) {
87
+ return '';
88
+ }
89
+ if (Array.isArray(value)) {
90
+ value = value.join(',');
91
+ }
92
+ const actions: any[] = [];
93
+ const currentSeparator = undefined === separator ? ',' : separator;
94
+ const temp = value.split(currentSeparator);
95
+ Object.keys(value.split(currentSeparator)).some((val) => {
96
+ let match = false;
97
+ Object.keys(datas).some((key) => {
98
+ if (datas[key].value == '' + temp[val]) {
99
+ actions.push(datas[key].label + currentSeparator);
100
+ match = true;
101
+ }
102
+ });
103
+ if (!match) {
104
+ actions.push(temp[val] + currentSeparator);
105
+ }
106
+ });
107
+ return actions.join('').substring(0, actions.join('').length - 1);
108
+ };
109
+
110
+ // 字符串格式化(%s )
111
+ export function sprintf(str: string) {
112
+ if (arguments.length !== 0) {
113
+ let flag = true,
114
+ i = 1;
115
+ str = str.replace(/%s/g, function () {
116
+ const arg = arguments[i++];
117
+ if (typeof arg === 'undefined') {
118
+ flag = false;
119
+ return '';
120
+ }
121
+ return arg;
122
+ });
123
+ return flag ? str : '';
124
+ }
125
+ }
126
+
127
+ // 转换字符串,undefined,null等转化为""
128
+ export const parseStrEmpty = (str: any) => {
129
+ if (!str || str == 'undefined' || str == 'null') {
130
+ return '';
131
+ }
132
+ return str;
133
+ };
134
+
135
+ // 数据合并
136
+ export const mergeRecursive = (source: any, target: any) => {
137
+ for (const p in target) {
138
+ try {
139
+ if (target[p].constructor == Object) {
140
+ source[p] = mergeRecursive(source[p], target[p]);
141
+ } else {
142
+ source[p] = target[p];
143
+ }
144
+ } catch (e) {
145
+ source[p] = target[p];
146
+ }
147
+ }
148
+ return source;
149
+ };
150
+
151
+ /**
152
+ * 构造树型结构数据
153
+ * @param {*} data 数据源
154
+ * @param {*} id id字段 默认 'id'
155
+ * @param {*} parentId 父节点字段 默认 'parentId'
156
+ * @param {*} children 孩子节点字段 默认 'children'
157
+ */
158
+ export const handleTree = <T>(data: any[], id?: string, parentId?: string, children?: string): T[] => {
159
+ const config: {
160
+ id: string;
161
+ parentId: string;
162
+ childrenList: string;
163
+ } = {
164
+ id: id || 'id',
165
+ parentId: parentId || 'parentId',
166
+ childrenList: children || 'children'
167
+ };
168
+
169
+ const childrenListMap: any = {};
170
+ const nodeIds: any = {};
171
+ const tree: T[] = [];
172
+
173
+ for (const d of data) {
174
+ const parentId = d[config.parentId];
175
+ if (childrenListMap[parentId] == null) {
176
+ childrenListMap[parentId] = [];
177
+ }
178
+ nodeIds[d[config.id]] = d;
179
+ childrenListMap[parentId].push(d);
180
+ }
181
+
182
+ for (const d of data) {
183
+ const parentId = d[config.parentId];
184
+ if (nodeIds[parentId] == null) {
185
+ tree.push(d);
186
+ }
187
+ }
188
+ const adaptToChildrenList = (o: any) => {
189
+ if (childrenListMap[o[config.id]] !== null) {
190
+ o[config.childrenList] = childrenListMap[o[config.id]];
191
+ }
192
+ if (o[config.childrenList]) {
193
+ for (const c of o[config.childrenList]) {
194
+ adaptToChildrenList(c);
195
+ }
196
+ }
197
+ };
198
+
199
+ for (const t of tree) {
200
+ adaptToChildrenList(t);
201
+ }
202
+
203
+ return tree;
204
+ };
205
+
206
+ /**
207
+ * 参数处理
208
+ * @param {*} params 参数
209
+ */
210
+ export const tansParams = (params: any) => {
211
+ let result = '';
212
+ for (const propName of Object.keys(params)) {
213
+ const value = params[propName];
214
+ const part = encodeURIComponent(propName) + '=';
215
+ if (value !== null && value !== '' && typeof value !== 'undefined') {
216
+ if (typeof value === 'object') {
217
+ for (const key of Object.keys(value)) {
218
+ if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
219
+ const params = propName + '[' + key + ']';
220
+ const subPart = encodeURIComponent(params) + '=';
221
+ result += subPart + encodeURIComponent(value[key]) + '&';
222
+ }
223
+ }
224
+ } else {
225
+ result += part + encodeURIComponent(value) + '&';
226
+ }
227
+ }
228
+ }
229
+ return result;
230
+ };
231
+
232
+ /**
233
+ * 剔除查询对象中的空值(null / undefined / '' / 空数组 / 空对象),便于列表与导出传参。
234
+ * @param query 原始查询对象
235
+ * @returns 去掉空字段后的部分对象
236
+ */
237
+ export const omitEmptyQueryParams = <T extends Record<string, any>>(query?: T): Partial<T> => {
238
+ if (!query) {
239
+ return {};
240
+ }
241
+ return Object.fromEntries(
242
+ Object.entries(query).filter(([, value]) => {
243
+ if (value === null || value === undefined || value === '') {
244
+ return false;
245
+ }
246
+ if (Array.isArray(value) && value.length === 0) {
247
+ return false;
248
+ }
249
+ if (
250
+ typeof value === 'object' &&
251
+ !Array.isArray(value) &&
252
+ !(value instanceof Date) &&
253
+ Object.keys(value as object).length === 0
254
+ ) {
255
+ return false;
256
+ }
257
+ return true;
258
+ })
259
+ ) as Partial<T>;
260
+ };
261
+
262
+ // 返回项目路径
263
+ export const getNormalPath = (p: string): string => {
264
+ if (p.length === 0 || !p || p === 'undefined') {
265
+ return p;
266
+ }
267
+ const res = p.replace('//', '/');
268
+ if (res[res.length - 1] === '/') {
269
+ return res.slice(0, res.length - 1);
270
+ }
271
+ return res;
272
+ };
273
+
274
+ // 验证是否为blob格式
275
+ export const blobValidate = (data: any) => {
276
+ return data.type !== 'application/json';
277
+ };
278
+
279
+ export default {
280
+ handleTree
281
+ };
282
+ /** qiankun mount 生命周期写入,比 window 标志更可靠(unload 后再 mount 的竞态) */
283
+ let qiankunMountAlive = false;
284
+
285
+ export const setQiankunMountAlive = (alive: boolean) => {
286
+ qiankunMountAlive = Boolean(alive);
287
+ };
288
+
289
+ /**
290
+ * 是否作为 qiankun 子应用运行。
291
+ * 不依赖 vite-plugin-qiankun(避免共享包 peer 被 Vite stub 成空模块)。
292
+ */
293
+ export const isSubApp = () => {
294
+ if (qiankunMountAlive) return true;
295
+ if (typeof window !== 'undefined' && (window as any).__POWERED_BY_QIANKUN__) {
296
+ return true;
297
+ }
298
+ // DOM 兜底:已挂在宿主 sub-app-viewport 内
299
+ if (typeof document !== 'undefined') {
300
+ const appRoot = document.querySelector('#app');
301
+ if (appRoot?.closest?.('[id^="sub-app-viewport-"]')) {
302
+ return true;
303
+ }
304
+ }
305
+ return false;
306
+ };
@@ -0,0 +1,65 @@
1
+ const easeInOutQuad = (t: number, b: number, c: number, d: number) => {
2
+ t /= d / 2;
3
+ if (t < 1) {
4
+ return (c / 2) * t * t + b;
5
+ }
6
+ t--;
7
+ return (-c / 2) * (t * (t - 2) - 1) + b;
8
+ };
9
+
10
+ // requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
11
+ const requestAnimFrame = (function () {
12
+ return (
13
+ window.requestAnimationFrame ||
14
+ (window as any).webkitRequestAnimationFrame ||
15
+ (window as any).mozRequestAnimationFrame ||
16
+ function (callback) {
17
+ window.setTimeout(callback, 1000 / 60);
18
+ }
19
+ );
20
+ })();
21
+
22
+ /**
23
+ * Because it's so fucking difficult to detect the scrolling element, just move them all
24
+ * @param {number} amount
25
+ */
26
+ const move = (amount: number) => {
27
+ document.documentElement.scrollTop = amount;
28
+ (document.body.parentNode as HTMLElement).scrollTop = amount;
29
+ document.body.scrollTop = amount;
30
+ };
31
+
32
+ const position = () => {
33
+ return document.documentElement.scrollTop || (document.body.parentNode as HTMLElement).scrollTop || document.body.scrollTop;
34
+ };
35
+
36
+ /**
37
+ * @param {number} to
38
+ * @param {number} duration
39
+ * @param {Function} callback
40
+ */
41
+ export const scrollTo = (to: number, duration: number, callback?: any) => {
42
+ const start = position();
43
+ const change = to - start;
44
+ const increment = 20;
45
+ let currentTime = 0;
46
+ duration = typeof duration === 'undefined' ? 500 : duration;
47
+ const animateScroll = function () {
48
+ // increment the time
49
+ currentTime += increment;
50
+ // find the value with the quadratic in-out easing function
51
+ const val = easeInOutQuad(currentTime, start, change, duration);
52
+ // move the document.body
53
+ move(val);
54
+ // do the animation unless its over
55
+ if (currentTime < duration) {
56
+ requestAnimFrame(animateScroll);
57
+ } else {
58
+ if (callback && typeof callback === 'function') {
59
+ // the animation is done so lets callback
60
+ callback();
61
+ }
62
+ }
63
+ };
64
+ animateScroll();
65
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * 列表状态 Tag 类型推断(按展示文案语义)
3
+ */
4
+ export type StatusTagType = 'success' | 'warning' | 'danger' | 'info' | 'primary';
5
+
6
+ /**
7
+ * 根据状态文案推断 el-tag type
8
+ * @param label 状态展示文案
9
+ */
10
+ export function getStatusTagTypeByLabel(label: unknown): StatusTagType {
11
+ const t = String(label ?? '').trim();
12
+ if (!t) {
13
+ return 'info';
14
+ }
15
+ // 禁用偏提示而非错误
16
+ if (/(禁用|停用|未启用)/.test(t)) {
17
+ return 'warning';
18
+ }
19
+ if (/(失败|驳回|拒绝|作废|取消|关闭|异常|无效|删除|不通过|未通过)/.test(t)) {
20
+ return 'danger';
21
+ }
22
+ if (/(成功|完成|通过|启用|有效|已生成|已授权|已确认|已支付|已收款|已开票|正常|在用|生效|已到账|已审核)/.test(t)) {
23
+ return 'success';
24
+ }
25
+ if (/(待|审核中|认证中|生成中|授权中|进行中|处理中|执行中|部分|草稿|未生成|未授权|未确认)/.test(t)) {
26
+ return 'warning';
27
+ }
28
+ return 'info';
29
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 用户表头筛选配置应用工具。
3
+ *
4
+ * 注意:vxe-table 动态列仅改数组顺序往往不刷新 DOM 列序,
5
+ * 页面在调用本方法后需递增表格 :key(如 columnTableKey)强制重挂。
6
+ */
7
+
8
+ export interface TableHeaderConfigData {
9
+ config?: string;
10
+ sortconfig?: string;
11
+ withconfig?: string;
12
+ }
13
+
14
+ export interface TableHeaderColumnItem {
15
+ label?: string;
16
+ value: string;
17
+ show?: boolean;
18
+ width?: number | string;
19
+ columnNew?: boolean;
20
+ [key: string]: unknown;
21
+ }
22
+
23
+ const splitCsv = (value?: string) =>
24
+ String(value || '')
25
+ .split(',')
26
+ .filter(Boolean);
27
+
28
+ /**
29
+ * 按后端用户表头配置更新列显隐与顺序。
30
+ * @param columns 待处理列(会原地改 show/width 并返回新数组引用)
31
+ * @param resData getConfig 接口 data
32
+ * @param widthMap 可选列宽映射(label -> width)
33
+ * @returns { columns, selectedValues }
34
+ */
35
+ export function applyUserTableHeaderConfig<T extends TableHeaderColumnItem>(
36
+ columns: T[],
37
+ resData?: TableHeaderConfigData | null,
38
+ widthMap?: Record<string, number | string> | null
39
+ ): { columns: T[]; selectedValues: string[] } {
40
+ const list = (columns || []).map((col) => ({ ...col })) as T[];
41
+ if (!resData) {
42
+ return {
43
+ columns: list,
44
+ selectedValues: list.map((col) => col.value)
45
+ };
46
+ }
47
+
48
+ const selectedValues = splitCsv(resData.config);
49
+ const orderValues = splitCsv(resData.sortconfig || resData.config);
50
+
51
+ list.forEach((col) => {
52
+ if (col.columnNew && !selectedValues.includes(col.value)) {
53
+ selectedValues.push(col.value);
54
+ }
55
+ if (col.columnNew && !orderValues.includes(col.value)) {
56
+ orderValues.push(col.value);
57
+ }
58
+ });
59
+
60
+ list.forEach((col) => {
61
+ col.show = selectedValues.length === 0 ? true : selectedValues.includes(col.value);
62
+ if (widthMap && col.label && widthMap[col.label] != null) {
63
+ col.width = widthMap[col.label];
64
+ }
65
+ });
66
+
67
+ if (orderValues.length > 0) {
68
+ list.sort((a, b) => {
69
+ const aIndex = orderValues.indexOf(a.value);
70
+ const bIndex = orderValues.indexOf(b.value);
71
+ if (aIndex === -1) return 1;
72
+ if (bIndex === -1) return -1;
73
+ return aIndex - bIndex;
74
+ });
75
+ }
76
+
77
+ return {
78
+ columns: list,
79
+ selectedValues: selectedValues.length > 0 ? selectedValues : list.map((col) => col.value)
80
+ };
81
+ }
@@ -0,0 +1,41 @@
1
+ import type { App } from 'vue';
2
+ import { ref } from 'vue';
3
+
4
+ const DEFAULT_TABLE_HEIGHT_OFFSET = 430;
5
+ const DEFAULT_MIN_TABLE_HEIGHT = 320;
6
+ const FALLBACK_TABLE_HEIGHT = 480;
7
+
8
+ const tableHeightState = ref(FALLBACK_TABLE_HEIGHT);
9
+ let resizeListenerInstalled = false;
10
+
11
+ function getWindowHeight() {
12
+ if (typeof window === 'undefined') return 0;
13
+ return window.innerHeight || document.documentElement.clientHeight || FALLBACK_TABLE_HEIGHT;
14
+ }
15
+
16
+ export function calcTableHeight(offset = DEFAULT_TABLE_HEIGHT_OFFSET, minHeight = DEFAULT_MIN_TABLE_HEIGHT) {
17
+ const nextHeight = getWindowHeight() - offset;
18
+ return Math.max(nextHeight, minHeight);
19
+ }
20
+
21
+ function updateTableHeight() {
22
+ tableHeightState.value = calcTableHeight();
23
+ }
24
+
25
+ export function installGlobalTableHeight(app: App) {
26
+ updateTableHeight();
27
+
28
+ Object.defineProperty(app.config.globalProperties, 'tableHeight', {
29
+ configurable: true,
30
+ get() {
31
+ return tableHeightState.value;
32
+ }
33
+ });
34
+
35
+ app.config.globalProperties.$calcTableHeight = calcTableHeight;
36
+
37
+ if (!resizeListenerInstalled && typeof window !== 'undefined') {
38
+ resizeListenerInstalled = true;
39
+ window.addEventListener('resize', updateTableHeight);
40
+ }
41
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * 判断url是否是http或https
3
+ * @returns {Boolean}
4
+ * @param url
5
+ */
6
+ export const isHttp = (url: string): boolean => {
7
+ return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1;
8
+ };
9
+
10
+ /**
11
+ * 判断path是否为外链
12
+ * @param {string} path
13
+ * @returns {Boolean}
14
+ */
15
+ export const isExternal = (path: string) => {
16
+ return /^(https?:|mailto:|tel:)/.test(path);
17
+ };
18
+
19
+ /**
20
+ * @param {string} str
21
+ * @returns {Boolean}
22
+ */
23
+ export const validUsername = (str: string) => {
24
+ const valid_map = ['admin', 'editor'];
25
+ return valid_map.indexOf(str.trim()) >= 0;
26
+ };
27
+
28
+ /**
29
+ * @param {string} url
30
+ * @returns {Boolean}
31
+ */
32
+ export const validURL = (url: string) => {
33
+ const reg =
34
+ /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
35
+ return reg.test(url);
36
+ };
37
+
38
+ /**
39
+ * @param {string} str
40
+ * @returns {Boolean}
41
+ */
42
+ export const validLowerCase = (str: string) => {
43
+ const reg = /^[a-z]+$/;
44
+ return reg.test(str);
45
+ };
46
+
47
+ /**
48
+ * @param {string} str
49
+ * @returns {Boolean}
50
+ */
51
+ export const validUpperCase = (str: string) => {
52
+ const reg = /^[A-Z]+$/;
53
+ return reg.test(str);
54
+ };
55
+
56
+ /**
57
+ * @param {string} str
58
+ * @returns {Boolean}
59
+ */
60
+ export const validAlphabets = (str: string) => {
61
+ const reg = /^[A-Za-z]+$/;
62
+ return reg.test(str);
63
+ };
64
+
65
+ /**
66
+ * @param {string} email
67
+ * @returns {Boolean}
68
+ */
69
+ export const validEmail = (email: string) => {
70
+ const reg =
71
+ /^(([^<>()\]\\.,;:\s@"]+(\.[^<>()\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
72
+ return reg.test(email);
73
+ };
74
+
75
+ /**
76
+ * @param {string} str
77
+ * @returns {Boolean}
78
+ */
79
+ export const isString = (str: any) => {
80
+ return typeof str === 'string' || str instanceof String;
81
+ };
82
+
83
+ /**
84
+ * @param {Array} arg
85
+ * @returns {Boolean}
86
+ */
87
+ export const isArray = (arg: string | string[]) => {
88
+ if (typeof Array.isArray === 'undefined') {
89
+ return Object.prototype.toString.call(arg) === '[object Array]';
90
+ }
91
+ return Array.isArray(arg);
92
+ };