@fairys/taro-tools-react 0.0.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.
Files changed (62) hide show
  1. package/README.md +1 -0
  2. package/esm/components/EnterLoading/index.d.ts +14 -0
  3. package/esm/components/EnterLoading/index.js +65 -0
  4. package/esm/components/MainPage/index.d.ts +10 -0
  5. package/esm/components/MainPage/index.js +49 -0
  6. package/esm/components/Mesage/index.d.ts +48 -0
  7. package/esm/components/Mesage/index.js +122 -0
  8. package/esm/components/Portal/index.d.ts +8 -0
  9. package/esm/components/Portal/index.js +11 -0
  10. package/esm/components/Toast/index.d.ts +1 -0
  11. package/esm/components/Toast/index.js +20 -0
  12. package/esm/components/connectToastMessage/index.d.ts +10 -0
  13. package/esm/components/connectToastMessage/index.js +28 -0
  14. package/esm/components/index.d.ts +6 -0
  15. package/esm/components/index.js +6 -0
  16. package/esm/context/global.data.instance.d.ts +5411 -0
  17. package/esm/context/global.data.instance.js +66 -0
  18. package/esm/context/global.setting.data.instance.d.ts +28 -0
  19. package/esm/context/global.setting.data.instance.js +20 -0
  20. package/esm/context/index.d.ts +4 -0
  21. package/esm/context/index.js +4 -0
  22. package/esm/context/page.data.instance.d.ts +71 -0
  23. package/esm/context/page.data.instance.js +139 -0
  24. package/esm/context/page.info.data.instance.d.ts +72 -0
  25. package/esm/context/page.info.data.instance.js +107 -0
  26. package/esm/index.d.ts +3 -0
  27. package/esm/index.js +3 -0
  28. package/esm/styles/index.css +711 -0
  29. package/esm/utils/index.d.ts +4 -0
  30. package/esm/utils/index.js +4 -0
  31. package/esm/utils/navigate.d.ts +109 -0
  32. package/esm/utils/navigate.js +45 -0
  33. package/esm/utils/request.d.ts +112 -0
  34. package/esm/utils/request.js +212 -0
  35. package/esm/utils/useId.d.ts +2 -0
  36. package/esm/utils/useId.js +13 -0
  37. package/esm/utils/valtio/index.d.ts +9 -0
  38. package/esm/utils/valtio/index.js +23 -0
  39. package/esm/utils/valtio/instance.d.ts +15 -0
  40. package/esm/utils/valtio/instance.js +34 -0
  41. package/lib/index.js +78 -0
  42. package/package.json +40 -0
  43. package/src/components/EnterLoading/index.tsx +57 -0
  44. package/src/components/MainPage/index.tsx +72 -0
  45. package/src/components/Mesage/index.tsx +217 -0
  46. package/src/components/Portal/index.tsx +18 -0
  47. package/src/components/Toast/index.tsx +22 -0
  48. package/src/components/connectToastMessage/index.tsx +41 -0
  49. package/src/components/index.ts +6 -0
  50. package/src/context/global.data.instance.ts +106 -0
  51. package/src/context/global.setting.data.instance.ts +36 -0
  52. package/src/context/index.ts +4 -0
  53. package/src/context/page.data.instance.ts +215 -0
  54. package/src/context/page.info.data.instance.ts +182 -0
  55. package/src/index.ts +3 -0
  56. package/src/styles/index.css +515 -0
  57. package/src/utils/index.ts +4 -0
  58. package/src/utils/navigate.ts +159 -0
  59. package/src/utils/request.ts +319 -0
  60. package/src/utils/useId.ts +14 -0
  61. package/src/utils/valtio/index.ts +23 -0
  62. package/src/utils/valtio/instance.ts +59 -0
