zmdms-utils 0.0.85 → 0.0.87

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/dist/es/file.d.ts CHANGED
@@ -99,11 +99,15 @@ interface IDownloadOptions extends IOptions {
99
99
  waterMark?: boolean | string;
100
100
  /** 是否开发不需要登录信息 */
101
101
  open?: boolean;
102
+ /** 是否解析异常blob结果 */
103
+ parseErrorBlob?: boolean;
102
104
  }
103
105
  interface IBatchDownloadOptions extends IOptions {
104
106
  zipName: string;
105
107
  /** 是否添加水印 */
106
108
  waterMark?: boolean | string;
109
+ /** 是否解析异常blob结果 */
110
+ parseErrorBlob?: boolean;
107
111
  }
108
112
  interface IDownloadLinkOptions extends Partial<IOptions> {
109
113
  /** 不需要登录信息的附件下载链接 */
@@ -124,5 +128,14 @@ interface IThumbnailLinkOptions extends Partial<IOptions> {
124
128
  /** 缩放比例 */
125
129
  scale?: number;
126
130
  }
131
+ /**
132
+ * 加密附件ID
133
+ * @param fileId 附件ID
134
+ * @description 加密方式
135
+ * 1. 都会通过encrypt加密一次
136
+ * 2. 如果参数是通过地址栏传输的,附件预览:encode一次;附件下载:encode两次;
137
+ * 3. 如果参数是通过body传输的,只需要encode一次
138
+ */
139
+ declare function encodeFileId(fileId: string, encodeNum?: number): string;
127
140
 
128
- export { batchDownloadFiles, createDeleteFileLink, createDownloadLink, createOriginalLink, createThumbnailLink, createUploadFileLink, downloadFile, exportBolb, previewFile };
141
+ export { batchDownloadFiles, createDeleteFileLink, createDownloadLink, createOriginalLink, createThumbnailLink, createUploadFileLink, downloadFile, encodeFileId, exportBolb, previewFile };
package/dist/es/file.js CHANGED
@@ -19,7 +19,7 @@ var isZmdmsFileService = FILE_SERVICE === "zmdms";
19
19
  * @param options.open boolean 是否不需要登录信息
20
20
  */
21
21
  function downloadFile(fileId, fileName, options) {
22
- var API_BASEURL = options.API_BASEURL, authToken = options.authToken, _a = options.waterMark, waterMark = _a === void 0 ? true : _a, open = options.open;
22
+ var API_BASEURL = options.API_BASEURL, authToken = options.authToken, _a = options.waterMark, waterMark = _a === void 0 ? true : _a, open = options.open, _b = options.parseErrorBlob, parseErrorBlob = _b === void 0 ? false : _b;
23
23
  if (isZmdmsFileService) {
24
24
  fileId = encodeFileId(fileId, 2);
25
25
  }
@@ -49,7 +49,32 @@ function downloadFile(fileId, fileName, options) {
49
49
  resolve({ msg: "文件下载成功!" });
50
50
  }
51
51
  else {
52
- reject(xhr.response);
52
+ if (!parseErrorBlob) {
53
+ reject(xhr.response);
54
+ return;
55
+ }
56
+ try {
57
+ if (Object.prototype.toString.call(xhr.response) === "[object Blob]") {
58
+ var blob = xhr.response;
59
+ blob
60
+ .text()
61
+ .then(function (text) {
62
+ var json = JSON.parse(text);
63
+ reject(json);
64
+ })
65
+ .catch(function (err) {
66
+ reject({
67
+ msg: (err === null || err === void 0 ? void 0 : err.message) || (err === null || err === void 0 ? void 0 : err.msg) || "下载失败!",
68
+ code: xhr.status,
69
+ });
70
+ });
71
+ }
72
+ }
73
+ catch (err) {
74
+ reject({
75
+ msg: "下载失败!",
76
+ });
77
+ }
53
78
  }
54
79
  };
55
80
  xhr.onerror = function (err) {
@@ -68,7 +93,7 @@ function downloadFile(fileId, fileName, options) {
68
93
  * @returns
69
94
  */
70
95
  function batchDownloadFiles(fileList, options) {
71
- var API_BASEURL = options.API_BASEURL, authToken = options.authToken, zipName = options.zipName, _a = options.waterMark, waterMark = _a === void 0 ? true : _a;
96
+ var API_BASEURL = options.API_BASEURL, authToken = options.authToken, zipName = options.zipName, _a = options.waterMark, waterMark = _a === void 0 ? true : _a, _b = options.parseErrorBlob, parseErrorBlob = _b === void 0 ? false : _b;
72
97
  return new Promise(function (resolve, reject) {
73
98
  var _a, _b, _c, _d, _e, _f;
74
99
  var xhr = new XMLHttpRequest();
@@ -91,7 +116,32 @@ function batchDownloadFiles(fileList, options) {
91
116
  resolve({ msg: "文件下载成功!" });
92
117
  }
93
118
  else {
94
- reject(xhr.response);
119
+ if (!parseErrorBlob) {
120
+ reject(xhr.response);
121
+ return;
122
+ }
123
+ try {
124
+ if (Object.prototype.toString.call(xhr.response) === "[object Blob]") {
125
+ var blob = xhr.response;
126
+ blob
127
+ .text()
128
+ .then(function (text) {
129
+ var json = JSON.parse(text);
130
+ reject(json);
131
+ })
132
+ .catch(function (err) {
133
+ reject({
134
+ msg: (err === null || err === void 0 ? void 0 : err.message) || (err === null || err === void 0 ? void 0 : err.msg) || "批量下载失败!",
135
+ code: xhr.status,
136
+ });
137
+ });
138
+ }
139
+ }
140
+ catch (err) {
141
+ reject({
142
+ msg: "批量下载失败!",
143
+ });
144
+ }
95
145
  }
96
146
  };
97
147
  xhr.onerror = function (err) {
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ export { addThousedSeparator, appendQueryParamsToUrl, copyToClipboard, dangerous
9
9
  export { divide, exactRound, formatUnit, minus, plus, times } from './es/math.js';
10
10
  export { validatePassword } from './es/passwordValidate.js';
11
11
  export { emailValidate, idCardValidate, isChineseValidate, morePhoneValidate, phoneValidate, strLenValidate } from './es/validate.js';
12
- export { batchDownloadFiles, createDeleteFileLink, createDownloadLink, createOriginalLink, createThumbnailLink, createUploadFileLink, downloadFile, exportBolb, previewFile } from './es/file.js';
12
+ export { batchDownloadFiles, createDeleteFileLink, createDownloadLink, createOriginalLink, createThumbnailLink, createUploadFileLink, downloadFile, encodeFileId, exportBolb, previewFile } from './es/file.js';
13
13
  export { calculateAge, parseTime } from './es/parseTime.js';
14
14
  export { BASIC_KEY, CLIENT_TYPE, EMITTER_CCP_KEY, EMITTER_PCC_KEY, EMITTER_TYPE, TOKEN_KEY } from './es/constants.js';
15
15
  export { convert, html, match, pinyin } from 'pinyin-pro';
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ export { addThousedSeparator, appendQueryParamsToUrl, copyToClipboard, dangerous
9
9
  export { divide, exactRound, formatUnit, minus, plus, times } from './es/math.js';
10
10
  export { validatePassword } from './es/passwordValidate.js';
11
11
  export { emailValidate, idCardValidate, isChineseValidate, morePhoneValidate, phoneValidate, strLenValidate } from './es/validate.js';
12
- export { batchDownloadFiles, createDeleteFileLink, createDownloadLink, createOriginalLink, createThumbnailLink, createUploadFileLink, downloadFile, exportBolb, previewFile } from './es/file.js';
12
+ export { batchDownloadFiles, createDeleteFileLink, createDownloadLink, createOriginalLink, createThumbnailLink, createUploadFileLink, downloadFile, encodeFileId, exportBolb, previewFile } from './es/file.js';
13
13
  export { calculateAge, parseTime } from './es/parseTime.js';
14
14
  export { BASIC_KEY, CLIENT_TYPE, EMITTER_CCP_KEY, EMITTER_PCC_KEY, EMITTER_TYPE, TOKEN_KEY } from './es/constants.js';
15
15
  export { convert, html, match, pinyin } from './es/node_modules/pinyin-pro/dist/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zmdms-utils",
3
- "version": "0.0.85",
3
+ "version": "0.0.87",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
package/src/file.ts CHANGED
@@ -35,7 +35,13 @@ export function downloadFile(
35
35
  fileName: string,
36
36
  options: IDownloadOptions
37
37
  ) {
38
- const { API_BASEURL, authToken, waterMark = true, open } = options;
38
+ const {
39
+ API_BASEURL,
40
+ authToken,
41
+ waterMark = true,
42
+ open,
43
+ parseErrorBlob = false,
44
+ } = options;
39
45
  if (isZmdmsFileService) {
40
46
  fileId = encodeFileId(fileId, 2);
41
47
  }
@@ -76,7 +82,33 @@ export function downloadFile(
76
82
 
77
83
  resolve({ msg: "文件下载成功!" });
78
84
  } else {
79
- reject(xhr.response);
85
+ if (!parseErrorBlob) {
86
+ reject(xhr.response);
87
+ return;
88
+ }
89
+ try {
90
+ if (
91
+ Object.prototype.toString.call(xhr.response) === "[object Blob]"
92
+ ) {
93
+ const blob = xhr.response;
94
+ blob
95
+ .text()
96
+ .then((text: any) => {
97
+ const json = JSON.parse(text);
98
+ reject(json);
99
+ })
100
+ .catch((err: any) => {
101
+ reject({
102
+ msg: err?.message || err?.msg || "下载失败!",
103
+ code: xhr.status,
104
+ });
105
+ });
106
+ }
107
+ } catch (err) {
108
+ reject({
109
+ msg: "下载失败!",
110
+ });
111
+ }
80
112
  }
81
113
  };
82
114
  xhr.onerror = function (err) {
@@ -103,7 +135,13 @@ export function batchDownloadFiles(
103
135
  }[],
104
136
  options: IBatchDownloadOptions
105
137
  ) {
106
- const { API_BASEURL, authToken, zipName, waterMark = true } = options;
138
+ const {
139
+ API_BASEURL,
140
+ authToken,
141
+ zipName,
142
+ waterMark = true,
143
+ parseErrorBlob = false,
144
+ } = options;
107
145
  return new Promise((resolve, reject) => {
108
146
  const xhr = new XMLHttpRequest();
109
147
  // 获取请求基础数据
@@ -133,7 +171,33 @@ export function batchDownloadFiles(
133
171
 
134
172
  resolve({ msg: "文件下载成功!" });
135
173
  } else {
136
- reject(xhr.response);
174
+ if (!parseErrorBlob) {
175
+ reject(xhr.response);
176
+ return;
177
+ }
178
+ try {
179
+ if (
180
+ Object.prototype.toString.call(xhr.response) === "[object Blob]"
181
+ ) {
182
+ const blob = xhr.response;
183
+ blob
184
+ .text()
185
+ .then((text: any) => {
186
+ const json = JSON.parse(text);
187
+ reject(json);
188
+ })
189
+ .catch((err: any) => {
190
+ reject({
191
+ msg: err?.message || err?.msg || "批量下载失败!",
192
+ code: xhr.status,
193
+ });
194
+ });
195
+ }
196
+ } catch (err) {
197
+ reject({
198
+ msg: "批量下载失败!",
199
+ });
200
+ }
137
201
  }
138
202
  };
139
203
  xhr.onerror = function (err) {
@@ -438,11 +502,15 @@ interface IDownloadOptions extends IOptions {
438
502
  waterMark?: boolean | string;
439
503
  /** 是否开发不需要登录信息 */
440
504
  open?: boolean;
505
+ /** 是否解析异常blob结果 */
506
+ parseErrorBlob?: boolean;
441
507
  }
442
508
  interface IBatchDownloadOptions extends IOptions {
443
509
  zipName: string;
444
510
  /** 是否添加水印 */
445
511
  waterMark?: boolean | string;
512
+ /** 是否解析异常blob结果 */
513
+ parseErrorBlob?: boolean;
446
514
  }
447
515
  interface IDownloadLinkOptions extends Partial<IOptions> {
448
516
  /** 不需要登录信息的附件下载链接 */
package/src/index.ts CHANGED
@@ -42,6 +42,7 @@ export {
42
42
  createThumbnailLink,
43
43
  createUploadFileLink,
44
44
  createDeleteFileLink,
45
+ encodeFileId,
45
46
  } from "./file";
46
47
  /**
47
48
  * 时间处理函数
@@ -1,18 +1,18 @@
1
- import i18next from "i18next";
2
- import { initReactI18next } from "react-i18next";
3
-
4
- type InitOptions = Parameters<typeof i18next.init>;
5
-
6
- /**
7
- * 初始化逻辑
8
- * - 本函数主要用于初始化 i18next 实例,同时使用 react-i18next 插件进行 react 组件的支持
9
- * - 本函数的调用时机,一般是在项目的入口文件中进行调用,如 src/main.tsx 中
10
- * @param options 参数 同i18next.init 第一个参数
11
- * @param callback 参数 同i18next.init 第二个参数
12
- * @returns
13
- */
14
- function initLocale(options: InitOptions[0], callback?: InitOptions[1]) {
15
- return i18next.use(initReactI18next).init(options, callback);
16
- }
17
-
18
- export { initLocale, i18next as i18n };
1
+ import i18next from "i18next";
2
+ import { initReactI18next } from "react-i18next";
3
+
4
+ type InitOptions = Parameters<typeof i18next.init>;
5
+
6
+ /**
7
+ * 初始化逻辑
8
+ * - 本函数主要用于初始化 i18next 实例,同时使用 react-i18next 插件进行 react 组件的支持
9
+ * - 本函数的调用时机,一般是在项目的入口文件中进行调用,如 src/main.tsx 中
10
+ * @param options 参数 同i18next.init 第一个参数
11
+ * @param callback 参数 同i18next.init 第二个参数
12
+ * @returns
13
+ */
14
+ function initLocale(options: InitOptions[0], callback?: InitOptions[1]) {
15
+ return i18next.use(initReactI18next).init(options, callback);
16
+ }
17
+
18
+ export { initLocale, i18next as i18n };
@@ -1,8 +1,8 @@
1
- // i18n实例 及 初始化方法
2
- export { i18n, initLocale } from "./i18n";
3
-
4
- // 代理的 useTranslation 函数
5
- export { useTranslation, Trans } from "./use-translation";
6
-
7
- // 导出 t 函数(应对在非 react 组件环境下进行使用的场景)
8
- export { safeT } from "./t-in-non-react";
1
+ // i18n实例 及 初始化方法
2
+ export { i18n, initLocale } from "./i18n";
3
+
4
+ // 代理的 useTranslation 函数
5
+ export { useTranslation, Trans } from "./use-translation";
6
+
7
+ // 导出 t 函数(应对在非 react 组件环境下进行使用的场景)
8
+ export { safeT } from "./t-in-non-react";
@@ -1,65 +1,65 @@
1
- /**
2
- * t 函数封装:
3
- * - 本文件的几个 t 函数,主要用于弥补一些在 React 组件之外使用的场景
4
- * - 常规情况下,在 react 组件中,更加推荐的是使用 react-i18next 包中的 t 函数,即 const { t } = useTranslate(); 形式
5
- */
6
- import { i18n } from "./i18n";
7
- import type { TOpionsEx } from "./t-options";
8
- import { getTFuncArgs } from "./t-options";
9
-
10
- /** 包裹一层 try-catch 的 t 函数 */
11
- const tryT = (
12
- key: string,
13
- defaultValueOrOptions: string | TOpionsEx
14
- ): string => {
15
- const { defaultValue, options } = getTFuncArgs(defaultValueOrOptions);
16
- if (!key) {
17
- // 情况1:键名为空,返回默认值或键名
18
- console.error(
19
- `tryT: 请不要传入空 key 值进行 i18n.t 函数执行,这将会导致直接返回空字符串!`
20
- );
21
- return defaultValue || key;
22
- }
23
- if (!i18n.exists(key)) {
24
- // 情况2:键名不存在,返回默认值或键名
25
- console.error(
26
- `tryT: i18n-key '${key}' 不存在,请检查对应的 @/locales/resources/locales/xx.json 中是否存在对应值`
27
- );
28
- return defaultValue || key;
29
- }
30
- try {
31
- // 情况3:尝试执行 i18n.t 函数
32
- return i18n.t(key, options);
33
- } catch (err) {
34
- // 情况4:执行 i18n.t 函数异常,返回默认值或键名
35
- console.error(`tryT: i18n.t key=${key} 函数执行异常:err=`, err);
36
- return defaultValue || key;
37
- }
38
- };
39
-
40
- /**
41
- * 同步版本的 i18n.t 函数(应对在 react 组件外使用的翻译函数)
42
- * - 如果 i18n 未初始化,则返回默认值或键名
43
- * - 如果 i18n 初始化后,键名不存在,则返回默认值或键名
44
- * - 其他正常情况(已经初始化+键名存在),则返回翻译值
45
- * @description 本函数为在非 react 组件中使用的翻译函数;(在react中请求使用 useTranslate() 返回的 t 函数)
46
- * @param {string} key
47
- * @param {TOpionsEx|string} defaultValue 必填值
48
- * @returns {string}
49
- * @example
50
- * const txt = t('someLocaleKey', '兜底默认值');
51
- */
52
- export function safeT(
53
- key: string,
54
- defaultValueOrOptions: string | TOpionsEx
55
- ): string {
56
- if (i18n.isInitialized) {
57
- return tryT(key, defaultValueOrOptions);
58
- }
59
- // 异常情况:没有初始化完成时,返回默认值
60
- const { defaultValue } = getTFuncArgs(defaultValueOrOptions);
61
- console.warn(
62
- `safeT: i18n is not initialized. Returning defaultValue(${defaultValue}) or origin key (${key}).`
63
- );
64
- return defaultValue || key;
65
- }
1
+ /**
2
+ * t 函数封装:
3
+ * - 本文件的几个 t 函数,主要用于弥补一些在 React 组件之外使用的场景
4
+ * - 常规情况下,在 react 组件中,更加推荐的是使用 react-i18next 包中的 t 函数,即 const { t } = useTranslate(); 形式
5
+ */
6
+ import { i18n } from "./i18n";
7
+ import type { TOpionsEx } from "./t-options";
8
+ import { getTFuncArgs } from "./t-options";
9
+
10
+ /** 包裹一层 try-catch 的 t 函数 */
11
+ const tryT = (
12
+ key: string,
13
+ defaultValueOrOptions: string | TOpionsEx
14
+ ): string => {
15
+ const { defaultValue, options } = getTFuncArgs(defaultValueOrOptions);
16
+ if (!key) {
17
+ // 情况1:键名为空,返回默认值或键名
18
+ console.error(
19
+ `tryT: 请不要传入空 key 值进行 i18n.t 函数执行,这将会导致直接返回空字符串!`
20
+ );
21
+ return defaultValue || key;
22
+ }
23
+ if (!i18n.exists(key)) {
24
+ // 情况2:键名不存在,返回默认值或键名
25
+ console.error(
26
+ `tryT: i18n-key '${key}' 不存在,请检查对应的 @/locales/resources/locales/xx.json 中是否存在对应值`
27
+ );
28
+ return defaultValue || key;
29
+ }
30
+ try {
31
+ // 情况3:尝试执行 i18n.t 函数
32
+ return i18n.t(key, options);
33
+ } catch (err) {
34
+ // 情况4:执行 i18n.t 函数异常,返回默认值或键名
35
+ console.error(`tryT: i18n.t key=${key} 函数执行异常:err=`, err);
36
+ return defaultValue || key;
37
+ }
38
+ };
39
+
40
+ /**
41
+ * 同步版本的 i18n.t 函数(应对在 react 组件外使用的翻译函数)
42
+ * - 如果 i18n 未初始化,则返回默认值或键名
43
+ * - 如果 i18n 初始化后,键名不存在,则返回默认值或键名
44
+ * - 其他正常情况(已经初始化+键名存在),则返回翻译值
45
+ * @description 本函数为在非 react 组件中使用的翻译函数;(在react中请求使用 useTranslate() 返回的 t 函数)
46
+ * @param {string} key
47
+ * @param {TOpionsEx|string} defaultValue 必填值
48
+ * @returns {string}
49
+ * @example
50
+ * const txt = t('someLocaleKey', '兜底默认值');
51
+ */
52
+ export function safeT(
53
+ key: string,
54
+ defaultValueOrOptions: string | TOpionsEx
55
+ ): string {
56
+ if (i18n.isInitialized) {
57
+ return tryT(key, defaultValueOrOptions);
58
+ }
59
+ // 异常情况:没有初始化完成时,返回默认值
60
+ const { defaultValue } = getTFuncArgs(defaultValueOrOptions);
61
+ console.warn(
62
+ `safeT: i18n is not initialized. Returning defaultValue(${defaultValue}) or origin key (${key}).`
63
+ );
64
+ return defaultValue || key;
65
+ }
@@ -1,24 +1,24 @@
1
- "use strict";
2
- import type { TOptions } from "i18next";
3
-
4
- export interface TOpionsEx extends TOptions {
5
- defaultValue: string; // 必须填值
6
- }
7
-
8
- /**
9
- * 获取 t 函数的参数
10
- * @param {string | TOpionsEx} defaultValueOrOptions 默认值或者选项
11
- * @returns { {defaultValue: string, options: TOpionsEx} } 默认值和选项
12
- */
13
- export function getTFuncArgs(defaultValueOrOptions: string | TOpionsEx) {
14
- let options: TOpionsEx | null = null;
15
- let defaultValue = "";
16
- if (typeof defaultValueOrOptions === "string") {
17
- defaultValue = defaultValueOrOptions;
18
- options = { defaultValue };
19
- } else {
20
- options = defaultValueOrOptions;
21
- defaultValue = options.defaultValue;
22
- }
23
- return { defaultValue, options };
24
- }
1
+ "use strict";
2
+ import type { TOptions } from "i18next";
3
+
4
+ export interface TOpionsEx extends TOptions {
5
+ defaultValue: string; // 必须填值
6
+ }
7
+
8
+ /**
9
+ * 获取 t 函数的参数
10
+ * @param {string | TOpionsEx} defaultValueOrOptions 默认值或者选项
11
+ * @returns { {defaultValue: string, options: TOpionsEx} } 默认值和选项
12
+ */
13
+ export function getTFuncArgs(defaultValueOrOptions: string | TOpionsEx) {
14
+ let options: TOpionsEx | null = null;
15
+ let defaultValue = "";
16
+ if (typeof defaultValueOrOptions === "string") {
17
+ defaultValue = defaultValueOrOptions;
18
+ options = { defaultValue };
19
+ } else {
20
+ options = defaultValueOrOptions;
21
+ defaultValue = options.defaultValue;
22
+ }
23
+ return { defaultValue, options };
24
+ }
@@ -1,76 +1,76 @@
1
- import { useTranslation, Trans } from "react-i18next";
2
- import type { TOpionsEx } from "./t-options";
3
- import { getTFuncArgs } from "./t-options";
4
-
5
- type Prams = Parameters<typeof useTranslation>;
6
- type NS = Prams[0];
7
- type Options = Prams[1];
8
-
9
- type EnhanceTFunc = (
10
- key: string,
11
- defaultValueOrOptions: string | TOpionsEx
12
- ) => string;
13
-
14
- /**
15
- * 这里只是简单代理一下useTranslation,方便后续扩展或添加其他逻辑
16
- * @param ns 命名空间 大多数情况下都不需要传入这个参数,除非你用到了命名空间。
17
- * @param options 其他参数 大多数情况下,都不需要关注这个参数。
18
- * options.keyPrefix 为所有翻译键添加前缀
19
- * // JSON 文件:{ "greeting": { "welcome": "Welcome" } }
20
- * const { t } = useTranslation('common', { keyPrefix: 'greeting' });
21
- * // 使用时省略前缀
22
- * t('welcome'); // 等价于 t('greeting:welcome')
23
- * @returns { t, i18n, ready }
24
- * t: 翻译方法
25
- * i18n: i18next实例 访问 i18next 的完整 API(如切换语言、加载命名空间)
26
- * i18n.changeLanguage('zh-CN'); 使用它切换语言,可以触发组件渲染。但是当前项目中是使用全局刷新的模式,来更新语言的。
27
- * ready: 是否加载完成
28
- */
29
- function useZtTranslation(ns?: NS, options?: Options) {
30
- const { t: _tOld, i18n, ready } = useTranslation(ns, options);
31
-
32
- // 扩展t方法,用于处理嵌套的翻译键
33
- const tEnhance: EnhanceTFunc = (key, defaultValueOrOptions) => {
34
- const { defaultValue, options } = getTFuncArgs(defaultValueOrOptions);
35
-
36
- if (!key) {
37
- // 情况1:键名为空,返回默认值或键名
38
- console.error(
39
- `tEnhance: 请不要传入空 key 值进行 t 函数执行,这将会导致直接返回空字符串!`
40
- );
41
- return defaultValue || key;
42
- }
43
- if (!i18n.exists(key)) {
44
- // 情况2:键名不存在,返回默认值或键名
45
- console.error(
46
- `tEnhance: i18n-key '${key}' 不存在,请检查对应的 @/locales/resources/locales/xx.json 中是否存在对应值`
47
- );
48
- return defaultValue || key;
49
- }
50
- try {
51
- return _tOld(key, options);
52
- } catch (error) {
53
- console.warn(`tEnhance: t 函数执行异常,请检查! key=${key}, err=`, error);
54
- return defaultValue || key || "unknown";
55
- }
56
- };
57
-
58
- return {
59
- /**
60
- * t函数的使用方式:基本上使用1、2两种方式就可以了。
61
- * 1、t('key') // 基础用法
62
- * 2、t('greeting', { name: 'John' }); // 对应 JSON: "greeting": "Hello {{name}}"
63
- * 3、t('auth:login'); // 显式指定命名空间
64
- *
65
- * 关于t函数的第二个参数的说明。
66
- * 为了防止一些异常情况,翻译失败。可以传入一个默认值。这个默认值就是原本的中文就行。
67
- * 1、t('key', '默认值');
68
- * 2、t('key', { defaultValue: '默认值', ...otherOptions });
69
- */
70
- t: tEnhance,
71
- i18n,
72
- ready,
73
- };
74
- }
75
-
76
- export { useZtTranslation as useTranslation, Trans };
1
+ import { useTranslation, Trans } from "react-i18next";
2
+ import type { TOpionsEx } from "./t-options";
3
+ import { getTFuncArgs } from "./t-options";
4
+
5
+ type Prams = Parameters<typeof useTranslation>;
6
+ type NS = Prams[0];
7
+ type Options = Prams[1];
8
+
9
+ type EnhanceTFunc = (
10
+ key: string,
11
+ defaultValueOrOptions: string | TOpionsEx
12
+ ) => string;
13
+
14
+ /**
15
+ * 这里只是简单代理一下useTranslation,方便后续扩展或添加其他逻辑
16
+ * @param ns 命名空间 大多数情况下都不需要传入这个参数,除非你用到了命名空间。
17
+ * @param options 其他参数 大多数情况下,都不需要关注这个参数。
18
+ * options.keyPrefix 为所有翻译键添加前缀
19
+ * // JSON 文件:{ "greeting": { "welcome": "Welcome" } }
20
+ * const { t } = useTranslation('common', { keyPrefix: 'greeting' });
21
+ * // 使用时省略前缀
22
+ * t('welcome'); // 等价于 t('greeting:welcome')
23
+ * @returns { t, i18n, ready }
24
+ * t: 翻译方法
25
+ * i18n: i18next实例 访问 i18next 的完整 API(如切换语言、加载命名空间)
26
+ * i18n.changeLanguage('zh-CN'); 使用它切换语言,可以触发组件渲染。但是当前项目中是使用全局刷新的模式,来更新语言的。
27
+ * ready: 是否加载完成
28
+ */
29
+ function useZtTranslation(ns?: NS, options?: Options) {
30
+ const { t: _tOld, i18n, ready } = useTranslation(ns, options);
31
+
32
+ // 扩展t方法,用于处理嵌套的翻译键
33
+ const tEnhance: EnhanceTFunc = (key, defaultValueOrOptions) => {
34
+ const { defaultValue, options } = getTFuncArgs(defaultValueOrOptions);
35
+
36
+ if (!key) {
37
+ // 情况1:键名为空,返回默认值或键名
38
+ console.error(
39
+ `tEnhance: 请不要传入空 key 值进行 t 函数执行,这将会导致直接返回空字符串!`
40
+ );
41
+ return defaultValue || key;
42
+ }
43
+ if (!i18n.exists(key)) {
44
+ // 情况2:键名不存在,返回默认值或键名
45
+ console.error(
46
+ `tEnhance: i18n-key '${key}' 不存在,请检查对应的 @/locales/resources/locales/xx.json 中是否存在对应值`
47
+ );
48
+ return defaultValue || key;
49
+ }
50
+ try {
51
+ return _tOld(key, options);
52
+ } catch (error) {
53
+ console.warn(`tEnhance: t 函数执行异常,请检查! key=${key}, err=`, error);
54
+ return defaultValue || key || "unknown";
55
+ }
56
+ };
57
+
58
+ return {
59
+ /**
60
+ * t函数的使用方式:基本上使用1、2两种方式就可以了。
61
+ * 1、t('key') // 基础用法
62
+ * 2、t('greeting', { name: 'John' }); // 对应 JSON: "greeting": "Hello {{name}}"
63
+ * 3、t('auth:login'); // 显式指定命名空间
64
+ *
65
+ * 关于t函数的第二个参数的说明。
66
+ * 为了防止一些异常情况,翻译失败。可以传入一个默认值。这个默认值就是原本的中文就行。
67
+ * 1、t('key', '默认值');
68
+ * 2、t('key', { defaultValue: '默认值', ...otherOptions });
69
+ */
70
+ t: tEnhance,
71
+ i18n,
72
+ ready,
73
+ };
74
+ }
75
+
76
+ export { useZtTranslation as useTranslation, Trans };