@tmagic/utils 1.0.0-beta.1

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.
@@ -0,0 +1,18 @@
1
+ import { MNode } from '@tmagic/schema';
2
+ export declare const sleep: (ms: number) => Promise<void>;
3
+ export declare const datetimeFormatter: (v: string | Date, defaultValue?: string, f?: string) => string | number;
4
+ export declare const asyncLoadJs: (url: string, crossOrigin?: string | undefined, document?: Document) => any;
5
+ export declare const asyncLoadCss: (url: string) => Promise<unknown>;
6
+ export declare const toLine: (name?: string) => string;
7
+ export declare const toHump: (name?: string) => string;
8
+ export declare const emptyFn: () => any;
9
+ /**
10
+ * 通过id获取组件在应用的子孙路径
11
+ * @param {number | string} id 组件id
12
+ * @param {Array} data 要查找的根容器节点
13
+ * @return {Array} 组件在data中的子孙路径
14
+ */
15
+ export declare const getNodePath: (id: number | string, data?: MNode[]) => MNode[];
16
+ export declare const filterXSS: (str: string) => string;
17
+ export declare const getUrlParam: (param: string, url?: string | undefined) => string;
18
+ export declare const isPop: (node: MNode) => boolean;
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client" />
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "version": "1.0.0-beta.1",
3
+ "name": "@tmagic/utils",
4
+ "main": "dist/magic-utils.umd.js",
5
+ "module": "dist/magic-utils.es.js",
6
+ "types": "dist/types/src/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/magic-utils.es.js",
10
+ "require": "./dist/magic-utils.umd.js"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "build": "vite build"
15
+ },
16
+ "engines": {
17
+ "node": ">=14"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/Tencent/tmagic-editor.git"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^15.12.4",
25
+ "typescript": "^4.3.4",
26
+ "vite": "^2.3.7",
27
+ "vite-plugin-dts": "^0.9.6"
28
+ }
29
+ }
package/src/index.ts ADDED
@@ -0,0 +1,184 @@
1
+ /*
2
+ * Tencent is pleased to support the open source community by making TMagicEditor available.
3
+ *
4
+ * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import moment from 'moment';
20
+
21
+ import { MNode } from '@tmagic/schema';
22
+
23
+ export const sleep = (ms: number): Promise<void> =>
24
+ new Promise((resolve) => {
25
+ const timer = setTimeout(() => {
26
+ clearTimeout(timer);
27
+ resolve();
28
+ }, ms);
29
+ });
30
+
31
+ export const datetimeFormatter = (v: string | Date, defaultValue = '-', f = 'YYYY-MM-DD HH:mm:ss') => {
32
+ let format = f;
33
+ if (format === 'timestamp') {
34
+ format = 'x';
35
+ }
36
+
37
+ if (v) {
38
+ let time = null;
39
+ if ((typeof v === 'string' && v.includes('Z')) || v.constructor === Date) {
40
+ // UTC字符串时间或Date对象格式化为北京时间
41
+ time = moment(v).utcOffset('+08:00').format(format);
42
+ } else {
43
+ time = moment(v).format(format);
44
+ }
45
+
46
+ if (format === 'x') {
47
+ return +time;
48
+ }
49
+ // 格式化为北京时间
50
+ if (time !== 'Invalid date') {
51
+ return time;
52
+ }
53
+ return defaultValue;
54
+ }
55
+ return defaultValue;
56
+ };
57
+
58
+ export const asyncLoadJs = (() => {
59
+ // 正在加载或加载成功的存入此Map中
60
+ const documentMap = new Map();
61
+
62
+ return (url: string, crossOrigin?: string, document = globalThis.document) => {
63
+ let loaded = documentMap.get(document);
64
+ if (!loaded) {
65
+ loaded = new Map();
66
+ documentMap.set(document, loaded);
67
+ }
68
+
69
+ // 正在加载或已经加载成功的,直接返回
70
+ if (loaded.get(url)) return loaded.get(url);
71
+
72
+ const load = new Promise<void>((resolve, reject) => {
73
+ const script = document.createElement('script');
74
+ script.type = 'text/javascript';
75
+ if (crossOrigin) {
76
+ script.crossOrigin = crossOrigin;
77
+ }
78
+ script.src = url;
79
+ document.body.appendChild(script);
80
+ script.onload = () => {
81
+ resolve();
82
+ };
83
+ script.onerror = () => {
84
+ reject(new Error('加载失败'));
85
+ };
86
+ setTimeout(() => {
87
+ reject(new Error('timeout'));
88
+ }, 60 * 1000);
89
+ }).catch((err) => {
90
+ // 加载失败的,从map中移除,第二次加载时,可以再次执行加载
91
+ loaded.delete(url);
92
+ throw err;
93
+ });
94
+
95
+ loaded.set(url, load);
96
+ return loaded.get(url);
97
+ };
98
+ })();
99
+
100
+ export const asyncLoadCss = function (url: string) {
101
+ return new Promise((resolve, reject) => {
102
+ const hasLoaded = globalThis.document.querySelector(`link[href="${url}"]`);
103
+ if (hasLoaded) {
104
+ resolve(undefined);
105
+ return;
106
+ }
107
+
108
+ const node = document.createElement('link');
109
+ node.rel = 'stylesheet';
110
+ node.href = url;
111
+ document.getElementsByTagName('head')[0].appendChild(node);
112
+ node.onload = resolve;
113
+ node.onerror = reject;
114
+ });
115
+ };
116
+
117
+ // 驼峰转换横线
118
+ export const toLine = (name = '') => name.replace(/\B([A-Z])/g, '-$1').toLowerCase();
119
+
120
+ export const toHump = (name = ''): string => name.replace(/-(\w)/g, (all, letter) => letter.toUpperCase());
121
+
122
+ export const emptyFn = (): any => undefined;
123
+
124
+ /**
125
+ * 通过id获取组件在应用的子孙路径
126
+ * @param {number | string} id 组件id
127
+ * @param {Array} data 要查找的根容器节点
128
+ * @return {Array} 组件在data中的子孙路径
129
+ */
130
+ export const getNodePath = (id: number | string, data: MNode[] = []): MNode[] => {
131
+ const path: MNode[] = [];
132
+
133
+ const get = function (id: number | string, data: MNode[]): MNode | null {
134
+ if (!Array.isArray(data)) {
135
+ return null;
136
+ }
137
+
138
+ for (let i = 0, l = data.length; i < l; i++) {
139
+ const item: any = data[i];
140
+
141
+ path.push(item);
142
+ if (`${item.id}` === `${id}`) {
143
+ return item;
144
+ }
145
+
146
+ if (item.items) {
147
+ const node = get(id, item.items);
148
+ if (node) {
149
+ return node;
150
+ }
151
+ }
152
+
153
+ path.pop();
154
+ }
155
+
156
+ return null;
157
+ };
158
+
159
+ get(id, data);
160
+
161
+ return path;
162
+ };
163
+
164
+ export const filterXSS = (str: string) =>
165
+ str.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
166
+
167
+ export const getUrlParam = (param: string, url?: string) => {
168
+ const u = url || location.href;
169
+ const reg = new RegExp(`[?&#]${param}=([^&#]+)`, 'gi');
170
+
171
+ const matches = u.match(reg);
172
+ let strArr;
173
+ if (matches && matches.length > 0) {
174
+ strArr = matches[matches.length - 1].split('=');
175
+ if (strArr && strArr.length > 1) {
176
+ // 过滤XSS字符
177
+ return filterXSS(strArr[1]);
178
+ }
179
+ return '';
180
+ }
181
+ return '';
182
+ };
183
+
184
+ export const isPop = (node: MNode): boolean => node.type.toLowerCase().endsWith('pop');
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client" />
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "baseUrl": "../..",
5
+ },
6
+ "exclude": [
7
+ "**/dist/**/*"
8
+ ],
9
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,45 @@
1
+ /*
2
+ * Tencent is pleased to support the open source community by making TMagicEditor available.
3
+ *
4
+ * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import { defineConfig } from 'vite';
20
+ import dts from 'vite-plugin-dts';
21
+
22
+ export default defineConfig({
23
+ plugins: [
24
+ dts({
25
+ outputDir: 'dist/types',
26
+ include: ['src/**/*'],
27
+ staticImport: true,
28
+ insertTypesEntry: true,
29
+ logDiagnostics: true,
30
+ }),
31
+ ],
32
+
33
+ build: {
34
+ cssCodeSplit: false,
35
+ sourcemap: true,
36
+ minify: false,
37
+ target: 'esnext',
38
+
39
+ lib: {
40
+ entry: 'src/index.ts',
41
+ name: 'TMagicUtils',
42
+ fileName: 'tmagic-utils',
43
+ },
44
+ },
45
+ });