clxx 3.0.0 → 3.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.
@@ -4,19 +4,33 @@ import { ContainerProps } from "../Container";
4
4
  export type RouterMode = "browser" | "hash" | "memory";
5
5
  export type AwaitValue<T> = T | Promise<T>;
6
6
  export interface CreateAppOption extends Omit<ContainerProps, "children"> {
7
+ /** 页面加载前触发,可 async;早于 render */
7
8
  onBefore?: (pathname: string) => AwaitValue<void>;
9
+ /** 页面成功渲染后触发,可 async;404 / 错误场景不触发 */
8
10
  onAfter?: (pathname: string) => AwaitValue<void>;
11
+ /** 返回加载中占位节点,在 render 执行期间展示 */
9
12
  loading?: (pathname: string) => AwaitValue<React.ReactNode>;
13
+ /** 根据路径返回页面节点;返回 null/undefined 触发 notFound */
10
14
  render?: (pathname: string) => AwaitValue<React.ReactNode>;
15
+ /** render 返回 null/undefined(404)时调用 */
11
16
  notFound?: (pathname: string) => AwaitValue<React.ReactNode>;
17
+ /** render 抛出错误时调用;未提供时降级到 notFound */
18
+ onError?: (pathname: string, error: unknown) => AwaitValue<React.ReactNode>;
19
+ /** 路由模式,默认 browser */
12
20
  mode?: RouterMode;
21
+ /** 路径为 / 或空时使用的默认路径,默认 /index */
13
22
  default?: string;
23
+ /** 路由切换时自动滚动到顶部,移动端推荐开启,默认 true */
24
+ scrollToTop?: boolean;
25
+ /** 开启 React.StrictMode,默认 false */
26
+ strict?: boolean;
27
+ /** 挂载目标(CSS 选择器或 HTMLElement) */
14
28
  target: string | HTMLElement;
15
29
  }
16
30
  export declare let history: null | History;
17
31
  export declare function getHistory(mode?: RouterMode): History;
18
32
  /**
19
- * 创建带路由的APP对象,全局对象,绝大部分情况下只需要调用一次
33
+ * 创建带路由的 App,全局单例,通常只调用一次。
20
34
  * @param option CreateAppOption
21
35
  */
22
- export declare function createApp(option: CreateAppOption): Promise<void>;
36
+ export declare function createApp(option: CreateAppOption): void;
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
36
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
37
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -8,140 +41,140 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
41
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
42
  });
10
43
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
44
  Object.defineProperty(exports, "__esModule", { value: true });
15
45
  exports.history = void 0;
16
46
  exports.getHistory = getHistory;
17
47
  exports.createApp = createApp;
18
48
  const jsx_runtime_1 = require("@emotion/react/jsx-runtime");
19
- const react_1 = require("react");
49
+ const react_1 = __importStar(require("react"));
20
50
  const client_1 = require("react-dom/client");
21
51
  const history_1 = require("history");
22
52
  const Container_1 = require("../Container");
23
- const pick_1 = __importDefault(require("lodash/pick"));
24
53
  // 存储历史记录对象
25
54
  exports.history = null;
26
55
  // 获取历史记录对象
