@zero-library/common 1.0.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.
@@ -0,0 +1,1402 @@
1
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
2
+ import { FileUnknownOutlined, FileZipOutlined, FileGifOutlined, FileImageOutlined, FileJpgOutlined, NotificationOutlined, VideoCameraOutlined, FilePptOutlined, FileExcelOutlined, FileWordOutlined, FilePdfOutlined, FileTextOutlined } from '@ant-design/icons';
3
+ import { forwardRef, useState, useMemo, useEffect, lazy, Suspense, createContext, useRef, useCallback, useContext } from 'react';
4
+ import { Spin, notification, Modal, Result, Splitter, Empty, Image, Flex, Drawer, Avatar, Alert, Form, Input, Button } from 'antd';
5
+ import parse from 'html-react-parser';
6
+ import { jsonrepair } from 'jsonrepair';
7
+ import markdownit from 'markdown-it';
8
+ import container from 'markdown-it-container';
9
+ import { Worker, Viewer, PasswordStatus } from '@react-pdf-viewer/core';
10
+ import { pageNavigationPlugin } from '@react-pdf-viewer/page-navigation';
11
+ import { thumbnailPlugin } from '@react-pdf-viewer/thumbnail';
12
+ import { zoomPlugin } from '@react-pdf-viewer/zoom';
13
+ import '@react-pdf-viewer/core/lib/styles/index.css';
14
+ import zh_CN from '@react-pdf-viewer/locales/lib/zh_CN.json';
15
+ import '@react-pdf-viewer/page-navigation/lib/styles/index.css';
16
+ import dayjs from 'dayjs';
17
+ import relativeTime from 'dayjs/plugin/relativeTime';
18
+ import AES from 'crypto-js/aes';
19
+ import encUtf8 from 'crypto-js/enc-utf8';
20
+ import Decimal from 'decimal.js';
21
+ import axios from 'axios';
22
+ import { message } from 'antd/lib';
23
+ import '@react-pdf-viewer/thumbnail/lib/styles/index.css';
24
+ import '@react-pdf-viewer/zoom/lib/styles/index.css';
25
+ import classNames from 'classnames';
26
+
27
+ // src/components/File/styles.module.less
28
+ var styles_module_default = {
29
+ nsPreviewImage: "styles_module_nsPreviewImage",
30
+ nsPreviewPdf: "styles_module_nsPreviewPdf",
31
+ pdfToolbar: "styles_module_pdfToolbar",
32
+ nsPreviewVideo: "styles_module_nsPreviewVideo",
33
+ nsPreviewAudio: "styles_module_nsPreviewAudio"
34
+ };
35
+ var AudioPlayer_default = ({ fileUrl }) => {
36
+ return /* @__PURE__ */ jsxs("audio", { controls: true, className: styles_module_default.nsPreviewAudio, children: [
37
+ /* @__PURE__ */ jsx("source", { src: fileUrl, type: "audio/mpeg" }),
38
+ "\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 audio \u6807\u7B7E\u3002"
39
+ ] });
40
+ };
41
+
42
+ // src/utils/theme.ts
43
+ var getPrimaryColor = () => {
44
+ const searchParams = new URLSearchParams(location.search);
45
+ const mainSource = searchParams.get("mainSource") || "cube-uc";
46
+ if (mainSource === "cube-uc") {
47
+ return "#34AFBE";
48
+ } else if (mainSource === "uc") {
49
+ return "#FA541C";
50
+ }
51
+ };
52
+ var LgPrimaryColor = getPrimaryColor();
53
+ var themeConfig = {
54
+ token: { colorPrimary: LgPrimaryColor, colorLink: LgPrimaryColor },
55
+ cssVar: true
56
+ };
57
+ var FileIcon_default = ({ suffix, fontSize = 22 }) => {
58
+ const styles = { fontSize, color: LgPrimaryColor };
59
+ const Icon = useMemo(() => {
60
+ switch (suffix?.toUpperCase()) {
61
+ case "TXT":
62
+ return /* @__PURE__ */ jsx(FileTextOutlined, {});
63
+ case "PDF":
64
+ return /* @__PURE__ */ jsx(FilePdfOutlined, {});
65
+ case "DOC":
66
+ case "DOCX":
67
+ return /* @__PURE__ */ jsx(FileWordOutlined, {});
68
+ case "XLS":
69
+ case "XLSX":
70
+ return /* @__PURE__ */ jsx(FileExcelOutlined, {});
71
+ case "PPT":
72
+ return /* @__PURE__ */ jsx(FilePptOutlined, {});
73
+ case "MP4":
74
+ case "MOV":
75
+ case "AVI":
76
+ case "FLV":
77
+ return /* @__PURE__ */ jsx(VideoCameraOutlined, {});
78
+ case "MP3":
79
+ return /* @__PURE__ */ jsx(NotificationOutlined, {});
80
+ case "JPG":
81
+ case "JPEG":
82
+ return /* @__PURE__ */ jsx(FileJpgOutlined, {});
83
+ case "PNG":
84
+ return /* @__PURE__ */ jsx(FileImageOutlined, {});
85
+ case "GIF":
86
+ return /* @__PURE__ */ jsx(FileGifOutlined, {});
87
+ case "ZIP":
88
+ case "RAR":
89
+ case "7Z":
90
+ return /* @__PURE__ */ jsx(FileZipOutlined, {});
91
+ case "CATALOG":
92
+ return /* @__PURE__ */ jsx("i", { style: styles, className: "iconfont icon-wenjianjia" });
93
+ // 文件夹
94
+ default:
95
+ return /* @__PURE__ */ jsx(FileUnknownOutlined, {});
96
+ }
97
+ }, [suffix]);
98
+ return /* @__PURE__ */ jsx("span", { style: styles, children: Icon });
99
+ };
100
+ var VideoPlayer_default = ({ fileUrl }) => {
101
+ return /* @__PURE__ */ jsxs("video", { controls: true, className: styles_module_default.nsPreviewVideo, children: [
102
+ /* @__PURE__ */ jsx("source", { src: fileUrl, type: "video/mp4" }),
103
+ "\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 video \u6807\u7B7E\u3002"
104
+ ] });
105
+ };
106
+ var baseComponentMap = {
107
+ // renderMarkdown: () => import('@/components/RenderMarkdown')
108
+ };
109
+ var LazyComponent_default = ({ type, customComponents, ...rest }) => {
110
+ const componentMap = useMemo(() => {
111
+ return { ...baseComponentMap, ...customComponents };
112
+ }, [customComponents]);
113
+ const LazyComponent = useMemo(() => {
114
+ const loader = componentMap[type];
115
+ return loader ? lazy(loader) : null;
116
+ }, [type, componentMap]);
117
+ if (!LazyComponent) return /* @__PURE__ */ jsxs("div", { children: [
118
+ "\u672A\u77E5\u7C7B\u578B\uFF1A",
119
+ type
120
+ ] });
121
+ return /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx("div", { children: "\u52A0\u8F7D\u4E2D..." }), children: /* @__PURE__ */ jsx(LazyComponent, { ...rest }) });
122
+ };
123
+ var md = markdownit({ html: true, breaks: true });
124
+ md.renderer.rules.link_open = function(tokens, idx, options, env, self) {
125
+ const token = tokens[idx];
126
+ token.attrPush(["target", "_blank"]);
127
+ return self.renderToken(tokens, idx, options);
128
+ };
129
+ var replaceSpecialCharacter = (str) => {
130
+ return str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
131
+ };
132
+ function parseParams(info) {
133
+ const params = {};
134
+ const regex = /(\w+)\s*=\s*(?:(['"])(.*?)\2|(\S+))/g;
135
+ let match;
136
+ while ((match = regex.exec(info)) !== null) {
137
+ const key = match[1];
138
+ const value = match[3] ?? match[4] ?? "";
139
+ if (key === "data") {
140
+ let obj = {};
141
+ try {
142
+ obj = JSON.parse(value);
143
+ } catch {
144
+ try {
145
+ obj = JSON.parse(jsonrepair(value));
146
+ } catch {
147
+ obj = {};
148
+ }
149
+ }
150
+ params[key] = replaceSpecialCharacter(JSON.stringify(obj));
151
+ } else {
152
+ params[key] = value;
153
+ }
154
+ }
155
+ return params;
156
+ }
157
+ md.use(container, "alert", {
158
+ validate: (params) => /^alert/.test(params.trim()),
159
+ render: function(tokens, idx) {
160
+ const token = tokens[idx];
161
+ if (token.nesting === 1) {
162
+ const info = token.info.trim();
163
+ const params = parseParams(info);
164
+ return `<lazy-component ${Object.entries(params).map(([key, value]) => `${key}=${value}`).join(" ")}>`;
165
+ } else {
166
+ return "</lazy-component>";
167
+ }
168
+ }
169
+ });
170
+ function preprocess(content) {
171
+ return content.replace(
172
+ /:::alert([\s\S]*?):::/g,
173
+ // 匹配 :::alert ... :::
174
+ (match, params) => {
175
+ return `
176
+ :::alert ${params.trim()}
177
+ :::
178
+ `;
179
+ }
180
+ );
181
+ }
182
+ function highlightKeywords(html, keywords) {
183
+ const escaped = keywords.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
184
+ const regex = new RegExp(`(${escaped.join("|")})`, "gi");
185
+ return html.replace(regex, '<span class="cube-hl">$1</span>');
186
+ }
187
+ var RenderMarkdown_default = ({ content = "", searchValue, customComponents, onChange, onPartialChange }) => {
188
+ const reactContent = useMemo(() => {
189
+ if (!content) return null;
190
+ let fixedContent = content;
191
+ const openCount = (fixedContent.match(/:::alert\b/g) || []).length;
192
+ const closeCount = (fixedContent.match(/\s*:::\s*/gm) || []).length - openCount;
193
+ let incomplete = false;
194
+ if (openCount > closeCount) {
195
+ incomplete = true;
196
+ fixedContent += ":::";
197
+ }
198
+ fixedContent = preprocess(fixedContent);
199
+ let rawHtml = md.render(fixedContent);
200
+ rawHtml = searchValue ? highlightKeywords(rawHtml, [searchValue]) : rawHtml;
201
+ let lazyIndex = -1;
202
+ const allLazyMatches = [...rawHtml.matchAll(/<lazy-component/gi)];
203
+ const lastLazyIndex = allLazyMatches.length - 1;
204
+ return parse(rawHtml, {
205
+ replace: (domNode) => {
206
+ if (domNode.name === "lazy-component") {
207
+ lazyIndex++;
208
+ const el = domNode;
209
+ const type = el.attribs.type;
210
+ const data = JSON.parse(el.attribs.data || "{}");
211
+ const loading = incomplete && lazyIndex === lastLazyIndex;
212
+ return /* @__PURE__ */ jsx(
213
+ LazyComponent_default,
214
+ {
215
+ type,
216
+ data,
217
+ loading,
218
+ customComponents,
219
+ onChange,
220
+ onPartialChange
221
+ },
222
+ `${type}${lazyIndex}`
223
+ );
224
+ }
225
+ }
226
+ });
227
+ }, [content, searchValue]);
228
+ return /* @__PURE__ */ jsx("div", { className: "ns-markdown", children: reactContent });
229
+ };
230
+ var MarkdownPreview_default = ({ fileUrl, searchValue }) => {
231
+ const [content, setContent] = useState("");
232
+ const [error, setError] = useState("");
233
+ const fetchMarkdown = async () => {
234
+ const res = await fetch(fileUrl);
235
+ if (res.status !== 200) {
236
+ throw new Error(`\u8BF7\u6C42\u5931\u8D25\uFF0C\u72B6\u6001\u7801: ${res.status}`);
237
+ }
238
+ const markdownText = await res.text();
239
+ if (!markdownText) {
240
+ throw new Error("\u8FD4\u56DE\u5185\u5BB9\u4E3A\u7A7A");
241
+ }
242
+ setContent(markdownText);
243
+ };
244
+ const init = async () => {
245
+ setContent("");
246
+ setError("");
247
+ if (fileUrl) {
248
+ try {
249
+ await fetchMarkdown();
250
+ } catch (error2) {
251
+ setError("\u52A0\u8F7D\u6216\u89E3\u6790 Markdown \u5931\u8D25");
252
+ }
253
+ }
254
+ };
255
+ useEffect(() => {
256
+ init();
257
+ }, [fileUrl]);
258
+ return error ? /* @__PURE__ */ jsx(Result, { status: "error", title: error }) : /* @__PURE__ */ jsx("div", { className: "height-full", children: /* @__PURE__ */ jsx(RenderMarkdown_default, { content, searchValue }) });
259
+ };
260
+ function createValtioContext() {
261
+ const Context = createContext(null);
262
+ const ValtioProvider = ({ store, children }) => /* @__PURE__ */ jsx(Context.Provider, { value: store, children });
263
+ const useValtioStore = () => {
264
+ const store = useContext(Context);
265
+ if (!store) throw new Error("useStore must be used within Provider");
266
+ return store;
267
+ };
268
+ return {
269
+ ValtioProvider,
270
+ useValtioStore
271
+ // Context
272
+ };
273
+ }
274
+
275
+ // src/hooks/iframe/iframeRelay.ts
276
+ function emit(type, data, to = "top") {
277
+ const payload = { type, data, to };
278
+ try {
279
+ window.parent.postMessage(payload, "*");
280
+ } catch (err) {
281
+ console.warn("emit parent failed", err);
282
+ }
283
+ }
284
+ function emitToChild(iframeWindow, type, data, origin = "*") {
285
+ if (!iframeWindow) {
286
+ console.warn("emitToChild failed: iframeWindow is null");
287
+ return;
288
+ }
289
+ const payload = { type, data, to: "child" };
290
+ try {
291
+ iframeWindow.postMessage(payload, origin);
292
+ } catch (err) {
293
+ console.warn("emit to child failed", err);
294
+ }
295
+ }
296
+
297
+ // src/utils/is.ts
298
+ var toString = Object.prototype.toString;
299
+ function is(val, type) {
300
+ return toString.call(val) === `[object ${type}]`;
301
+ }
302
+ function isUnDef(val) {
303
+ return is(val, "Undefined");
304
+ }
305
+ function isDef(val) {
306
+ return !isUnDef(val);
307
+ }
308
+ function isObject(val) {
309
+ return is(val, "Object");
310
+ }
311
+ function isEmptyObj(val) {
312
+ if (isObject(val)) {
313
+ return Object.keys(val).length === 0;
314
+ }
315
+ return false;
316
+ }
317
+ function isDate(val) {
318
+ return is(val, "Date");
319
+ }
320
+ function isNull(val) {
321
+ return is(val, "Null");
322
+ }
323
+ function isNullOrUnDef(val) {
324
+ return isUnDef(val) || isNull(val);
325
+ }
326
+ function isNumber(val) {
327
+ return is(val, "Number");
328
+ }
329
+ function isNumberNoNaN(val) {
330
+ return is(val, "Number") && !isNaN(val);
331
+ }
332
+ function isString(val) {
333
+ return is(val, "String");
334
+ }
335
+ function isFunction(val) {
336
+ return is(val, "Function");
337
+ }
338
+ function isPromise(val) {
339
+ return is(val, "Promise") && isObject(val) && isFunction(val.then) && isFunction(val.catch);
340
+ }
341
+ function isBoolean(val) {
342
+ return is(val, "Boolean");
343
+ }
344
+ function isRegExp(val) {
345
+ return is(val, "RegExp");
346
+ }
347
+ function isArray(val) {
348
+ return Array.isArray(val);
349
+ }
350
+ function isEmpty(val) {
351
+ if (isArray(val) || isString(val)) {
352
+ return val.length === 0;
353
+ }
354
+ if (isNullOrUnDef(val)) {
355
+ return true;
356
+ }
357
+ if (val instanceof Map || val instanceof Set) {
358
+ return val.size === 0;
359
+ }
360
+ return isEmptyObj(val);
361
+ }
362
+ function isWindow(val) {
363
+ return typeof window !== "undefined" && is(val, "Window");
364
+ }
365
+ function isElement(val) {
366
+ return isObject(val) && !!val.tagName;
367
+ }
368
+ function isMap(val) {
369
+ return is(val, "Map");
370
+ }
371
+ var isServer = typeof window === "undefined";
372
+ var isClient = !isServer;
373
+ var isExternal = (path) => {
374
+ return /^(https?:|mailto:|tel:)/.test(path);
375
+ };
376
+ var isBlob = (val) => {
377
+ return is(val, "Blob");
378
+ };
379
+
380
+ // src/hooks/iframe/useIframeRelayBridge.ts
381
+ function useIframeRelayBridge(allowedOrigins = ["*"]) {
382
+ const handlers = useRef({});
383
+ useEffect(() => {
384
+ const onMessage = (evt) => {
385
+ const { data, source, origin } = evt;
386
+ if (!data || !isObject(data) || !data.type) return;
387
+ if (allowedOrigins[0] !== "*" && !allowedOrigins.includes(origin)) return;
388
+ const { type, data: params, to = "parent" } = data;
389
+ const isTop = window.parent === window;
390
+ if (to === "top" && !isTop) {
391
+ window.parent.postMessage(data, allowedOrigins[0] === "*" ? "*" : origin);
392
+ return;
393
+ }
394
+ const fns = handlers.current[type] || [];
395
+ fns.forEach((fn) => fn(params, source, origin));
396
+ };
397
+ window.addEventListener("message", onMessage);
398
+ return () => window.removeEventListener("message", onMessage);
399
+ }, [allowedOrigins]);
400
+ function on(type, handler) {
401
+ handlers.current[type] = handlers.current[type] || [];
402
+ handlers.current[type].push(handler);
403
+ }
404
+ function off(type, handler) {
405
+ handlers.current[type] = (handlers.current[type] || []).filter((fn) => fn !== handler);
406
+ }
407
+ return { on, off };
408
+ }
409
+ function useDebounce(func, wait = 400) {
410
+ const { current } = useRef({ func, timeOut: null });
411
+ useEffect(() => {
412
+ current.func = func;
413
+ }, [func]);
414
+ let args;
415
+ function debounce(..._args) {
416
+ args = _args;
417
+ if (current.timeOut) {
418
+ clearTimeout(current.timeOut);
419
+ current.timeOut = null;
420
+ }
421
+ return new Promise((resolve, reject) => {
422
+ current.timeOut = setTimeout(async () => {
423
+ try {
424
+ const result = await current.func.apply(null, args);
425
+ resolve(result);
426
+ } catch (e) {
427
+ reject(e);
428
+ }
429
+ }, wait);
430
+ });
431
+ }
432
+ function cancel() {
433
+ if (!current.timeOut) return;
434
+ clearTimeout(current.timeOut);
435
+ current.timeOut = null;
436
+ }
437
+ function flush() {
438
+ cancel();
439
+ return current.func.apply(null, args);
440
+ }
441
+ debounce.flush = flush;
442
+ debounce.cancel = cancel;
443
+ return useCallback(debounce, []);
444
+ }
445
+
446
+ // src/utils/common.ts
447
+ var deepCopy = (obj, isJson = true) => {
448
+ if (!isArray(obj) && !isObject(obj)) return obj;
449
+ if (isJson) return JSON.parse(JSON.stringify(obj));
450
+ const result = isArray(obj) ? [] : {};
451
+ for (const key in obj) {
452
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
453
+ result[key] = deepCopy(obj[key], isJson);
454
+ }
455
+ }
456
+ return result;
457
+ };
458
+ function deepEqual(a, b) {
459
+ if (Object.is(a, b)) return true;
460
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
461
+ if (a instanceof RegExp && b instanceof RegExp) return a.toString() === b.toString();
462
+ if (a instanceof Map && b instanceof Map) {
463
+ if (a.size !== b.size) return false;
464
+ for (const [key, val] of a.entries()) {
465
+ if (!b.has(key) || !deepEqual(val, b.get(key))) return false;
466
+ }
467
+ return true;
468
+ }
469
+ if (a instanceof Set && b instanceof Set) {
470
+ if (a.size !== b.size) return false;
471
+ for (const val of a.values()) {
472
+ if (!b.has(val)) return false;
473
+ }
474
+ return true;
475
+ }
476
+ if (Array.isArray(a) && Array.isArray(b)) {
477
+ if (a.length !== b.length) return false;
478
+ return a.every((item, i) => deepEqual(item, b[i]));
479
+ }
480
+ if (typeof a === "function" && typeof b === "function") return a.toString() === b.toString();
481
+ if (isObject(a) && isObject(b)) {
482
+ const keysA = Object.keys(a);
483
+ const keysB = Object.keys(b);
484
+ if (keysA.length !== keysB.length) return false;
485
+ for (const key of keysA) {
486
+ if (!deepEqual(a[key], b[key])) return false;
487
+ }
488
+ return true;
489
+ }
490
+ return false;
491
+ }
492
+ var deepMerge = (base, override) => {
493
+ const result = { ...base };
494
+ Object.keys(override || {}).forEach((key) => {
495
+ const baseValue = base[key];
496
+ const overrideValue = override[key];
497
+ if (typeof baseValue === "object" && baseValue !== null && !isArray(baseValue) && typeof overrideValue === "object" && overrideValue !== null && !isArray(overrideValue)) {
498
+ result[key] = deepMerge(baseValue, overrideValue);
499
+ } else if (overrideValue !== void 0) {
500
+ result[key] = overrideValue;
501
+ }
502
+ });
503
+ return result;
504
+ };
505
+ var objToOptions = (obj) => {
506
+ return Object.keys(obj).map((key) => ({
507
+ label: obj[key],
508
+ value: Number(key)
509
+ }));
510
+ };
511
+ var arrToObj = (arr = [], key) => {
512
+ const obj = {};
513
+ arr?.forEach((item) => {
514
+ obj[item[key]] = item;
515
+ });
516
+ return obj;
517
+ };
518
+ var nsSetInterval = (fn, t) => {
519
+ let timer = null;
520
+ let isCancelled = false;
521
+ const interval = () => {
522
+ timer = setTimeout(async () => {
523
+ if (isCancelled) {
524
+ return;
525
+ }
526
+ await fn();
527
+ if (!isCancelled) {
528
+ interval();
529
+ }
530
+ }, t);
531
+ };
532
+ interval();
533
+ return {
534
+ isRun: () => !!timer,
535
+ cancel: () => {
536
+ isCancelled = true;
537
+ if (timer) {
538
+ clearTimeout(timer);
539
+ timer = null;
540
+ }
541
+ }
542
+ };
543
+ };
544
+ var genNonDuplicateID = () => {
545
+ let idStr = Date.now().toString(36);
546
+ idStr += Math.random().toString(36).substr(2);
547
+ return idStr;
548
+ };
549
+ var copyText = (text) => {
550
+ if (navigator.clipboard && window.isSecureContext) {
551
+ return navigator.clipboard.writeText(text);
552
+ } else {
553
+ const textArea = document.createElement("textarea");
554
+ textArea.value = text;
555
+ textArea.style.position = "absolute";
556
+ textArea.style.opacity = "0";
557
+ textArea.style.left = "-999999px";
558
+ textArea.style.top = "-999999px";
559
+ document.body.appendChild(textArea);
560
+ textArea.focus();
561
+ textArea.select();
562
+ return new Promise((res, rej) => {
563
+ document.execCommand("copy") ? res() : rej();
564
+ textArea.remove();
565
+ });
566
+ }
567
+ };
568
+ function formatNumberWithCommas(number) {
569
+ const numericValue = parseFloat(number);
570
+ if (!isNaN(numericValue)) {
571
+ return numericValue.toLocaleString();
572
+ }
573
+ return number;
574
+ }
575
+ var generateRandomNumbers = (min, max, count) => {
576
+ const randomNumbers = /* @__PURE__ */ new Set();
577
+ while (randomNumbers.size < count) {
578
+ const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
579
+ randomNumbers.add(randomNumber);
580
+ }
581
+ return Array.from(randomNumbers);
582
+ };
583
+ var getFileName = (filePath) => {
584
+ return filePath.split("?")[0].split("/").pop() || "";
585
+ };
586
+ var textAreaView = (con) => {
587
+ return con ? con.replace(/\r\n/g, "\n").replace(/\n/g, "<br/>") : "";
588
+ };
589
+ var buildUrlParams = (obj, url) => {
590
+ const params = Object.entries(obj).filter(([, value]) => !isNullOrUnDef(value)).map(([key, value]) => {
591
+ if (isArray(value)) {
592
+ return value.filter((v) => !isNullOrUnDef(v)).map((v) => `${encodeURIComponent(key)}=${encodeURIComponent(v)}`).join("&");
593
+ }
594
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
595
+ }).join("&");
596
+ if (url) {
597
+ const separator = url.includes("?") ? "&" : "?";
598
+ return `${url}${separator}${params}`;
599
+ }
600
+ return params;
601
+ };
602
+ var downloadFile = (url, name) => {
603
+ const a = document.createElement("a");
604
+ a.download = name || "\u56FE\u7247\u4E0B\u8F7D";
605
+ a.href = url;
606
+ document.body.appendChild(a);
607
+ a.click();
608
+ document.body.removeChild(a);
609
+ };
610
+ var addUrlLastSlash = (url = "") => {
611
+ const u = new URL(url, "https://logosdata.cn");
612
+ let pathname = u.pathname;
613
+ if (!pathname.endsWith("/")) {
614
+ pathname += "/";
615
+ }
616
+ u.pathname = pathname;
617
+ return `${isExternal(url) ? u.origin : ""}${u.pathname}${u.search}${u.hash}`;
618
+ };
619
+ var getUrlMainSource = (url, preHref) => {
620
+ if (!preHref) return url;
621
+ let newUrl = "";
622
+ const preHrefUrl = new URL(preHref);
623
+ const urlParts = url.split("?");
624
+ const srcParams = new URLSearchParams(urlParts[1] || "");
625
+ if (srcParams.has("mainSource")) {
626
+ newUrl = url;
627
+ } else {
628
+ const mainSource = preHrefUrl.searchParams.get("mainSource");
629
+ if (mainSource) {
630
+ newUrl = buildUrlParams({ mainSource }, url);
631
+ } else {
632
+ newUrl = url;
633
+ }
634
+ }
635
+ return newUrl;
636
+ };
637
+ var getWebSocketUrl = (path, customHost) => {
638
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
639
+ const host = customHost || window.location.host;
640
+ return `${protocol}//${host}${path}`;
641
+ };
642
+
643
+ // src/hooks/useDeepEffect.ts
644
+ function useDeepEffect(effect, deps) {
645
+ const prevDepsRef = useRef();
646
+ const depsChanged = !prevDepsRef.current || deps.length !== prevDepsRef.current.length || deps.some((dep, i) => !deepEqual(dep, prevDepsRef.current[i]));
647
+ useEffect(() => {
648
+ if (depsChanged) {
649
+ prevDepsRef.current = deps;
650
+ return effect();
651
+ }
652
+ }, [depsChanged]);
653
+ }
654
+ function useRefState(init) {
655
+ const [state, setState] = useState(init);
656
+ const stateRef = useRef(init);
657
+ const setProxy = (newVal) => {
658
+ stateRef.current = newVal;
659
+ setState(newVal);
660
+ };
661
+ const getState = () => stateRef.current;
662
+ return [state, setProxy, getState];
663
+ }
664
+ var useSyncInput = (storeValue, setStoreValue) => {
665
+ const [inputValue, setInputValue] = useState(storeValue);
666
+ useEffect(() => {
667
+ if (storeValue !== inputValue) {
668
+ setInputValue(storeValue);
669
+ }
670
+ }, [storeValue]);
671
+ const handleValueChange = (value) => {
672
+ setStoreValue(value);
673
+ setInputValue(value);
674
+ };
675
+ return {
676
+ inputValue,
677
+ setInputValue: handleValueChange
678
+ };
679
+ };
680
+ function useThrottle(func, wait) {
681
+ const { current } = useRef({ func, timeOut: null });
682
+ useEffect(() => {
683
+ current.func = func;
684
+ }, [func]);
685
+ let args;
686
+ function throttle(..._args) {
687
+ args = _args;
688
+ return new Promise((resolve, reject) => {
689
+ if (!current.timeOut) {
690
+ try {
691
+ const result = current.func.apply(null, args);
692
+ resolve(result);
693
+ } catch (e) {
694
+ reject(e);
695
+ }
696
+ current.timeOut = setTimeout(() => {
697
+ current.timeOut = null;
698
+ }, wait);
699
+ }
700
+ });
701
+ }
702
+ function cancel() {
703
+ if (!current.timeOut) return;
704
+ clearTimeout(current.timeOut);
705
+ current.timeOut = null;
706
+ }
707
+ function flush() {
708
+ cancel();
709
+ return current.func.apply(null, args);
710
+ }
711
+ throttle.flush = flush;
712
+ throttle.cancel = cancel;
713
+ return useCallback(throttle, []);
714
+ }
715
+ dayjs.extend(relativeTime);
716
+ var DateFormatType = "YYYY-MM-DD HH:mm:ss";
717
+ var DateFormatType2 = "YYYY-MM-DD";
718
+ var UNIT = "date";
719
+ var getStartOfTimestamp = (date, unit = UNIT) => {
720
+ return dayjs(date).startOf(unit).valueOf();
721
+ };
722
+ var getEndOfTimestamp = (date, unit = UNIT) => {
723
+ return dayjs(date).endOf(unit).valueOf();
724
+ };
725
+ var formatDate = (date, fmt = DateFormatType) => {
726
+ if (date) {
727
+ return dayjs(date).format(fmt);
728
+ }
729
+ return "";
730
+ };
731
+ var getTimestamp = (date) => {
732
+ return dayjs(date).valueOf();
733
+ };
734
+ var isExpire = (date) => {
735
+ return dayjs(date).isBefore(getStartOfTimestamp());
736
+ };
737
+ var USER_KEY = "NS-USER";
738
+ function setCurrentUser(userInfo) {
739
+ const cipherText = AES.encrypt(JSON.stringify(userInfo), "((#II))").toString();
740
+ sessionStorage.setItem(USER_KEY, cipherText);
741
+ }
742
+ function getCurrentUser() {
743
+ const userInfoJson = sessionStorage.getItem(USER_KEY);
744
+ if (userInfoJson) {
745
+ const bytes = AES.decrypt(userInfoJson, "((#II))");
746
+ const originalText = bytes.toString(encUtf8);
747
+ return JSON.parse(originalText);
748
+ }
749
+ return null;
750
+ }
751
+ function clearCurrentUser() {
752
+ sessionStorage.removeItem(USER_KEY);
753
+ }
754
+ var DEVICEID_KEY = "NS-DEVICE-ID";
755
+ function getDeviceId() {
756
+ let deviceId = localStorage.getItem(DEVICEID_KEY);
757
+ if (deviceId) {
758
+ return deviceId;
759
+ }
760
+ deviceId = genNonDuplicateID();
761
+ localStorage.setItem(DEVICEID_KEY, deviceId);
762
+ return deviceId;
763
+ }
764
+ var OperatorToMethodName = {
765
+ "+": "plus",
766
+ "-": "minus",
767
+ "*": "times",
768
+ "/": "dividedBy"
769
+ };
770
+ var calculate = (operator, ...args) => {
771
+ if (args.length === 0) return "0";
772
+ const [arg, ...newArgs] = args;
773
+ return newArgs.reduce((acc, val) => acc[OperatorToMethodName[operator]](new Decimal(val)), new Decimal(arg)).toString();
774
+ };
775
+ var plus = (...args) => calculate("+", ...args);
776
+ var minus = (...args) => calculate("-", ...args);
777
+ var times = (...args) => calculate("*", ...args);
778
+ var dividedBy = (...args) => calculate("/", ...args);
779
+ var decimalPlaces = (arg1) => {
780
+ return new Decimal(arg1).decimalPlaces();
781
+ };
782
+ var precision = (arg1) => {
783
+ return new Decimal(arg1).precision(true);
784
+ };
785
+ var absVal = (arg1) => new Decimal(arg1).abs().toString();
786
+ var compareNum = (arg1, arg2, type) => {
787
+ const x = new Decimal(arg1);
788
+ const y = new Decimal(arg2);
789
+ switch (type) {
790
+ case ">":
791
+ return x.greaterThan(y);
792
+ case ">=":
793
+ return x.greaterThanOrEqualTo(y);
794
+ case "<":
795
+ return x.lessThan(y);
796
+ case "<=":
797
+ return x.lessThanOrEqualTo(y);
798
+ case "==":
799
+ return x.equals(y);
800
+ }
801
+ };
802
+ var toFixed = (num, decimals = 2, fill = true) => {
803
+ const x = new Decimal(num);
804
+ if (fill) {
805
+ return x.toFixed(decimals, Decimal.ROUND_HALF_UP);
806
+ } else {
807
+ return x.toDecimalPlaces(decimals, Decimal.ROUND_HALF_UP).toString();
808
+ }
809
+ };
810
+ var isInteger = (num) => {
811
+ return new Decimal(num).isInteger();
812
+ };
813
+ var isNegative = (num) => {
814
+ return new Decimal(num).isNegative();
815
+ };
816
+ var cacheMessage = () => {
817
+ const contents = {};
818
+ return ({ title = "\u63D0\u793A", content, type = "warning", duration = 3, onClose, isCache = true, isOnly = false }) => {
819
+ if (!content) return;
820
+ const key = isOnly ? "cache-key" : content;
821
+ const onClose2 = () => {
822
+ delete contents[key];
823
+ onClose?.();
824
+ };
825
+ if (isCache && contents[key]) ; else {
826
+ if (isCache) {
827
+ contents[key] = getTimestamp();
828
+ }
829
+ if (duration) {
830
+ if (content.length > 30) {
831
+ notification[type]({
832
+ message: title,
833
+ description: content,
834
+ placement: "top",
835
+ duration,
836
+ onClose: onClose2
837
+ });
838
+ } else {
839
+ message[type]({
840
+ content,
841
+ duration,
842
+ onClose: onClose2
843
+ });
844
+ }
845
+ } else {
846
+ Modal[type]({
847
+ title,
848
+ content,
849
+ okButtonProps: { style: { background: LgPrimaryColor, outline: "none" } },
850
+ afterClose: onClose2
851
+ });
852
+ }
853
+ }
854
+ };
855
+ };
856
+ var showMessage = cacheMessage();
857
+
858
+ // src/utils/session.ts
859
+ var TOKEN_KEY = "NS-TOKEN";
860
+ function setToken(accessToken) {
861
+ localStorage.setItem(TOKEN_KEY, accessToken);
862
+ }
863
+ function getUrlToken() {
864
+ const searchParams = new URLSearchParams(location.search);
865
+ const token = searchParams.get(TOKEN_KEY);
866
+ return token || "";
867
+ }
868
+ function getToken() {
869
+ const token = getUrlToken();
870
+ if (!token) {
871
+ const token2 = localStorage.getItem(TOKEN_KEY);
872
+ return token2 || "";
873
+ } else {
874
+ setToken(token);
875
+ return token;
876
+ }
877
+ }
878
+ function clearToken() {
879
+ localStorage.removeItem(TOKEN_KEY);
880
+ }
881
+ var SIGNPATH = "SIGNPATH";
882
+ function getSignPath() {
883
+ const path = localStorage.getItem(SIGNPATH);
884
+ return `${path || "/sign-in"}`;
885
+ }
886
+
887
+ // src/utils/request.ts
888
+ var OK = 200;
889
+ var OK2 = "S0000";
890
+ var ERROR = 500;
891
+ var MISSING_PARAMETER = 400;
892
+ var UNAUTHORIZED = 401;
893
+ var FORBIDDEN = 403;
894
+ var NOT_FOUND = 404;
895
+ var ILLEGAL_PARAMETER = 901;
896
+ var PERMISSION_DENIED = 13001;
897
+ var LoginPastCode = 11200;
898
+ var FacePastCode = 11201;
899
+ var formType = "form";
900
+ var jsonType = "json";
901
+ var parseOptions = (options) => {
902
+ const headers = {};
903
+ if (options?.reqType && options.reqType === formType) {
904
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
905
+ }
906
+ return { headers, ...options };
907
+ };
908
+ var redirectUrl = () => {
909
+ emit("jumpLink", { url: `/uc${getSignPath()}` });
910
+ };
911
+ axios.interceptors.request.use(
912
+ function(config) {
913
+ config.headers[TOKEN_KEY] = getToken();
914
+ if (config.url && !config.url.startsWith("/api/")) {
915
+ config.baseURL = "/api";
916
+ }
917
+ config.timeout = config.timeout || 6e4;
918
+ return config;
919
+ },
920
+ function(error) {
921
+ return Promise.reject(error);
922
+ }
923
+ );
924
+ axios.interceptors.response.use(
925
+ function(response) {
926
+ if (response.data?.code !== OK && response.data?.code !== OK2) {
927
+ const isPermission = response.data?.code === PERMISSION_DENIED;
928
+ if (response.config?.showError !== false) {
929
+ showMessage({
930
+ title: isPermission ? "" : void 0,
931
+ content: response.data.message,
932
+ duration: isPermission ? 0 : 3
933
+ });
934
+ }
935
+ return Promise.reject(response.data);
936
+ }
937
+ return response;
938
+ },
939
+ function(err) {
940
+ const showError = err?.config?.showError !== false;
941
+ if (!err.response) {
942
+ if (showError) showMessage({ content: "\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC", type: "error" });
943
+ } else {
944
+ switch (err.response?.status) {
945
+ case UNAUTHORIZED:
946
+ if (showError) showMessage({ content: err.response?.data.message, type: "error" });
947
+ redirectUrl();
948
+ break;
949
+ case FORBIDDEN:
950
+ case NOT_FOUND:
951
+ case ERROR:
952
+ case MISSING_PARAMETER:
953
+ case ILLEGAL_PARAMETER:
954
+ if (showError) showMessage({ content: err.response?.data.message, type: "error" });
955
+ break;
956
+ default:
957
+ if (showError) showMessage({ content: "\u8BF7\u6C42\u6570\u636E\u53D1\u751F\u9519\u8BEF\uFF01", type: "info" });
958
+ }
959
+ }
960
+ return Promise.reject(err);
961
+ }
962
+ );
963
+ var get = async (url, params, options) => {
964
+ const res = await axios({ method: "get", url, params, ...options });
965
+ return res.data;
966
+ };
967
+ var post = async (url, data, options) => {
968
+ const res = await axios({
969
+ method: "post",
970
+ url,
971
+ data,
972
+ ...parseOptions(options)
973
+ });
974
+ return res.data;
975
+ };
976
+ var put = async (url, data, options) => {
977
+ const res = await axios({ method: "put", url, data, ...parseOptions(options) });
978
+ return res.data;
979
+ };
980
+ var del = async (url, data, options) => {
981
+ const reqConfig = {
982
+ method: "delete",
983
+ url,
984
+ ...parseOptions(options)
985
+ };
986
+ const params = options?.reqType === formType ? { params: data } : { data };
987
+ const res = await axios({ ...reqConfig, ...params });
988
+ return res.data;
989
+ };
990
+ var request_default = {
991
+ get,
992
+ post,
993
+ put,
994
+ delete: del
995
+ };
996
+
997
+ // src/hooks/useWebSocket.ts
998
+ var useWebSocket = ({
999
+ url,
1000
+ onMessage,
1001
+ onClose,
1002
+ heartbeatInterval = 3e4,
1003
+ heartbeatMessage = "ping",
1004
+ clientHeartbeat = true,
1005
+ reconnectInterval = 5e3,
1006
+ // 默认重连间隔为 5 秒
1007
+ maxReconnectAttempts,
1008
+ // 不设置默认值为无限重连
1009
+ isReconnect = true
1010
+ // 默认开启重连机制
1011
+ }) => {
1012
+ const socketRef = useRef(null);
1013
+ const heartbeatIntervalRef = useRef(null);
1014
+ const [socketReadyState, setSocketReadyState] = useState(null);
1015
+ const reconnectIntervalRef = useRef(null);
1016
+ const reconnectAttempts = useRef(0);
1017
+ const documentHide = useRef(document.visibilityState === "hidden");
1018
+ const isDestroy = useRef(false);
1019
+ const onMessageEctype = useCallback(onMessage, [onMessage]);
1020
+ const startHeartbeat = (currentSocket) => {
1021
+ if (!clientHeartbeat) {
1022
+ return;
1023
+ }
1024
+ const intervalId = setInterval(() => {
1025
+ if (currentSocket.readyState === WebSocket.OPEN) {
1026
+ currentSocket.send(heartbeatMessage);
1027
+ }
1028
+ }, heartbeatInterval);
1029
+ heartbeatIntervalRef.current = intervalId;
1030
+ };
1031
+ const stopHeartbeat = () => {
1032
+ if (heartbeatIntervalRef.current) {
1033
+ clearInterval(heartbeatIntervalRef.current);
1034
+ }
1035
+ };
1036
+ const stopReconnectTimer = () => {
1037
+ if (reconnectIntervalRef.current) {
1038
+ clearTimeout(reconnectIntervalRef.current);
1039
+ reconnectIntervalRef.current = null;
1040
+ }
1041
+ };
1042
+ const tryReconnect = () => {
1043
+ if (isDestroy.current) return;
1044
+ if (isReconnect && !documentHide.current) {
1045
+ if ((!isNumber(maxReconnectAttempts) || reconnectAttempts.current < maxReconnectAttempts) && isNullOrUnDef(reconnectIntervalRef.current)) {
1046
+ reconnectIntervalRef.current = setTimeout(() => {
1047
+ console.log(`\u5C1D\u8BD5\u7B2C ${reconnectAttempts.current + 1} \u6B21\u91CD\u8FDE...`, url);
1048
+ reconnectAttempts.current = reconnectAttempts.current + 1;
1049
+ createAndListenWebSocket();
1050
+ stopReconnectTimer();
1051
+ }, reconnectInterval);
1052
+ } else {
1053
+ if (isNumber(maxReconnectAttempts)) {
1054
+ console.log("\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u5C1D\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE");
1055
+ }
1056
+ }
1057
+ }
1058
+ };
1059
+ const handleOpen = (newSocket) => {
1060
+ console.log("WebSocket \u8FDE\u63A5\u5DF2\u6253\u5F00");
1061
+ setSocketReadyState(newSocket.readyState);
1062
+ startHeartbeat(newSocket);
1063
+ reconnectAttempts.current = 0;
1064
+ };
1065
+ const handleMessage = (event) => {
1066
+ if (isString(event.data)) {
1067
+ try {
1068
+ const parsedData = JSON.parse(event.data);
1069
+ onMessageEctype?.(parsedData);
1070
+ stopHeartbeat();
1071
+ startHeartbeat(socketRef.current);
1072
+ } catch (error) {
1073
+ console.error("\u89E3\u6790\u6D88\u606F\u6570\u636E\u65F6\u51FA\u9519:", error);
1074
+ }
1075
+ }
1076
+ };
1077
+ const handleClose = (event) => {
1078
+ console.log("WebSocket \u8FDE\u63A5\u5DF2\u5173\u95ED", event.code, event.reason);
1079
+ setSocketReadyState(event.code);
1080
+ stopHeartbeat();
1081
+ onClose?.();
1082
+ tryReconnect();
1083
+ };
1084
+ const handleError = (error) => {
1085
+ console.error("WebSocket \u53D1\u751F\u9519\u8BEF:", error);
1086
+ setSocketReadyState(null);
1087
+ stopHeartbeat();
1088
+ tryReconnect();
1089
+ };
1090
+ const createAndListenWebSocket = () => {
1091
+ const newSocket = new WebSocket(url);
1092
+ socketRef.current = newSocket;
1093
+ setSocketReadyState(newSocket.readyState);
1094
+ newSocket.onopen = () => handleOpen(newSocket);
1095
+ newSocket.onmessage = handleMessage;
1096
+ newSocket.onclose = handleClose;
1097
+ newSocket.onerror = handleError;
1098
+ };
1099
+ const handleVisibilityChange = () => {
1100
+ documentHide.current = document.visibilityState === "hidden";
1101
+ if (socketRef.current?.readyState !== WebSocket.OPEN) {
1102
+ tryReconnect();
1103
+ }
1104
+ };
1105
+ useEffect(() => {
1106
+ isDestroy.current = false;
1107
+ createAndListenWebSocket();
1108
+ window.addEventListener("visibilitychange", handleVisibilityChange);
1109
+ return () => {
1110
+ window.removeEventListener("visibilitychange", handleVisibilityChange);
1111
+ isDestroy.current = true;
1112
+ if (socketRef.current) {
1113
+ socketRef.current.close();
1114
+ return;
1115
+ }
1116
+ stopHeartbeat();
1117
+ stopReconnectTimer();
1118
+ };
1119
+ }, [url]);
1120
+ const sendMessage = (message2) => {
1121
+ if (socketRef.current?.readyState === WebSocket.OPEN) {
1122
+ socketRef.current.send(message2);
1123
+ stopHeartbeat();
1124
+ startHeartbeat(socketRef.current);
1125
+ }
1126
+ };
1127
+ return {
1128
+ sendMessage,
1129
+ socketReadyState
1130
+ };
1131
+ };
1132
+ var useWebSocket_default = useWebSocket;
1133
+ var ProtectedView = ({
1134
+ passwordStatus,
1135
+ verifyPassword,
1136
+ onVerifyPasswordEnd
1137
+ }) => {
1138
+ const [form] = Form.useForm();
1139
+ const onSubmit = () => {
1140
+ form.validateFields().then((values) => {
1141
+ if (values) {
1142
+ verifyPassword(values.password);
1143
+ onVerifyPasswordEnd(values.password);
1144
+ }
1145
+ });
1146
+ };
1147
+ return /* @__PURE__ */ jsx(Flex, { justify: "center", align: "center", className: "height-full", children: /* @__PURE__ */ jsxs("div", { style: { width: 300 }, children: [
1148
+ passwordStatus === PasswordStatus.WrongPassword && /* @__PURE__ */ jsx(Alert, { message: "\u5BC6\u7801\u65E0\u6548\u3002\u8BF7\u518D\u8BD5\u4E00\u6B21\uFF01", type: "error" }),
1149
+ /* @__PURE__ */ jsxs(Form, { form, size: "large", className: "m-t-24", children: [
1150
+ /* @__PURE__ */ jsx(Form.Item, { name: "password", rules: [{ required: true, message: "\u8BF7\u8F93\u5165\u5BC6\u7801" }], children: /* @__PURE__ */ jsx(Input.Password, { autoComplete: "new-password", placeholder: "\u8BF7\u8F93\u5165\u5BC6\u7801" }) }),
1151
+ /* @__PURE__ */ jsx(Flex, { justify: "center", children: /* @__PURE__ */ jsx(Button, { type: "primary", onClick: onSubmit, children: "\u63D0 \u4EA4" }) })
1152
+ ] })
1153
+ ] }) });
1154
+ };
1155
+ var PdfPreview_default = ({ password, fileUrl, pageNo = 1, scale = 1, isHasThumbnails = true, onSetPassword, onSetPageNo }) => {
1156
+ const embedRef = useRef(null);
1157
+ const [sizes, setSizes] = useState([0]);
1158
+ const [, setDocLoaded, getDocLoaded] = useRefState(false);
1159
+ const [currentPage, setCurrentPage, getCurrentPage] = useRefState(void 0);
1160
+ const [temporaryPassword, setTemporaryPassword] = useState("");
1161
+ const jumpToPageNo = useRef();
1162
+ const onVerifyPasswordEnd = (password2) => {
1163
+ setTemporaryPassword(password2);
1164
+ };
1165
+ const pageNavigationPluginInstance = pageNavigationPlugin({ enableShortcuts: true });
1166
+ const thumbnailPluginInstance = thumbnailPlugin({
1167
+ thumbnailWidth: sizes[0] - 70
1168
+ // 不会自适应
1169
+ });
1170
+ const zoomPluginInstance = zoomPlugin();
1171
+ const { Thumbnails } = thumbnailPluginInstance;
1172
+ const { ZoomIn, ZoomOut } = zoomPluginInstance;
1173
+ const Toolbar = () => /* @__PURE__ */ jsxs(Flex, { gap: 6, align: "center", className: styles_module_default.pdfToolbar, children: [
1174
+ /* @__PURE__ */ jsx(ZoomIn, {}),
1175
+ /* @__PURE__ */ jsx(ZoomOut, {})
1176
+ ] });
1177
+ const onJumpToPage = (pageNo2) => {
1178
+ if (getDocLoaded()) {
1179
+ if (pageNo2 && pageNo2 - 1 !== getCurrentPage()) {
1180
+ jumpToPageNo.current = pageNo2 - 1;
1181
+ pageNavigationPluginInstance.jumpToPage(jumpToPageNo.current);
1182
+ }
1183
+ }
1184
+ };
1185
+ const handleDocumentLoad = () => {
1186
+ setSizes([400]);
1187
+ setDocLoaded(true);
1188
+ onJumpToPage(pageNo);
1189
+ if (temporaryPassword) {
1190
+ onSetPassword?.(temporaryPassword);
1191
+ setTemporaryPassword("");
1192
+ }
1193
+ };
1194
+ useEffect(() => {
1195
+ setCurrentPage(void 0);
1196
+ setDocLoaded(false);
1197
+ setSizes([0]);
1198
+ }, [fileUrl]);
1199
+ useEffect(() => {
1200
+ setTimeout(() => {
1201
+ onJumpToPage(pageNo);
1202
+ }, 0);
1203
+ }, [pageNo]);
1204
+ const renderError = (error) => {
1205
+ let message2 = "";
1206
+ switch (error.name) {
1207
+ case "InvalidPDFException":
1208
+ message2 = "\u6587\u4EF6\u65E0\u6548\u6216\u5DF2\u635F\u574F";
1209
+ break;
1210
+ case "MissingPDFException":
1211
+ message2 = "\u6587\u4EF6\u4E0D\u5B58\u5728";
1212
+ break;
1213
+ case "UnexpectedResponseException":
1214
+ message2 = "\u610F\u5916\u7684\u670D\u52A1\u5668\u54CD\u5E94";
1215
+ break;
1216
+ // case 'CMapReaderFactory not initialized':
1217
+ // message = '字体映射文件加载失败,请刷新页面重试'
1218
+ // break
1219
+ default:
1220
+ message2 = "\u65E0\u6CD5\u52A0\u8F7D\u6587\u6863";
1221
+ break;
1222
+ }
1223
+ return /* @__PURE__ */ jsx(Flex, { className: "height-full", justify: "center", align: "center", children: /* @__PURE__ */ jsx(Alert, { message: message2, type: "error", showIcon: true }) });
1224
+ };
1225
+ const onPageChange = (e) => {
1226
+ let newCurrentPage = e.currentPage;
1227
+ if (isNumber(jumpToPageNo.current)) {
1228
+ newCurrentPage = jumpToPageNo.current;
1229
+ setTimeout(() => {
1230
+ jumpToPageNo.current = void 0;
1231
+ }, 1e3);
1232
+ }
1233
+ setCurrentPage(newCurrentPage);
1234
+ };
1235
+ useEffect(() => {
1236
+ if (!(embedRef.current && isNumber(currentPage))) return;
1237
+ setTimeout(() => {
1238
+ const pages = embedRef.current?.querySelectorAll(".rpv-core__viewer .rpv-core__page-layer");
1239
+ pages?.forEach((page) => {
1240
+ if (Number(page.getAttribute("data-virtual-index")) === currentPage) {
1241
+ page.classList.add("current-page-highlight");
1242
+ } else {
1243
+ page.classList.remove("current-page-highlight");
1244
+ }
1245
+ });
1246
+ }, 500);
1247
+ onSetPageNo?.(currentPage + 1);
1248
+ }, [currentPage]);
1249
+ return /* @__PURE__ */ jsx("div", { ref: embedRef, className: styles_module_default.nsPreviewPdf, children: /* @__PURE__ */ jsx(Worker, { workerUrl: `/uc/pdf/pdf.worker.min.js`, children: /* @__PURE__ */ jsxs(Splitter, { onResize: setSizes, children: [
1250
+ isHasThumbnails && /* @__PURE__ */ jsx(Splitter.Panel, { resizable: false, size: sizes[0], min: 250, max: 500, collapsible: true, children: /* @__PURE__ */ jsx(Thumbnails, {}) }),
1251
+ /* @__PURE__ */ jsx(Splitter.Panel, { children: /* @__PURE__ */ jsxs("div", { className: "height-full", children: [
1252
+ /* @__PURE__ */ jsx(
1253
+ Viewer,
1254
+ {
1255
+ localization: zh_CN,
1256
+ withCredentials: true,
1257
+ onDocumentAskPassword: (e) => {
1258
+ setTemporaryPassword("");
1259
+ e.verifyPassword(password || "");
1260
+ },
1261
+ transformGetDocumentParams: (options) => {
1262
+ return Object.assign({}, options, {
1263
+ // disableRange: false,
1264
+ disableStream: true,
1265
+ // 建议传入是否加密字段来控制
1266
+ httpHeaders: { "Cache-Control": "no-cache" },
1267
+ // 启用 CMap 支持,解决中文字体显示问题
1268
+ // cMapUrl: 指定 CMap 文件的 URL,用于处理非拉丁字符(如中文)
1269
+ // cMapPacked: 使用压缩的 CMap 文件以提高性能
1270
+ cMapUrl: "/uc/pdf/pdfjs-dist@3.2.146/cmaps/",
1271
+ // 使用可用的源
1272
+ cMapPacked: true,
1273
+ // 禁用字体子集化,确保完整字体加载
1274
+ disableFontFace: false,
1275
+ // 启用标准字体支持
1276
+ standardFontDataUrl: "/uc/pdf/pdfjs-dist@3.2.146/standard_fonts/",
1277
+ // 设置字体回退策略
1278
+ fallbackFontName: "Helvetica"
1279
+ });
1280
+ },
1281
+ fileUrl,
1282
+ defaultScale: scale,
1283
+ plugins: [
1284
+ pageNavigationPluginInstance,
1285
+ thumbnailPluginInstance,
1286
+ zoomPluginInstance
1287
+ // printPluginInstance,
1288
+ // rotatePluginInstance,
1289
+ // searchPluginInstance,
1290
+ ],
1291
+ onPageChange,
1292
+ renderError,
1293
+ onDocumentLoad: handleDocumentLoad,
1294
+ renderProtectedView: (renderProps) => /* @__PURE__ */ jsx(ProtectedView, { onVerifyPasswordEnd, ...renderProps })
1295
+ }
1296
+ ),
1297
+ /* @__PURE__ */ jsx(Toolbar, {})
1298
+ ] }) })
1299
+ ] }) }) });
1300
+ };
1301
+ var FilePreview_default = ({ suffix, fileUrl, pdfParams, password, searchValue }) => {
1302
+ const Preview = useMemo(() => {
1303
+ if (!fileUrl) {
1304
+ return /* @__PURE__ */ jsx(Empty, {});
1305
+ }
1306
+ switch (suffix?.toUpperCase()) {
1307
+ case "PNG":
1308
+ case "JPG":
1309
+ case "JPEG":
1310
+ case "GIF":
1311
+ return /* @__PURE__ */ jsx(Image, { rootClassName: styles_module_default.nsPreviewImage, src: fileUrl, alt: "\u9884\u89C8\u56FE\u7247" });
1312
+ case "PDF":
1313
+ return /* @__PURE__ */ jsx(PdfPreview_default, { fileUrl, ...pdfParams, password });
1314
+ // onSetPassword={onSetPassword}
1315
+ case "MP4":
1316
+ return /* @__PURE__ */ jsx(VideoPlayer_default, { fileUrl });
1317
+ case "MP3":
1318
+ return /* @__PURE__ */ jsx(AudioPlayer_default, { fileUrl });
1319
+ case "MD":
1320
+ case "MARKDOWN":
1321
+ return /* @__PURE__ */ jsx(MarkdownPreview_default, { fileUrl, searchValue });
1322
+ default:
1323
+ return /* @__PURE__ */ jsx(Result, { subTitle: `\u6682\u4E0D\u652F\u6301 ${suffix || ""} \u6587\u4EF6\u7684\u9884\u89C8` });
1324
+ }
1325
+ }, [suffix, fileUrl, pdfParams]);
1326
+ return /* @__PURE__ */ jsx(Flex, { justify: "center", align: "center", className: "height-full", children: Preview });
1327
+ };
1328
+ var FilePreviewDrawer_default = ({ open, fileUrl, suffix, title = "\u6587\u4EF6\u9884\u89C8", onClose, password, fileParams, pdfParams, onSetPassSuccess }) => {
1329
+ return /* @__PURE__ */ jsx(Drawer, { title, push: false, width: "100%", open, onClose, children: /* @__PURE__ */ jsx(
1330
+ FilePreview_default,
1331
+ {
1332
+ fileUrl,
1333
+ suffix,
1334
+ password,
1335
+ fileParams,
1336
+ pdfParams,
1337
+ onSetPassSuccess
1338
+ }
1339
+ ) });
1340
+ };
1341
+
1342
+ // src/components/Iframe/styles.module.less
1343
+ var styles_module_default2 = {
1344
+ iframe: "styles_module_iframe"
1345
+ };
1346
+ var Iframe_default = forwardRef(({ id, src, className, onLoad }, ref) => {
1347
+ const [loading, setLoading] = useState(false);
1348
+ const finalSrc = useMemo(() => {
1349
+ return buildUrlParams({ v: Date.now() }, addUrlLastSlash(getUrlMainSource(src, location.href)));
1350
+ }, [src]);
1351
+ const onHandleLoad = () => {
1352
+ setLoading(false);
1353
+ onLoad?.();
1354
+ };
1355
+ useEffect(() => {
1356
+ setLoading(true);
1357
+ }, [src]);
1358
+ return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(Spin, { spinning: loading, wrapperClassName: "full-spin", tip: "\u52A0\u8F7D\u4E2D...", children: /* @__PURE__ */ jsx("iframe", { id, ref, src: finalSrc, className: classNames(styles_module_default2.iframe, className), onLoad: onHandleLoad }) }) });
1359
+ });
1360
+ function isRenderFn(node) {
1361
+ return isFunction(node) || isObject(node) && !isNull(node) && "$$typeof" in node && node.$$typeof === Symbol.for("react.forward_ref");
1362
+ }
1363
+ function renderDefault(DefaultComponent, props) {
1364
+ if (!DefaultComponent) return null;
1365
+ return isRenderFn(DefaultComponent) ? /* @__PURE__ */ jsx(DefaultComponent, { ...props }) : DefaultComponent;
1366
+ }
1367
+ function RenderWrapper({ control = true, ctx, DefaultComponent }) {
1368
+ if (control === false || isNull(control)) return null;
1369
+ if (control === true || control === void 0) {
1370
+ return renderDefault(DefaultComponent);
1371
+ }
1372
+ const { visible = true, render, props } = control;
1373
+ if (!visible) return null;
1374
+ if (render) {
1375
+ return typeof render === "function" ? render(ctx) : render;
1376
+ }
1377
+ return renderDefault(DefaultComponent, props);
1378
+ }
1379
+ var shouldRender = (control) => control != null && (isBoolean(control) ? control : control?.visible !== false);
1380
+ function propsMerge(control, props) {
1381
+ if (control === true || control === void 0) {
1382
+ return {
1383
+ props
1384
+ };
1385
+ }
1386
+ if (isObject(control) && (control?.visible === true || control?.visible === void 0)) {
1387
+ return {
1388
+ props: {
1389
+ ...props,
1390
+ ...control?.props
1391
+ }
1392
+ };
1393
+ }
1394
+ return null;
1395
+ }
1396
+ var UserAvatar_default = ({ size, avatarSrc, userName }) => {
1397
+ return avatarSrc ? /* @__PURE__ */ jsx(Avatar, { size, src: avatarSrc }) : /* @__PURE__ */ jsx(Avatar, { size, className: "cursor-pointer", style: { backgroundColor: LgPrimaryColor }, children: userName?.slice(0, 1)?.toLocaleUpperCase() });
1398
+ };
1399
+
1400
+ export { AudioPlayer_default as AudioPlayer, DateFormatType, DateFormatType2, ERROR, FORBIDDEN, FacePastCode, FileIcon_default as FileIcon, FilePreview_default as FilePreview, FilePreviewDrawer_default as FilePreviewDrawer, ILLEGAL_PARAMETER, Iframe_default as Iframe, LazyComponent_default as LazyComponent, LgPrimaryColor, LoginPastCode, MISSING_PARAMETER, MarkdownPreview_default as MarkdownPreview, NOT_FOUND, OK, OK2, PERMISSION_DENIED, PdfPreview_default as PdfPreview, RenderMarkdown_default as RenderMarkdown, RenderWrapper, TOKEN_KEY, UNAUTHORIZED, UserAvatar_default as UserAvatar, VideoPlayer_default as VideoPlayer, absVal, addUrlLastSlash, arrToObj, buildUrlParams, calculate, clearCurrentUser, clearToken, compareNum, copyText, createValtioContext, decimalPlaces, deepCopy, deepEqual, deepMerge, dividedBy, downloadFile, emit, emitToChild, formType, formatDate, formatNumberWithCommas, genNonDuplicateID, generateRandomNumbers, getCurrentUser, getDeviceId, getEndOfTimestamp, getFileName, getSignPath, getStartOfTimestamp, getTimestamp, getToken, getUrlMainSource, getUrlToken, getWebSocketUrl, is, isArray, isBlob, isBoolean, isClient, isDate, isDef, isElement, isEmpty, isEmptyObj, isExpire, isExternal, isFunction, isInteger, isMap, isNegative, isNull, isNullOrUnDef, isNumber, isNumberNoNaN, isObject, isPromise, isRegExp, isServer, isString, isUnDef, isWindow, jsonType, minus, nsSetInterval, objToOptions, plus, precision, propsMerge, request_default as request, setCurrentUser, setToken, shouldRender, textAreaView, themeConfig, times, toFixed, useDebounce, useDeepEffect, useIframeRelayBridge, useRefState, useSyncInput, useThrottle, useWebSocket_default as useWebSocket };
1401
+ //# sourceMappingURL=index.esm.js.map
1402
+ //# sourceMappingURL=index.esm.js.map