@viewfly/router 0.0.1-alpha.13

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 TanBo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,131 @@
1
+ Viewfly
2
+ ================================
3
+
4
+ Viewfly 是一个简单、数据驱动的前端框架。此项目为 Viewfly 的路由库,可让 Viewfly 支持浏览器路由。
5
+
6
+ ## 安装
7
+
8
+ ```
9
+ npm install @viewfly/router
10
+ ```
11
+
12
+ ## 使用示例
13
+
14
+ ```jsx
15
+ function ListTab1() {
16
+ return () => {
17
+ return (
18
+ <div>listTab1</div>
19
+ )
20
+ }
21
+ }
22
+
23
+ function ListTab2() {
24
+ return () => {
25
+ return (
26
+ <div>listTab2</div>
27
+ )
28
+ }
29
+ }
30
+
31
+ function ListTab3() {
32
+ return () => {
33
+ return (
34
+ <div>listTab3</div>
35
+ )
36
+ }
37
+ }
38
+
39
+ function List() {
40
+ return () => {
41
+ return (
42
+ <div>
43
+ <h3>list</h3>
44
+ <div>
45
+ <Link active="active" to='./tab1'>tab1</Link>
46
+ <Link active="active" to='./tab2'>tab2</Link>
47
+ <Link active="active" to='./tab3'>tab3</Link>
48
+ </div>
49
+ <div>
50
+ <RouterOutlet config={[
51
+ {
52
+ name: 'tab1',
53
+ component: ListTab1
54
+ },
55
+ {
56
+ name: 'tab2',
57
+ component: ListTab2
58
+ },
59
+ {
60
+ name: 'tab3',
61
+ component: ListTab3
62
+ }
63
+ ]}>没找到 Tab</RouterOutlet>
64
+ </div>
65
+ </div>
66
+ )
67
+ }
68
+ }
69
+
70
+ function Detail() {
71
+ return () => {
72
+ return (
73
+ <div>detail</div>
74
+ )
75
+ }
76
+ }
77
+
78
+ function Home() {
79
+ const router = inject(Router)
80
+ return () => {
81
+ return (
82
+ <div>
83
+ <div>home</div>
84
+ <button type="button" onClick={() => {
85
+ router.navigateTo('../list')
86
+ }
87
+ }>跳转到列表
88
+ </button>
89
+ </div>
90
+ )
91
+ }
92
+ }
93
+
94
+ function App() {
95
+ return () => {
96
+ return (
97
+ <div>
98
+ <RootRouter>
99
+ <div>
100
+ <Link active="active" exact to="/">Home</Link>
101
+ <Link active="active" to="/list" queryParams={{ a: 'xx' }}>List</Link>
102
+ <Link active="active" to="/detail">Detail</Link>
103
+ </div>
104
+ <div>
105
+ <RouterOutlet config={[
106
+ {
107
+ name: 'home',
108
+ component: Home
109
+ },
110
+ {
111
+ name: 'list',
112
+ component: Promise.resolve().then(() => List)
113
+ },
114
+ {
115
+ name: 'detail',
116
+ component: Detail
117
+ }
118
+ ]}>
119
+ 未匹配到任何路由
120
+ </RouterOutlet>
121
+ </div>
122
+ </RootRouter>
123
+ </div>
124
+ )
125
+ }
126
+ }
127
+
128
+ createApp(document.getElementById('app')!, <App/>)
129
+ ```
130
+
131
+ 完整文档请参考官方网站:[viewfly.org](https://viewfly.org)
@@ -0,0 +1,320 @@
1
+ import { jsx, Fragment } from '@viewfly/core/jsx-runtime';
2
+ import { Injectable, inject, useSignal, onDestroy, provide } from '@viewfly/core';
3
+ import { Subject, Subscription, fromEvent } from '@tanbo/stream';
4
+
5
+ /******************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+ /* global Reflect, Promise */
20
+
21
+
22
+ function __decorate(decorators, target, key, desc) {
23
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
25
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
26
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
27
+ }
28
+
29
+ function __metadata(metadataKey, metadataValue) {
30
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
31
+ }
32
+
33
+ class Navigator {
34
+ constructor(basePath) {
35
+ this.basePath = basePath;
36
+ }
37
+ }
38
+ function formatUrl(pathname, query) {
39
+ if (query) {
40
+ return pathname + '?' + formatQueryParam(query);
41
+ }
42
+ return pathname;
43
+ }
44
+ function formatQueryParam(queryParam) {
45
+ const map = new Map();
46
+ Object.keys(queryParam).forEach(key => {
47
+ map.set(key, queryParam[key]);
48
+ });
49
+ const params = [];
50
+ map.forEach((value, key) => {
51
+ params.push(`${key}=${String(value)}`);
52
+ });
53
+ return params.join('&');
54
+ }
55
+ let BrowserNavigator = class BrowserNavigator extends Navigator {
56
+ get pathname() {
57
+ return location.pathname;
58
+ }
59
+ constructor(basePath) {
60
+ super(basePath);
61
+ this.urlChangeEvent = new Subject();
62
+ this.subscription = new Subscription();
63
+ this.onUrlChanged = this.urlChangeEvent.asObservable();
64
+ this.subscription.add(fromEvent(window, 'popstate').subscribe(() => {
65
+ this.urlChangeEvent.next();
66
+ }));
67
+ }
68
+ to(pathName, relative, queryParams) {
69
+ const url = this.join(pathName, relative, queryParams);
70
+ if (location.origin + url === location.href) {
71
+ return true;
72
+ }
73
+ history.pushState(null, '', this.basePath + url);
74
+ this.urlChangeEvent.next();
75
+ return true;
76
+ }
77
+ join(pathname, relative, queryParams) {
78
+ var _a;
79
+ let beforePath = relative.beforePath;
80
+ if (pathname.startsWith('/')) {
81
+ return formatUrl(pathname, queryParams);
82
+ }
83
+ while (true) {
84
+ if (pathname.startsWith('./')) {
85
+ pathname = pathname.substring(2);
86
+ continue;
87
+ }
88
+ if (pathname.startsWith('../')) {
89
+ pathname = pathname.substring(3);
90
+ beforePath = ((_a = relative.parent) === null || _a === void 0 ? void 0 : _a.beforePath) || '';
91
+ if (!beforePath) {
92
+ break;
93
+ }
94
+ continue;
95
+ }
96
+ break;
97
+ }
98
+ return formatUrl(beforePath + '/' + pathname, queryParams);
99
+ }
100
+ back() {
101
+ history.back();
102
+ }
103
+ forward() {
104
+ history.forward();
105
+ }
106
+ go(offset) {
107
+ history.go(offset);
108
+ }
109
+ destroy() {
110
+ this.subscription.unsubscribe();
111
+ }
112
+ };
113
+ BrowserNavigator = __decorate([
114
+ Injectable(),
115
+ __metadata("design:paramtypes", [String])
116
+ ], BrowserNavigator);
117
+
118
+ class Router {
119
+ get pathname() {
120
+ var _a;
121
+ if (this.parent) {
122
+ return ((_a = this.parent.path.match(/[^\/?#]+/)) === null || _a === void 0 ? void 0 : _a[0]) || '';
123
+ }
124
+ return '';
125
+ }
126
+ get beforePath() {
127
+ if (this.parent) {
128
+ return this.parent.beforePath + '/' + this.pathname;
129
+ }
130
+ return '';
131
+ }
132
+ constructor(navigator, parent, path) {
133
+ this.navigator = navigator;
134
+ this.parent = parent;
135
+ this.path = path;
136
+ this.refreshEvent = new Subject();
137
+ this.onRefresh = this.refreshEvent.asObservable();
138
+ }
139
+ navigateTo(path, params) {
140
+ this.navigator.to(path, this, params);
141
+ }
142
+ refresh(path) {
143
+ this.path = path;
144
+ this.refreshEvent.next();
145
+ }
146
+ consumeConfig(routes) {
147
+ const routeConfig = this.matchRoute(routes);
148
+ if (!routeConfig) {
149
+ return null;
150
+ }
151
+ let remainingPath = '';
152
+ if (routeConfig.name === '') {
153
+ remainingPath = this.path;
154
+ }
155
+ else if (routeConfig.name === '*') {
156
+ remainingPath = '';
157
+ }
158
+ else {
159
+ remainingPath = this.path.substring(routeConfig.name.length + 1);
160
+ }
161
+ return {
162
+ remainingPath,
163
+ routeConfig
164
+ };
165
+ }
166
+ back() {
167
+ this.navigator.back();
168
+ }
169
+ forward() {
170
+ this.navigator.forward();
171
+ }
172
+ go(offset) {
173
+ this.navigator.go(offset);
174
+ }
175
+ matchRoute(configs) {
176
+ var _a;
177
+ let matchedConfig = null;
178
+ let defaultConfig = null;
179
+ let fallbackConfig = null;
180
+ const pathname = ((_a = (this.path || '').match(/[^\/?#]+/)) === null || _a === void 0 ? void 0 : _a[0]) || '';
181
+ for (const item of configs) {
182
+ if (item.name === pathname) {
183
+ matchedConfig = item;
184
+ break;
185
+ }
186
+ else if (item.name === '*') {
187
+ if (!fallbackConfig) {
188
+ fallbackConfig = item;
189
+ }
190
+ }
191
+ else if (item.name === '') {
192
+ if (!defaultConfig) {
193
+ defaultConfig = item;
194
+ }
195
+ }
196
+ }
197
+ return matchedConfig || defaultConfig || fallbackConfig;
198
+ }
199
+ }
200
+
201
+ function Link(props) {
202
+ const navigator = inject(Navigator);
203
+ const router = inject(Router);
204
+ function getActive() {
205
+ return props.exact ?
206
+ navigator.pathname === navigator.join(props.to, router) :
207
+ navigator.pathname.startsWith(navigator.join(props.to, router));
208
+ }
209
+ const isActive = useSignal(getActive());
210
+ const subscription = navigator.onUrlChanged.subscribe(() => {
211
+ isActive.set(getActive());
212
+ });
213
+ onDestroy(() => {
214
+ subscription.unsubscribe();
215
+ });
216
+ function navigate(ev) {
217
+ ev.preventDefault();
218
+ router.navigateTo(props.to, props.queryParams);
219
+ }
220
+ return () => {
221
+ const Tag = props.tag || 'a';
222
+ const attrs = Object.assign({
223
+ target: '_blank'
224
+ }, props, Object.assign({ onClick: navigate }, props));
225
+ if (Tag === 'a') {
226
+ attrs.href = navigator.join(props.to, router, props.queryParams);
227
+ }
228
+ if (isActive() && props.active) {
229
+ if (!attrs.class) {
230
+ attrs.class = props.active.toString();
231
+ }
232
+ else if (typeof attrs.class === 'string') {
233
+ attrs.class += ' ' + props.active;
234
+ }
235
+ else if (typeof props.active === 'object') {
236
+ attrs.class[props.active] = true;
237
+ }
238
+ else if (Array.isArray(attrs.class)) {
239
+ attrs.class.push(props.active);
240
+ }
241
+ }
242
+ return jsx(Tag, Object.assign({}, attrs, { children: props.children }));
243
+ };
244
+ }
245
+
246
+ function RootRouter(props) {
247
+ const basePath = props.basePath || '';
248
+ const navigator = new BrowserNavigator(basePath);
249
+ function getPath() {
250
+ const pathname = navigator.pathname;
251
+ return pathname.startsWith(basePath) ? pathname.substring(basePath.length) : pathname;
252
+ }
253
+ const router = new Router(navigator, null, getPath());
254
+ provide([
255
+ {
256
+ provide: Navigator,
257
+ useValue: navigator
258
+ },
259
+ {
260
+ provide: Router,
261
+ useValue: router
262
+ }
263
+ ]);
264
+ const subscription = navigator.onUrlChanged.subscribe(() => {
265
+ router.refresh(getPath());
266
+ });
267
+ onDestroy(() => {
268
+ subscription.unsubscribe();
269
+ navigator.destroy();
270
+ });
271
+ return () => {
272
+ return jsx(Fragment, { children: props.children });
273
+ };
274
+ }
275
+
276
+ function RouterOutlet(props) {
277
+ const children = useSignal(null);
278
+ const router = inject(Router);
279
+ const childRouter = new Router(inject(Navigator), router, '');
280
+ provide({
281
+ provide: Router,
282
+ useValue: childRouter
283
+ });
284
+ const subscription = router.onRefresh.subscribe(() => {
285
+ updateChildren();
286
+ });
287
+ onDestroy(() => {
288
+ subscription.unsubscribe();
289
+ });
290
+ let currentComponent = null;
291
+ function updateChildren() {
292
+ const result = router.consumeConfig(props.config);
293
+ if (!result) {
294
+ currentComponent = null;
295
+ children.set(props.children || null);
296
+ return;
297
+ }
298
+ const { routeConfig, remainingPath } = result;
299
+ const matchingRouteComponent = routeConfig.component;
300
+ if (matchingRouteComponent instanceof Promise) {
301
+ matchingRouteComponent.then(result => _updateChildren(result, remainingPath));
302
+ }
303
+ else {
304
+ _updateChildren(matchingRouteComponent, remainingPath);
305
+ }
306
+ }
307
+ function _updateChildren(Component, remainingPath) {
308
+ childRouter.refresh(remainingPath);
309
+ if (Component !== currentComponent) {
310
+ children.set(jsx(Component, {}));
311
+ }
312
+ currentComponent = Component;
313
+ }
314
+ updateChildren();
315
+ return () => {
316
+ return jsx(Fragment, { children: children() });
317
+ };
318
+ }
319
+
320
+ export { BrowserNavigator, Link, Navigator, RootRouter, Router, RouterOutlet, formatQueryParam, formatUrl };
@@ -0,0 +1,328 @@
1
+ 'use strict';
2
+
3
+ var jsxRuntime = require('@viewfly/core/jsx-runtime');
4
+ var core = require('@viewfly/core');
5
+ var stream = require('@tanbo/stream');
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+ /* global Reflect, Promise */
22
+
23
+
24
+ function __decorate(decorators, target, key, desc) {
25
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
26
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
27
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
28
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
29
+ }
30
+
31
+ function __metadata(metadataKey, metadataValue) {
32
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
33
+ }
34
+
35
+ class Navigator {
36
+ constructor(basePath) {
37
+ this.basePath = basePath;
38
+ }
39
+ }
40
+ function formatUrl(pathname, query) {
41
+ if (query) {
42
+ return pathname + '?' + formatQueryParam(query);
43
+ }
44
+ return pathname;
45
+ }
46
+ function formatQueryParam(queryParam) {
47
+ const map = new Map();
48
+ Object.keys(queryParam).forEach(key => {
49
+ map.set(key, queryParam[key]);
50
+ });
51
+ const params = [];
52
+ map.forEach((value, key) => {
53
+ params.push(`${key}=${String(value)}`);
54
+ });
55
+ return params.join('&');
56
+ }
57
+ exports.BrowserNavigator = class BrowserNavigator extends Navigator {
58
+ get pathname() {
59
+ return location.pathname;
60
+ }
61
+ constructor(basePath) {
62
+ super(basePath);
63
+ this.urlChangeEvent = new stream.Subject();
64
+ this.subscription = new stream.Subscription();
65
+ this.onUrlChanged = this.urlChangeEvent.asObservable();
66
+ this.subscription.add(stream.fromEvent(window, 'popstate').subscribe(() => {
67
+ this.urlChangeEvent.next();
68
+ }));
69
+ }
70
+ to(pathName, relative, queryParams) {
71
+ const url = this.join(pathName, relative, queryParams);
72
+ if (location.origin + url === location.href) {
73
+ return true;
74
+ }
75
+ history.pushState(null, '', this.basePath + url);
76
+ this.urlChangeEvent.next();
77
+ return true;
78
+ }
79
+ join(pathname, relative, queryParams) {
80
+ var _a;
81
+ let beforePath = relative.beforePath;
82
+ if (pathname.startsWith('/')) {
83
+ return formatUrl(pathname, queryParams);
84
+ }
85
+ while (true) {
86
+ if (pathname.startsWith('./')) {
87
+ pathname = pathname.substring(2);
88
+ continue;
89
+ }
90
+ if (pathname.startsWith('../')) {
91
+ pathname = pathname.substring(3);
92
+ beforePath = ((_a = relative.parent) === null || _a === void 0 ? void 0 : _a.beforePath) || '';
93
+ if (!beforePath) {
94
+ break;
95
+ }
96
+ continue;
97
+ }
98
+ break;
99
+ }
100
+ return formatUrl(beforePath + '/' + pathname, queryParams);
101
+ }
102
+ back() {
103
+ history.back();
104
+ }
105
+ forward() {
106
+ history.forward();
107
+ }
108
+ go(offset) {
109
+ history.go(offset);
110
+ }
111
+ destroy() {
112
+ this.subscription.unsubscribe();
113
+ }
114
+ };
115
+ exports.BrowserNavigator = __decorate([
116
+ core.Injectable(),
117
+ __metadata("design:paramtypes", [String])
118
+ ], exports.BrowserNavigator);
119
+
120
+ class Router {
121
+ get pathname() {
122
+ var _a;
123
+ if (this.parent) {
124
+ return ((_a = this.parent.path.match(/[^\/?#]+/)) === null || _a === void 0 ? void 0 : _a[0]) || '';
125
+ }
126
+ return '';
127
+ }
128
+ get beforePath() {
129
+ if (this.parent) {
130
+ return this.parent.beforePath + '/' + this.pathname;
131
+ }
132
+ return '';
133
+ }
134
+ constructor(navigator, parent, path) {
135
+ this.navigator = navigator;
136
+ this.parent = parent;
137
+ this.path = path;
138
+ this.refreshEvent = new stream.Subject();
139
+ this.onRefresh = this.refreshEvent.asObservable();
140
+ }
141
+ navigateTo(path, params) {
142
+ this.navigator.to(path, this, params);
143
+ }
144
+ refresh(path) {
145
+ this.path = path;
146
+ this.refreshEvent.next();
147
+ }
148
+ consumeConfig(routes) {
149
+ const routeConfig = this.matchRoute(routes);
150
+ if (!routeConfig) {
151
+ return null;
152
+ }
153
+ let remainingPath = '';
154
+ if (routeConfig.name === '') {
155
+ remainingPath = this.path;
156
+ }
157
+ else if (routeConfig.name === '*') {
158
+ remainingPath = '';
159
+ }
160
+ else {
161
+ remainingPath = this.path.substring(routeConfig.name.length + 1);
162
+ }
163
+ return {
164
+ remainingPath,
165
+ routeConfig
166
+ };
167
+ }
168
+ back() {
169
+ this.navigator.back();
170
+ }
171
+ forward() {
172
+ this.navigator.forward();
173
+ }
174
+ go(offset) {
175
+ this.navigator.go(offset);
176
+ }
177
+ matchRoute(configs) {
178
+ var _a;
179
+ let matchedConfig = null;
180
+ let defaultConfig = null;
181
+ let fallbackConfig = null;
182
+ const pathname = ((_a = (this.path || '').match(/[^\/?#]+/)) === null || _a === void 0 ? void 0 : _a[0]) || '';
183
+ for (const item of configs) {
184
+ if (item.name === pathname) {
185
+ matchedConfig = item;
186
+ break;
187
+ }
188
+ else if (item.name === '*') {
189
+ if (!fallbackConfig) {
190
+ fallbackConfig = item;
191
+ }
192
+ }
193
+ else if (item.name === '') {
194
+ if (!defaultConfig) {
195
+ defaultConfig = item;
196
+ }
197
+ }
198
+ }
199
+ return matchedConfig || defaultConfig || fallbackConfig;
200
+ }
201
+ }
202
+
203
+ function Link(props) {
204
+ const navigator = core.inject(Navigator);
205
+ const router = core.inject(Router);
206
+ function getActive() {
207
+ return props.exact ?
208
+ navigator.pathname === navigator.join(props.to, router) :
209
+ navigator.pathname.startsWith(navigator.join(props.to, router));
210
+ }
211
+ const isActive = core.useSignal(getActive());
212
+ const subscription = navigator.onUrlChanged.subscribe(() => {
213
+ isActive.set(getActive());
214
+ });
215
+ core.onDestroy(() => {
216
+ subscription.unsubscribe();
217
+ });
218
+ function navigate(ev) {
219
+ ev.preventDefault();
220
+ router.navigateTo(props.to, props.queryParams);
221
+ }
222
+ return () => {
223
+ const Tag = props.tag || 'a';
224
+ const attrs = Object.assign({
225
+ target: '_blank'
226
+ }, props, Object.assign({ onClick: navigate }, props));
227
+ if (Tag === 'a') {
228
+ attrs.href = navigator.join(props.to, router, props.queryParams);
229
+ }
230
+ if (isActive() && props.active) {
231
+ if (!attrs.class) {
232
+ attrs.class = props.active.toString();
233
+ }
234
+ else if (typeof attrs.class === 'string') {
235
+ attrs.class += ' ' + props.active;
236
+ }
237
+ else if (typeof props.active === 'object') {
238
+ attrs.class[props.active] = true;
239
+ }
240
+ else if (Array.isArray(attrs.class)) {
241
+ attrs.class.push(props.active);
242
+ }
243
+ }
244
+ return jsxRuntime.jsx(Tag, Object.assign({}, attrs, { children: props.children }));
245
+ };
246
+ }
247
+
248
+ function RootRouter(props) {
249
+ const basePath = props.basePath || '';
250
+ const navigator = new exports.BrowserNavigator(basePath);
251
+ function getPath() {
252
+ const pathname = navigator.pathname;
253
+ return pathname.startsWith(basePath) ? pathname.substring(basePath.length) : pathname;
254
+ }
255
+ const router = new Router(navigator, null, getPath());
256
+ core.provide([
257
+ {
258
+ provide: Navigator,
259
+ useValue: navigator
260
+ },
261
+ {
262
+ provide: Router,
263
+ useValue: router
264
+ }
265
+ ]);
266
+ const subscription = navigator.onUrlChanged.subscribe(() => {
267
+ router.refresh(getPath());
268
+ });
269
+ core.onDestroy(() => {
270
+ subscription.unsubscribe();
271
+ navigator.destroy();
272
+ });
273
+ return () => {
274
+ return jsxRuntime.jsx(jsxRuntime.Fragment, { children: props.children });
275
+ };
276
+ }
277
+
278
+ function RouterOutlet(props) {
279
+ const children = core.useSignal(null);
280
+ const router = core.inject(Router);
281
+ const childRouter = new Router(core.inject(Navigator), router, '');
282
+ core.provide({
283
+ provide: Router,
284
+ useValue: childRouter
285
+ });
286
+ const subscription = router.onRefresh.subscribe(() => {
287
+ updateChildren();
288
+ });
289
+ core.onDestroy(() => {
290
+ subscription.unsubscribe();
291
+ });
292
+ let currentComponent = null;
293
+ function updateChildren() {
294
+ const result = router.consumeConfig(props.config);
295
+ if (!result) {
296
+ currentComponent = null;
297
+ children.set(props.children || null);
298
+ return;
299
+ }
300
+ const { routeConfig, remainingPath } = result;
301
+ const matchingRouteComponent = routeConfig.component;
302
+ if (matchingRouteComponent instanceof Promise) {
303
+ matchingRouteComponent.then(result => _updateChildren(result, remainingPath));
304
+ }
305
+ else {
306
+ _updateChildren(matchingRouteComponent, remainingPath);
307
+ }
308
+ }
309
+ function _updateChildren(Component, remainingPath) {
310
+ childRouter.refresh(remainingPath);
311
+ if (Component !== currentComponent) {
312
+ children.set(jsxRuntime.jsx(Component, {}));
313
+ }
314
+ currentComponent = Component;
315
+ }
316
+ updateChildren();
317
+ return () => {
318
+ return jsxRuntime.jsx(jsxRuntime.Fragment, { children: children() });
319
+ };
320
+ }
321
+
322
+ exports.Link = Link;
323
+ exports.Navigator = Navigator;
324
+ exports.RootRouter = RootRouter;
325
+ exports.Router = Router;
326
+ exports.RouterOutlet = RouterOutlet;
327
+ exports.formatQueryParam = formatQueryParam;
328
+ exports.formatUrl = formatUrl;
@@ -0,0 +1,10 @@
1
+ import { Props } from '@viewfly/core';
2
+ import { QueryParams } from './providers/_api';
3
+ export interface LinkProps extends Props {
4
+ to: string;
5
+ active?: string;
6
+ exact?: boolean;
7
+ queryParams?: QueryParams;
8
+ tag?: string;
9
+ }
10
+ export declare function Link(props: LinkProps): () => any;
@@ -0,0 +1,2 @@
1
+ export * from './navigator';
2
+ export * from './router';
@@ -0,0 +1,33 @@
1
+ import { Observable } from '@tanbo/stream';
2
+ import { Router } from './router';
3
+ export interface QueryParams {
4
+ [key: string]: string | string[];
5
+ }
6
+ export declare abstract class Navigator {
7
+ basePath: string;
8
+ protected constructor(basePath: string);
9
+ abstract onUrlChanged: Observable<void>;
10
+ abstract get pathname(): string;
11
+ abstract to(pathName: string, relative: Router, queryParams?: QueryParams): boolean;
12
+ abstract join(pathName: string, relative: Router, queryParams?: QueryParams): string;
13
+ abstract back(): void;
14
+ abstract forward(): void;
15
+ abstract go(offset: number): void;
16
+ abstract destroy(): void;
17
+ }
18
+ export type QueryParam = Record<string, string | boolean | number>;
19
+ export declare function formatUrl(pathname: string, query?: QueryParams): string;
20
+ export declare function formatQueryParam(queryParam: QueryParams): string;
21
+ export declare class BrowserNavigator extends Navigator {
22
+ onUrlChanged: Observable<void>;
23
+ get pathname(): string;
24
+ private urlChangeEvent;
25
+ private subscription;
26
+ constructor(basePath: string);
27
+ to(pathName: string, relative: Router, queryParams?: QueryParams): boolean;
28
+ join(pathname: string, relative: Router, queryParams?: QueryParams): string;
29
+ back(): void;
30
+ forward(): void;
31
+ go(offset: number): void;
32
+ destroy(): void;
33
+ }
@@ -0,0 +1,28 @@
1
+ import { ComponentSetup } from '@viewfly/core';
2
+ import { Observable } from '@tanbo/stream';
3
+ import { Navigator, QueryParams } from './navigator';
4
+ export interface RouteConfig {
5
+ name: string;
6
+ component: ComponentSetup | Promise<ComponentSetup>;
7
+ beforeEach?(): boolean | Promise<boolean>;
8
+ }
9
+ export declare class Router {
10
+ private navigator;
11
+ parent: Router | null;
12
+ path: string;
13
+ onRefresh: Observable<void>;
14
+ get pathname(): string;
15
+ get beforePath(): string;
16
+ private refreshEvent;
17
+ constructor(navigator: Navigator, parent: Router | null, path: string);
18
+ navigateTo(path: string, params?: QueryParams): void;
19
+ refresh(path: string): void;
20
+ consumeConfig(routes: RouteConfig[]): {
21
+ remainingPath: string;
22
+ routeConfig: RouteConfig;
23
+ } | null;
24
+ back(): void;
25
+ forward(): void;
26
+ go(offset: number): void;
27
+ private matchRoute;
28
+ }
@@ -0,0 +1,4 @@
1
+ export * from './link';
2
+ export * from './root-router';
3
+ export * from './router-outlet';
4
+ export * from './providers/_api';
@@ -0,0 +1,6 @@
1
+ import { JSXChildNode, Props } from '@viewfly/core';
2
+ export interface RootRouterProps extends Props {
3
+ basePath?: string;
4
+ children?: JSXChildNode;
5
+ }
6
+ export declare function RootRouter(props: RootRouterProps): () => any;
@@ -0,0 +1,6 @@
1
+ import { Props } from '@viewfly/core';
2
+ import { RouteConfig } from './providers/_api';
3
+ export interface RouterOutletProps extends Props {
4
+ config: RouteConfig[];
5
+ }
6
+ export declare function RouterOutlet(props: RouterOutletProps): () => any;
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@viewfly/router",
3
+ "version": "0.0.1-alpha.13",
4
+ "description": "A routing library based on the Viewfly framework that can be run in the browser or Nodejs background.",
5
+ "main": "./bundles/index.js",
6
+ "module": "./bundles/index.esm.js",
7
+ "typings": "./bundles/public-api.d.ts",
8
+ "scripts": {
9
+ "build:lib": "rimraf bundles && rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript",
10
+ "publish:lib": "npm run build:lib && npm publish --access=public"
11
+ },
12
+ "license": "MIT",
13
+ "keywords": [],
14
+ "dependencies": {
15
+ "@tanbo/stream": "^1.1.9",
16
+ "@viewfly/core": "^0.0.1-alpha.13",
17
+ "url": "^0.11.1"
18
+ },
19
+ "devDependencies": {
20
+ "@rollup/plugin-commonjs": "^23.0.2",
21
+ "@rollup/plugin-typescript": "^9.0.2",
22
+ "rimraf": "^3.0.2",
23
+ "rollup": "^3.2.5",
24
+ "tslib": "^2.4.1"
25
+ },
26
+ "author": {
27
+ "name": "Tanbo",
28
+ "email": "tanbohb@qq.com"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/viewfly/viewfly.git"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/viewfly/viewfly.git/issues"
36
+ }
37
+ }