27
56
  function getHistory(mode = "browser") {
28
57
  if (exports.history === null) {
29
- const createMap = {
58
+ const factories = {
30
59
  browser: history_1.createBrowserHistory,
31
60
  hash: history_1.createHashHistory,
32
61
  memory: history_1.createMemoryHistory,
33
62
  };
34
- exports.history = createMap[mode]();
63
+ exports.history = factories[mode]();
35
64
  }
36
65
  return exports.history;
37
66
  }
67
+ const VALID_MODES = new Set(["browser", "hash", "memory"]);
68
+ // 模块级常量,移除路径首尾斜杠;g 标志确保首尾各自替换一次
69
+ const PATH_TRIM_RE = /^\/*|\/*$/g;
38
70
  /**
39
- * 创建带路由的APP对象,全局对象,绝大部分情况下只需要调用一次
71
+ * 创建带路由的 App,全局单例,通常只调用一次。
40
72
  * @param option CreateAppOption
41
73
  */
42
74
  function createApp(option) {
43
- return __awaiter(this, void 0, void 0, function* () {
44
- // 设置默认的路由方式
45
- if (!option.mode ||
46
- ["browser", "hash", "memory"].indexOf(option.mode) === -1) {
47
- option.mode = "browser";
48
- }
49
- // 设置默认路由路径
50
- if (!option.default) {
51
- option.default = "/index";
52
- }
53
- // 这里是为了确保历史记录对象在组件渲染之前一定存在
54
- exports.history = getHistory(option.mode);
55
- // 提取关键数据
56
- const containerProps = (0, pick_1.default)(option, [
57
- "designWidth",
58
- "globalStyle",
59
- ]);
60
- const { onBefore, onAfter, loading, render, notFound } = option;
61
- // 规范化路径:移除首尾斜杠
62
- const PATH_TRIM_REGEX = /^\/*|\/*$/g;
63
- const normalizePath = (path) => {
64
- const normalized = path.replace(PATH_TRIM_REGEX, "");
65
- return normalized || option.default.replace(PATH_TRIM_REGEX, "");
66
- };
67
- /**
68
- * 全局APP组件对象
69
- * @returns
70
- */
71
- const App = () => {
72
- const [page, setPage] = (0, react_1.useState)(null);
73
- /**
74
- * 加载并渲染页面
75
- */
76
- const loadAndRenderPage = (0, react_1.useCallback)((pathname) => __awaiter(this, void 0, void 0, function* () {
77
- const normalizedPath = normalizePath(pathname);
78
- // 如果有 loading 占位符,先显示
79
- if (typeof loading === "function") {
80
- setPage(yield loading(normalizedPath));
75
+ var _a;
76
+ // 不修改入参,用局部变量保存规范化后的值
77
+ const mode = option.mode && VALID_MODES.has(option.mode) ? option.mode : "browser";
78
+ const defaultPath = ((_a = option.default) !== null && _a !== void 0 ? _a : "/index").replace(PATH_TRIM_RE, "");
79
+ const scrollToTop = option.scrollToTop !== false;
80
+ // 确保 history 在组件渲染前已就绪
81
+ exports.history = getHistory(mode);
82
+ // 提取 ContainerProps(含 maxWidth,原 pick 遗漏此项)
83
+ const { designWidth, maxWidth, globalStyle } = option;
84
+ const containerProps = { designWidth, maxWidth, globalStyle };
85
+ const { onBefore, onAfter, loading, render, notFound, onError } = option;
86
+ // 规范化路径:移除首尾斜杠,空路径回退到 defaultPath
87
+ const normalizePath = (path) => {
88
+ const normalized = path.replace(PATH_TRIM_RE, "");
89
+ return normalized || defaultPath;
90
+ };
91
+ /**
92
+ * 全局 App 组件,仅在 createApp 内实例化一次
93
+ */
94
+ const App = () => {
95
+ const [page, setPage] = (0, react_1.useState)(null);
96
+ // 导航版本号:每次发起新导航自增;过时的异步回调检测到不匹配后静默丢弃,
97
+ // 防止慢请求在更新的导航完成后覆盖页面(竞态条件)
98
+ const navIdRef = (0, react_1.useRef)(0);
99
+ const loadPage = (0, react_1.useCallback)((pathname) => __awaiter(this, void 0, void 0, function* () {
100
+ const navId = ++navIdRef.current;
101
+ const path = normalizePath(pathname);
102
+ // 1. 展示加载占位
103
+ if (typeof loading === "function") {
104
+ const loadingNode = yield loading(path);
105
+ if (navId !== navIdRef.current)
106
+ return;
107
+ setPage(loadingNode);
108
+ }
109
+ // 2. 前置钩子
110
+ yield (onBefore === null || onBefore === void 0 ? void 0 : onBefore(path));
111
+ if (navId !== navIdRef.current)
112
+ return;
113
+ // 3. 渲染页面
114
+ if (typeof render === "function") {
115
+ let content;
116
+ let loadError;
117
+ let hasError = false;
118
+ try {
119
+ content = yield render(path);
81
120
  }
82
- // 页面加载前钩子
83
- yield (onBefore === null || onBefore === void 0 ? void 0 : onBefore(normalizedPath));
84
- // 加载并显示页面
85
- if (typeof render === "function") {
86
- try {
87
- const pageContent = yield render(normalizedPath);
88
- // 如果返回 null/undefined,视为页面未找到
89
- if (pageContent === null || pageContent === undefined) {
90
- if (typeof notFound === "function") {
91
- setPage(yield notFound(normalizedPath));
92
- }
93
- else {
94
- // 默认 404 页面
95
- setPage((0, jsx_runtime_1.jsxs)("div", { children: ["Not Found: ", normalizedPath] }));
96
- }
97
- return;
98
- }
99
- setPage(pageContent);
100
- }
101
- catch (_a) {
102
- // 动态 import 失败等场景
103
- if (typeof notFound === "function") {
104
- setPage(yield notFound(normalizedPath));
105
- }
106
- else {
107
- setPage((0, jsx_runtime_1.jsxs)("div", { children: ["Not Found: ", normalizedPath] }));
108
- }
121
+ catch (err) {
122
+ loadError = err;
123
+ hasError = true;
124
+ }
125
+ if (navId !== navIdRef.current)
126
+ return;
127
+ if (hasError) {
128
+ // render 抛出异常:优先 onError,降级 notFound,再降级内置提示
129
+ const errNode = typeof onError === "function" ? (yield onError(path, loadError)) : typeof notFound === "function" ? (yield notFound(path)) : ((0, jsx_runtime_1.jsxs)("div", { children: ["Error: ", path] }));
130
+ if (navId !== navIdRef.current)
109
131
  return;
110
- }
132
+ setPage(errNode);
133
+ return;
111
134
  }
112
- // 页面加载后钩子
113
- yield (onAfter === null || onAfter === void 0 ? void 0 : onAfter(normalizedPath));
114
- }),
115
- // 所有外部变量在闭包创建时已捕获,不会变化
116
- // eslint-disable-next-line react-hooks/exhaustive-deps
117
- []);
118
- /**
119
- * 监听路由变化
120
- */
121
- (0, react_1.useEffect)(() => {
122
- // 监听页面变化,一旦变化渲染新页面
123
- const unlisten = exports.history.listen(({ location }) => {
124
- loadAndRenderPage(location.pathname);
125
- });
126
- // 初始化时渲染当前路径对应的页面
127
- loadAndRenderPage(exports.history.location.pathname);
128
- // 卸载时,取消监听
129
- return unlisten;
130
- }, [loadAndRenderPage]);
131
- return (0, jsx_runtime_1.jsx)(Container_1.Container, Object.assign({}, containerProps, { children: page }));
132
- };
133
- // 获取挂载对象
134
- let mount = null;
135
- if (typeof option.target === "string") {
136
- mount = document.querySelector(option.target);
137
- }
138
- else if (option.target instanceof HTMLElement) {
139
- mount = option.target;
140
- }
141
- if (!mount) {
142
- throw new Error(`Mount target not found: ${typeof option.target === "string" ? option.target : "invalid element"}`);
143
- }
144
- const root = (0, client_1.createRoot)(mount);
145
- root.render((0, jsx_runtime_1.jsx)(App, {}));
146
- });
135
+ if (content == null) {
136
+ // render 返回 null/undefined:404
137
+ const notFoundNode = typeof notFound === "function" ? (yield notFound(path)) : ((0, jsx_runtime_1.jsxs)("div", { children: ["Not Found: ", path] }));
138
+ if (navId !== navIdRef.current)
139
+ return;
140
+ setPage(notFoundNode);
141
+ return;
142
+ }
143
+ // 成功:切换前滚回顶部,再替换页面内容
144
+ if (scrollToTop)
145
+ window.scrollTo(0, 0);
146
+ setPage(content);
147
+ }
148
+ if (navId !== navIdRef.current)
149
+ return;
150
+ // 4. 后置钩子(仅成功渲染后调用)
151
+ yield (onAfter === null || onAfter === void 0 ? void 0 : onAfter(path));
152
+ }),
153
+ // 所有依赖均来自 createApp 闭包,生命周期内不变
154
+ // eslint-disable-next-line react-hooks/exhaustive-deps
155
+ []);
156
+ (0, react_1.useEffect)(() => {
157
+ // 初始渲染当前路径
158
+ loadPage(exports.history.location.pathname);
159
+ // 监听后续路由变化,返回 unlisten 作为 cleanup
160
+ return exports.history.listen(({ location }) => loadPage(location.pathname));
161
+ }, [loadPage]);
162
+ return (0, jsx_runtime_1.jsx)(Container_1.Container, Object.assign({}, containerProps, { children: page }));
163
+ };
164
+ // 解析挂载目标
165
+ let mount;
166
+ if (typeof option.target === "string") {
167
+ mount = document.querySelector(option.target);
168
+ }
169
+ else if (option.target instanceof HTMLElement) {
170
+ mount = option.target;
171
+ }
172
+ else {
173
+ mount = null;
174
+ }
175
+ if (!mount) {
176
+ throw new Error(`createApp: mount target not found — "${typeof option.target === "string" ? option.target : "[invalid element]"}"`);
177
+ }
178
+ const root = (0, client_1.createRoot)(mount);
179
+ root.render(option.strict ? ((0, jsx_runtime_1.jsx)(react_1.default.StrictMode, { children: (0, jsx_runtime_1.jsx)(App, {}) })) : ((0, jsx_runtime_1.jsx)(App, {})));
147
180
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clxx",
3
- "version": "3.0.0",
3
+ "version": "3.0.1",
4
4
  "description": "Basic JS library for mobile devices",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.js",