@@ -0,0 +1,319 @@
1
+ import Taro from '@tarojs/taro';
2
+ import { globalSettingDataInstance } from 'context/global.setting.data.instance';
3
+ import { globalDataInstance } from 'context/global.data.instance';
4
+
5
+ const codeMessage = {
6
+ // 200: '服务器成功返回请求的数据',
7
+ // 201: '新建或修改数据成功',
8
+ 400: '发出的请求错误',
9
+ 401: '用户没有权限',
10
+ 403: '用户访问被禁止',
11
+ 404: '请求不存在,服务器没有进行操作',
12
+ 406: '请求的格式错误',
13
+ 410: '资源被永久删除',
14
+ 422: '验证错误',
15
+ 500: '服务器发生错误,请检查服务器',
16
+ 502: 'nginx异常',
17
+ 503: '服务不可用,服务器暂时过载或维护',
18
+ 504: 'nginx超时',
19
+ } as const;
20
+
21
+ export interface RequestInstanceOptions extends Taro.request.Option<any, any> {
22
+ /**模块名称*/
23
+ module?: string;
24
+ /**是否忽略token*/
25
+ isIgnoreToken?: boolean;
26
+ /**是否提示错误信息*/
27
+ isShowErrorMessage?: boolean;
28
+ }
29
+
30
+ /**处理提示信息*/
31
+ const requestResponseHandle = (result: Taro.request.SuccessCallbackResult<any>, options?: RequestInstanceOptions) => {
32
+ let msg = '';
33
+ try {
34
+ const statusCode = result.statusCode;
35
+ const code = result?.data?.code;
36
+ if (result?.data) {
37
+ if (statusCode === 401 || code === 401) {
38
+ // 权限问题 ,重新登录
39
+ msg = '请重新登录';
40
+ /**重新跳转登录页面*/
41
+ globalDataInstance.toLoginPage();
42
+ } else if (![globalSettingDataInstance.store.requestSuccessCode, 200].includes(code)) {
43
+ // 提示内容
44
+ msg = result?.data?.message || '接口异常';
45
+ }
46
+ } else {
47
+ msg = codeMessage[result?.statusCode];
48
+ }
49
+ } catch (error) {
50
+ msg = codeMessage[result?.statusCode];
51
+ console.log(error);
52
+ }
53
+ if (msg && options?.isShowErrorMessage !== false) {
54
+ globalDataInstance.showMessage({
55
+ content: msg || '请求发生错误',
56
+ type: 'error',
57
+ });
58
+ }
59
+ };
60
+
61
+ export interface RequestInstanceCreateOptions {
62
+ /**
63
+ * 本地存储token字段名
64
+ * @default token
65
+ */
66
+ tokenFieldName?: string;
67
+ /**
68
+ * 请求头token字段名
69
+ * @default token
70
+ */
71
+ headerTokenName?: string;
72
+ /**
73
+ * 公共请求配置
74
+ * @default {}
75
+ */
76
+ commonOptions?: Omit<Taro.request.Option<any, any>, 'url'>;
77
+
78
+ /**
79
+ * 请求IP地址
80
+ * @default ''
81
+ */
82
+ IP?: string | ((url: string, module?: string, env?: string) => string);
83
+ /**
84
+ * 简单的代理配置
85
+ * @default {}
86
+ */
87
+ proxy?: {
88
+ dev: Record<string, string | { target: string; pathRewrite: Record<string, string> }>;
89
+ pro: Record<string, string | { target: string; pathRewrite: Record<string, string> }>;
90
+ };
91
+ }
92
+
93
+ export class RequestInstance {
94
+ /**请求IP地址*/
95
+ public IP?: string | ((url: string, module?: string, env?: string) => string);
96
+ /**简单的代理配置*/
97
+ public proxy?: RequestInstanceCreateOptions['proxy'];
98
+ /**
99
+ * 本地存储token字段名
100
+ * @default token
101
+ */
102
+ public tokenFieldName = 'token';
103
+ /**
104
+ * 请求头token字段名
105
+ * @default token
106
+ */
107
+ public headerTokenName = 'token';
108
+ /**公共请求配置*/
109
+ public commonOptions: Omit<Taro.request.Option<any, any>, 'url'> = {};
110
+
111
+ constructor(options: RequestInstanceCreateOptions = {}) {
112
+ this.extends(options);
113
+ }
114
+
115
+ /**创建实例*/
116
+ static create(options: RequestInstanceCreateOptions = {}) {
117
+ const request = new RequestInstance(options);
118
+ return request;
119
+ }
120
+
121
+ /**扩展请求配置*/
122
+ extends = (options: RequestInstanceCreateOptions = {}) => {
123
+ this.IP = options.IP || this.IP;
124
+ this.proxy = options.proxy || this.proxy;
125
+ this.tokenFieldName = options.tokenFieldName || this.tokenFieldName;
126
+ this.headerTokenName = options.headerTokenName || this.headerTokenName;
127
+ this.commonOptions = { ...this.commonOptions, ...options.commonOptions };
128
+ return this;
129
+ };
130
+
131
+ /**获取请求地址*/
132
+ public getHttpPath = (url: string, module?: string) => {
133
+ if (typeof this.IP === 'function') {
134
+ return this.IP(url, module, process.env.NODE_ENV) || '';
135
+ }
136
+ return this.IP || '';
137
+ };
138
+
139
+ /**获取转换后地址*/
140
+ public getProxyHost = (url: string, module?: string) => {
141
+ let host = '';
142
+ let _url = url;
143
+ /**h5中不用代理*/
144
+ if (process.env.TARO_ENV === 'h5') {
145
+ return {
146
+ host: '',
147
+ url: _url,
148
+ };
149
+ }
150
+ if (this.proxy) {
151
+ const proxy = this.proxy[process.env.NODE_ENV === 'production' ? 'pro' : 'dev'];
152
+ if (proxy)
153
+ for (const key in proxy) {
154
+ const rgx = new RegExp(key);
155
+ const item = proxy[key];
156
+ if (rgx.test(url) && item) {
157
+ if (typeof item === 'string') {
158
+ host = item;
159
+ } else if (item?.target) {
160
+ host = item.target;
161
+ if (item.pathRewrite) {
162
+ for (const key in item.pathRewrite) {
163
+ const rgx = new RegExp(key);
164
+ _url = url.replace(rgx, item.pathRewrite[key]);
165
+ }
166
+ }
167
+ }
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ if (!host) {
173
+ host = this.getHttpPath(url, module);
174
+ }
175
+ return {
176
+ host,
177
+ url: _url,
178
+ };
179
+ };
180
+
181
+ /**格式化地址*/
182
+ formatUrl = (url: string, module?: string) => {
183
+ let { host, url: _url } = this.getProxyHost(url, module);
184
+ if (host) {
185
+ host = host.replace(/\/$/, '');
186
+ }
187
+ const newUrl = `${_url}`.replace(/^\//, '').replace(/\/$/, '');
188
+ if (module && process.env.NODE_ENV === 'production') {
189
+ const m = `${module}`.replace(/^\//, '').replace(/\/$/, '');
190
+ return `${host}/${m}/${newUrl}`;
191
+ }
192
+ return `${host}/${newUrl}`;
193
+ };
194
+
195
+ /**发送请求,返回 Taro.RequestTask */
196
+ requestBase = (options: RequestInstanceOptions) => {
197
+ const { data, header = {}, module, isIgnoreToken, isShowErrorMessage, ...restOptions } = options;
198
+ const token = Taro.getStorageSync(this.tokenFieldName || 'token');
199
+ const newHeader = { ...header };
200
+ if (token) {
201
+ newHeader[this.headerTokenName || 'token'] = token;
202
+ } else {
203
+ if (isIgnoreToken !== true) {
204
+ // 跳转登录页
205
+ if (isShowErrorMessage !== false) {
206
+ globalDataInstance.showMessage({
207
+ content: '未登录',
208
+ type: 'error',
209
+ });
210
+ }
211
+ options?.fail?.({ errMsg: '未登录' });
212
+ globalDataInstance.toLoginPage();
213
+ return undefined;
214
+ }
215
+ }
216
+ return Taro.request({
217
+ ...this.commonOptions,
218
+ ...restOptions,
219
+ header: {
220
+ ...newHeader,
221
+ ...(options?.header || {}),
222
+ },
223
+ url: this.formatUrl(options.url, module),
224
+ success: (result) => {
225
+ /**处理提示
226
+ * 使用 global 状态管理
227
+ * */
228
+ requestResponseHandle(result, options);
229
+ options?.success?.(result);
230
+ },
231
+ fail: (result) => {
232
+ if (isShowErrorMessage !== false) {
233
+ globalDataInstance.showMessage({
234
+ content: result.errMsg || '请求发生错误',
235
+ type: 'error',
236
+ });
237
+ }
238
+ options?.fail?.(result);
239
+ },
240
+ });
241
+ };
242
+
243
+ /**发送请求,返回 Promise */
244
+ request = (options: RequestInstanceOptions): Promise<{ code?: number; data?: any; message?: string }> => {
245
+ return new Promise((resolve, reject) => {
246
+ this.requestBase({
247
+ ...options,
248
+ success: (result) => {
249
+ options?.success?.(result);
250
+ resolve(result?.data);
251
+ },
252
+ fail: (result) => {
253
+ options?.fail?.(result);
254
+ reject(result);
255
+ },
256
+ });
257
+ });
258
+ };
259
+
260
+ /**GET请求*/
261
+ GET = (options: RequestInstanceOptions) => {
262
+ try {
263
+ return this.request({
264
+ ...options,
265
+ method: 'GET',
266
+ });
267
+ } catch (error) {
268
+ throw error;
269
+ }
270
+ };
271
+
272
+ /**POST请求*/
273
+ POST = (options: RequestInstanceOptions) => {
274
+ try {
275
+ return this.request({
276
+ ...options,
277
+ method: 'POST',
278
+ });
279
+ } catch (error) {
280
+ throw error;
281
+ }
282
+ };
283
+
284
+ /**发送formData格式数据*/
285
+ formData = (options: RequestInstanceOptions) => {
286
+ try {
287
+ return this.request({
288
+ ...options,
289
+ method: 'POST',
290
+ header: {
291
+ 'Content-Type': 'multipart/form-data',
292
+ ...(options.header || {}),
293
+ },
294
+ });
295
+ } catch (error) {
296
+ throw error;
297
+ }
298
+ };
299
+
300
+ /**发送x-www-form-urlencoded格式数据*/
301
+ xFormUrlEncoded = (options: RequestInstanceOptions) => {
302
+ try {
303
+ return this.request({
304
+ ...options,
305
+ method: 'POST',
306
+ header: {
307
+ 'Content-Type': 'application/x-www-form-urlencoded',
308
+ ...(options.header || {}),
309
+ },
310
+ });
311
+ } catch (error) {
312
+ throw error;
313
+ }
314
+ };
315
+ }
316
+
317
+ /** 请求*/
318
+ export const request = new RequestInstance();
319
+ export default request;
@@ -0,0 +1,14 @@
1
+ import { useRef, useMemo } from 'react';
2
+ let localId = 0;
3
+
4
+ export const createUseId = (suffix: string = 'D') => {
5
+ const count = localId++;
6
+ return `FAIRYS_TARO_UI_${count.toString(32)}_${suffix}`;
7
+ };
8
+
9
+ export const useId = (suffix: string = 'D') => {
10
+ const count = useRef(localId++);
11
+ return useMemo(() => {
12
+ return `FAIRYS_TARO_UI_${count.current.toString(32)}_${suffix}`;
13
+ }, [count.current]);
14
+ };
@@ -0,0 +1,23 @@
1
+ import { useRef } from 'react';
2
+ import { useSnapshot } from 'valtio';
3
+ import { ProxyInstanceObjectBase } from './instance';
4
+ export * from './instance';
5
+
6
+ /**创建简单的状态管理*/
7
+ export const useValtioState = <T extends object>(inital?: T) => {
8
+ const instance = useRef(new ProxyInstanceObjectBase<T>()._ctor(inital)).current;
9
+ const state = useSnapshot(instance.store);
10
+ return [state, instance, (state as any).__defaultValue] as const;
11
+ };
12
+
13
+ export const useValtioInstaceState = <
14
+ T extends object = any,
15
+ K extends ProxyInstanceObjectBase<T> = ProxyInstanceObjectBase<T>,
16
+ M extends { new (...args: any[]): K } = { new (...args: any[]): K },
17
+ >(
18
+ Instance: M,
19
+ ) => {
20
+ const instance = useRef(new Instance()).current;
21
+ const state = useSnapshot(instance.store);
22
+ return [state, instance, (state as any).__defaultValue] as const;
23
+ };
@@ -0,0 +1,59 @@
1
+ import { proxy, ref } from 'valtio';
2
+ import React from 'react';
3
+
4
+ /**
5
+ * 单个proxy对象数据基础实例封装
6
+ */
7
+ export class ProxyInstanceObjectBase<T extends Object = any> {
8
+ /**proxy 可状态更新字段 */
9
+ store = proxy<T>({} as T);
10
+
11
+ /**初始化存储值*/
12
+ _ctor = (inital?: Partial<T>, fields?: string[]) => {
13
+ this._setValues(inital || {}, fields);
14
+ return this;
15
+ };
16
+
17
+ /**更新store数据 循环对象进行存储,当值是对象的时候存储为ref*/
18
+ _setValues = <K = T>(values: Partial<K>, fields?: string[]) => {
19
+ if (!this.store) {
20
+ this.store = proxy({}) as T;
21
+ }
22
+ Object.keys(values).forEach((key) => {
23
+ const value = values[key];
24
+ if (Array.isArray(fields) && fields.includes(key)) {
25
+ this.store[key] = values[key];
26
+ } else if (React.isValidElement(value) || typeof value === 'function') {
27
+ this.store[key] = ref(values[key]);
28
+ } else if (typeof value === 'object' && value !== null) {
29
+ this.store[key] = ref(values[key]);
30
+ } else {
31
+ this.store[key] = values[key];
32
+ }
33
+ });
34
+ return this;
35
+ };
36
+
37
+ /**删除字段值*/
38
+ _deleteValue = (names: string | string[]) => {
39
+ if (Array.isArray(names)) {
40
+ let cacheValue = this.store;
41
+ const newNames = [...names];
42
+ const lastField = newNames.pop();
43
+ for (let index = 0; index < newNames.length; index++) {
44
+ cacheValue = cacheValue[newNames[index]];
45
+ }
46
+ if (cacheValue && lastField) {
47
+ delete cacheValue[lastField];
48
+ }
49
+ } else {
50
+ delete this.store[names];
51
+ }
52
+ return this;
53
+ };
54
+
55
+ /**创建 ref 对象 (ref对象不做监听更新)*/
56
+ _createRef = <K extends Object = any>(inital?: K) => {
57
+ return ref<K>(inital || ({} as K)) as K;
58
+ };
59
+ }