@ossy/router-react 0.1.4 → 0.1.6

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/build/index.js ADDED
@@ -0,0 +1 @@
1
+ import e,{createContext as n,useContext as r,useCallback as a}from"react";import{Router as t}from"@ossy/router";var o=function(){return o=Object.assign||function(e){for(var n,r=1,a=arguments.length;r<a;r++)for(var t in n=arguments[r])Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t]);return e},o.apply(this,arguments)};"function"==typeof SuppressedError&&SuppressedError;var i=n({pages:[],defaultLanguage:void 0,supportedLanguages:[]}),u=function(){return r(i)},d=function(e){return void 0===e&&(e=""),function(e){return"/"===e[e.length-1]?e:"".concat(e,"/")}(function(e){return"/"===e[0]?e:"/".concat(e)}(e))},l=function(n){var r,u,l,c,s,f=n.url,g=n.pages,p=void 0===g?[]:g,v=n.defaultLanguage,w=void 0===v?void 0:v,h=n.supportedLanguages,m=void 0===h?[]:h;if(f){var y=f.match(/([^?#]*)(\?[^#]*)?(#.*)?/);u=f,l=(null==y?void 0:y[1])||"",c=(null==y?void 0:y[3])||"",s=(null==y?void 0:y[2])||""}else{if("undefined"==typeof window)return e.createElement(e.Fragment,null);u=window.location.href,l=window.location.pathname,s=(null==(c=window.location.hash)?void 0:c.includes("?"))?c.split("?")[1]:window.location.search}var L=m.length>1&&!!w,P=l.split("/")[1]||"",S=m.includes(P)?P:w,b=t.of({pages:p,defaultLanguage:w,supportedLanguages:m}),E=b.getParamsFromUrl(u),R=new URLSearchParams(s),k=b.getPageByUrl(u);if(k||(L&&"/"===l&&"undefined"!=typeof window&&(window.location.href="/"+w),k=L?p.find(function(e){return"*"===d(e.path[S])}):p.find(function(e){return"*"===d(e.path)})),!k)return console.warn("[RouterReact] No active page found for",l),e.createElement(e.Fragment,null);a(function(e,n){if("undefined"!=typeof window){window.history.pushState({},"","".concat(l,"?").concat(R.toString()));var r=new URLSearchParams(R);r.set(e,n),history.pushState({},"","?".concat(r.toString()))}},[R]);var U=a(function(e){var n,r,a,t,o,i={};if("string"==typeof e?(n=e,i=E,r=S):(o=e).id||void 0===o.language?(n=(null==e?void 0:e.id)||k.id,i=(null==e?void 0:e.params)||E,r=(null==e?void 0:e.language)||S):(n=k.id,i=E,r=e.language),n.includes("#")){var u=n.split("#");if(n=u[0],(a=u[1]).includes("?")){var d=n.split("?");a=d[0],t=d[1]}}else if(n.includes("?")){var l=n.split("?");n=l[0],t=l[1]}var c=b.getPathname({id:n.replace("@",""),params:i,language:r});return a&&(c=c+"#"+a),t&&(c=c+"?"+t),c},[b,S]),F=a(function(e){if("undefined"!=typeof window&&e)if("@back"!==e){var n=U(e);n&&(window.location.href=n)}else window.history.back()},[U]),O=a(function(){"undefined"!=typeof window&&window.history.back()},[]),j={href:u,pages:p,language:S,defaultLanguage:w,supportedLanguages:m,params:E,searchParams:o({},Array.from(R.entries()).reduce(function(e,n){var r,a=n[0],t=n[1];return o(o({},e),((r={})[a]=t,r))},{})),navigate:F,getHref:U,back:O};(null==k?void 0:k.redirect)&&F({id:k.redirect});var x=(null==k?void 0:k.element)||(null===(r=null==k?void 0:k.render)||void 0===r?void 0:r.call(k));return e.createElement(i.Provider,{value:j},x)};export{l as Router,i as RouterContext,u as useRouter};
@@ -0,0 +1,51 @@
1
+ import React from 'react';
2
+ import { MultiLanguagePage, RouterOptions, SingleLanguagePage } from '@ossy/router';
3
+ export declare const RouterContext: React.Context<{
4
+ pages: RouterPage[];
5
+ defaultLanguage: string | undefined;
6
+ supportedLanguages: string[];
7
+ }>;
8
+ export declare const useRouter: () => {
9
+ pages: RouterPage[];
10
+ defaultLanguage: string | undefined;
11
+ supportedLanguages: string[];
12
+ };
13
+ export declare const Router: <T extends RouterPage>({ url, pages, defaultLanguage, supportedLanguages }: RouterProps<T>) => React.JSX.Element;
14
+ export interface RouterProps<T extends RouterPage> extends RouterOptions<T> {
15
+ /**
16
+ * Render page associated with the given url.
17
+ * Used to render the page on server side where window.location is not available
18
+ * @type string
19
+ * @default undefined
20
+ */
21
+ url?: string;
22
+ }
23
+ export type RouterPage = SingleLanguageRouterPage | MultiLanguageRouterPage;
24
+ export interface SingleLanguageRouterPage extends SingleLanguagePage {
25
+ /** If provided the page will redirect to the given page id
26
+ * @default undefined
27
+ * @type {string}
28
+ * @example { redirect: '@home'}
29
+ */
30
+ redirect?: string;
31
+ element?: React.ReactNode;
32
+ render: () => React.ReactNode;
33
+ }
34
+ export interface MultiLanguageRouterPage extends MultiLanguagePage {
35
+ /** If provided the page will redirect to the given page id
36
+ * @default undefined
37
+ * @type {string}
38
+ * @example { redirect: '@home'}
39
+ */
40
+ redirect?: string;
41
+ element?: React.ReactNode;
42
+ render: () => React.ReactNode;
43
+ }
44
+ export interface GetHrefRequest {
45
+ id?: string;
46
+ language?: string;
47
+ params?: Record<string, string>;
48
+ }
49
+ export interface GetHrefOfActivePageByLanguageRequest {
50
+ language: string;
51
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ossy/router-react",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/ossy-se/packages.git"
@@ -57,5 +57,9 @@
57
57
  "access": "public",
58
58
  "registry": "https://registry.npmjs.org"
59
59
  },
60
- "gitHead": "d5cd2ad89b32cdc9cd31a27ff53b71a9c3226799"
60
+ "files": [
61
+ "/build",
62
+ "README.md"
63
+ ],
64
+ "gitHead": "b13ae79ee733d5934fc4fefa3b50e30a7b566ac9"
61
65
  }
package/CHANGELOG.md DELETED
@@ -1,166 +0,0 @@
1
- # Change Log
2
-
3
- All notable changes to this project will be documented in this file.
4
- See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
-
6
- ## 0.1.4 (2025-10-31)
7
-
8
-
9
- ### Bug Fixes
10
-
11
- * **app:** add @babel/preset-env ([#7](https://github.com/ossy-se/packages/issues/7)) ([252b41a](https://github.com/ossy-se/packages/commit/252b41a6d4e3d7d3750661091c97186b0d9cdde2))
12
-
13
-
14
-
15
-
16
-
17
- ## 0.1.3 (2025-10-31)
18
-
19
- **Note:** Version bump only for package @ossy/router-react
20
-
21
-
22
-
23
-
24
-
25
- ## 0.1.2 (2025-10-31)
26
-
27
- **Note:** Version bump only for package @ossy/router-react
28
-
29
-
30
-
31
-
32
-
33
- ## 0.1.1 (2025-10-31)
34
-
35
- **Note:** Version bump only for package @ossy/router-react
36
-
37
-
38
-
39
-
40
-
41
- # 0.1.0 (2025-10-30)
42
-
43
-
44
- ### Features
45
-
46
- * **sdk:** get current workspace ([#4](https://github.com/ossy-se/packages/issues/4)) ([afce7d5](https://github.com/ossy-se/packages/commit/afce7d5787af42691f62c9eba672ea1be000e19e))
47
-
48
-
49
-
50
-
51
-
52
- ## 0.0.16 (2025-10-30)
53
-
54
- **Note:** Version bump only for package @ossy/router-react
55
-
56
-
57
-
58
-
59
-
60
- ## 0.0.15 (2025-10-27)
61
-
62
- **Note:** Version bump only for package @ossy/router-react
63
-
64
-
65
-
66
-
67
-
68
- ## 0.0.14 (2025-10-27)
69
-
70
- **Note:** Version bump only for package @ossy/router-react
71
-
72
-
73
-
74
-
75
-
76
- ## 0.0.13 (2025-10-27)
77
-
78
- **Note:** Version bump only for package @ossy/router-react
79
-
80
-
81
-
82
-
83
-
84
- ## 0.0.12 (2025-10-27)
85
-
86
- **Note:** Version bump only for package @ossy/router-react
87
-
88
-
89
-
90
-
91
-
92
- ## 0.0.11 (2025-10-27)
93
-
94
- **Note:** Version bump only for package @ossy/router-react
95
-
96
-
97
-
98
-
99
-
100
- ## 0.0.10 (2025-10-25)
101
-
102
- **Note:** Version bump only for package @ossy/router-react
103
-
104
-
105
-
106
-
107
-
108
- ## 0.0.9 (2025-10-25)
109
-
110
- **Note:** Version bump only for package @ossy/router-react
111
-
112
-
113
-
114
-
115
-
116
- ## 0.0.8 (2025-10-25)
117
-
118
- **Note:** Version bump only for package @ossy/router-react
119
-
120
-
121
-
122
-
123
-
124
- ## 0.0.7 (2025-10-25)
125
-
126
- **Note:** Version bump only for package @ossy/router-react
127
-
128
-
129
-
130
-
131
-
132
- ## 0.0.6 (2025-10-25)
133
-
134
- **Note:** Version bump only for package @ossy/router-react
135
-
136
-
137
-
138
-
139
-
140
- ## 0.0.5 (2025-10-25)
141
-
142
- **Note:** Version bump only for package @ossy/router-react
143
-
144
-
145
-
146
-
147
-
148
- ## 0.0.4 (2025-10-25)
149
-
150
- **Note:** Version bump only for package @ossy/router-react
151
-
152
-
153
-
154
-
155
-
156
- ## 0.0.3 (2025-10-25)
157
-
158
- **Note:** Version bump only for package @ossy/router-react
159
-
160
-
161
-
162
-
163
-
164
- ## 0.0.2 (2025-10-25)
165
-
166
- **Note:** Version bump only for package @ossy/router-react
package/rollup.config.js DELETED
@@ -1,34 +0,0 @@
1
- import babel from '@rollup/plugin-babel'
2
- import { nodeResolve as resolveDependencies } from '@rollup/plugin-node-resolve'
3
- import resolveCommonJsDependencies from '@rollup/plugin-commonjs'
4
- import removeOwnPeerDependencies from 'rollup-plugin-peer-deps-external'
5
- import minifyJS from '@rollup/plugin-terser'
6
- import typescript from '@rollup/plugin-typescript'
7
- import preserveDirectives from "rollup-plugin-preserve-directives"
8
-
9
- export default [
10
- {
11
- input: 'src/router-react.tsx',
12
- output: [
13
- {
14
- file: 'build/index.js',
15
- format: 'esm'
16
- }
17
- ],
18
- plugins: [
19
- resolveCommonJsDependencies(),
20
- resolveDependencies(),
21
- removeOwnPeerDependencies(),
22
- babel({
23
- exclude: ['**/node_modules/**/*'],
24
- presets: ['@babel/preset-react']
25
- }),
26
- minifyJS(),
27
- preserveDirectives(),
28
- typescript({
29
- tsconfig: "./tsconfig.json",
30
- outDir: 'build',
31
- }),
32
- ]
33
- },
34
- ]
@@ -1,253 +0,0 @@
1
- 'use client'
2
- import React, { createContext, useContext, useCallback } from 'react'
3
- import { MultiLanguagePage, Router as BaseRouter, RouterOptions, SingleLanguagePage, Page as _Page } from '@ossy/router'
4
-
5
- export const RouterContext = createContext({
6
- pages: [] as RouterPage[],
7
- defaultLanguage: undefined as string | undefined,
8
- supportedLanguages: [] as string[]
9
- })
10
-
11
- export const useRouter = () => useContext(RouterContext)
12
-
13
-
14
- const appendSlash = (string: string) => string[string.length - 1] === '/'
15
- ? string : `${string}/`
16
-
17
- const prependSlash = (string: string) => string[0] === '/'
18
- ? string : `/${string}`
19
-
20
- const padWithSlash = (string = '') => appendSlash(prependSlash(string))
21
-
22
- export const Router = <T extends RouterPage>({
23
- url,
24
- pages = [],
25
- defaultLanguage = undefined,
26
- supportedLanguages = []
27
- }: RouterProps<T> ) => {
28
- let href: string;
29
- let pathname: string;
30
- let hash: string;
31
- let search: string;
32
-
33
- if (url) {
34
- const urlParts = url.match(/([^?#]*)(\?[^#]*)?(#.*)?/);
35
- href = url;
36
- pathname = urlParts?.[1] || '';
37
- hash = urlParts?.[3] || '';
38
- search = urlParts?.[2] || '';
39
- } else if (typeof window !== 'undefined') {
40
- href = window.location.href
41
- pathname = window.location.pathname
42
- hash = window.location.hash
43
- search = hash?.includes('?') ? hash.split('?')[1] : window.location.search
44
- } else {
45
- return <></>
46
- }
47
-
48
- const isMultiLanguage = supportedLanguages.length > 1 && !!defaultLanguage
49
- const potentialLanguage = pathname.split('/')[1] || ''
50
- const language = supportedLanguages.includes(potentialLanguage) ? potentialLanguage : defaultLanguage
51
- const router = BaseRouter.of<T>({ pages, defaultLanguage, supportedLanguages })
52
- const params = router.getParamsFromUrl(href)
53
- const searchParams = new URLSearchParams(search)
54
-
55
- let activePage: T = router.getPageByUrl(href) as T
56
-
57
- if (!activePage) {
58
- if (isMultiLanguage) {
59
- if (pathname === '/') {
60
- if (typeof window !== 'undefined') {
61
- window.location.href = '/' + defaultLanguage
62
- }
63
- }
64
- }
65
-
66
- activePage = isMultiLanguage
67
- ? pages.find(page => padWithSlash((page.path as Record<string, string>)[(language as string)]) === '*') as T
68
- : pages.find(page => padWithSlash(page.path as string) === '*') as T
69
- }
70
-
71
- if (!activePage) {
72
- console.warn('[RouterReact] No active page found for', pathname)
73
- return <></>
74
- }
75
-
76
- /**
77
- * @deprecated router do not support setting client side only search params.
78
- * Use getHref with search params instead
79
- *
80
- * Note: That migh not be true though because we have the back() and navigate() functions....
81
- */
82
- const setSearchParam = useCallback((name: string, value: any) => {
83
- if (typeof window === 'undefined') return
84
- window.history.pushState({}, '', `${pathname}?${searchParams.toString()}`)
85
- const newSearchParams = new URLSearchParams(searchParams)
86
- newSearchParams.set(name, value)
87
- history.pushState({ }, "", `?${newSearchParams.toString()}`)
88
- }, [searchParams])
89
-
90
- /**
91
- * takes either a string id or an object with id, params and language
92
- * - params.id - id of the page to get the href for
93
- * - param.language - language to use for the href, defaults to current language
94
- * - param.params - params to use for the href, defaults to current params
95
- * @param {string|object}
96
- * @returns {string}
97
- */
98
- const getHref = useCallback((getHrefRequest: string | GetHrefRequest | GetHrefOfActivePageByLanguageRequest) => {
99
- // Can be supplied from params, if not will be taken from active page
100
- let _pageId: string;
101
- let _params: Record<string, string> = {}
102
- let _language: string | undefined;
103
-
104
- // Can only be supplied from params, will not be taken from active page
105
- let hash: string | undefined;
106
- let search: string | undefined;
107
-
108
-
109
- if (typeof getHrefRequest === 'string') {
110
- _pageId = getHrefRequest
111
- _params = params
112
- _language = language
113
- } else if (isGetHrefOfActivePageByLanguageRequest(getHrefRequest)) {
114
- _pageId = activePage.id
115
- _params = params
116
- _language = getHrefRequest.language
117
- } else {
118
- _pageId = getHrefRequest?.id || activePage.id
119
- _params = getHrefRequest?.params || params
120
- _language = getHrefRequest?.language || language
121
- }
122
-
123
- if (_pageId.includes('#')) {
124
- const [_id, _hash] = _pageId.split('#')
125
- _pageId = _id
126
- hash = _hash
127
-
128
- if (hash.includes('?')) {
129
- const [_hash, _search] = _pageId.split('?')
130
- hash = _hash
131
- search = _search
132
- }
133
-
134
- } else if (_pageId.includes('?')) {
135
- const [_id, _search] = _pageId.split('?')
136
- _pageId = _id
137
- search = _search
138
- }
139
-
140
- let pathname = router.getPathname({
141
- id: _pageId.replace('@', ''),
142
- params: _params,
143
- language: _language
144
- })
145
-
146
- if (hash) {
147
- pathname = pathname + '#' + hash
148
- }
149
-
150
- if (search) {
151
- pathname = pathname + '?' + search
152
- }
153
-
154
- return pathname
155
- }, [router, language])
156
-
157
- const navigate = useCallback((navigationRequest: string | '@back' | GetHrefRequest | GetHrefOfActivePageByLanguageRequest) => {
158
- if (typeof window === 'undefined') return
159
- if (!navigationRequest) return
160
-
161
- if (navigationRequest === '@back') {
162
- window.history.back()
163
- return
164
- }
165
-
166
- const href = getHref(navigationRequest)
167
- if (!href) return
168
- window.location.href = href
169
-
170
- }, [getHref])
171
-
172
- const back = useCallback(() => {
173
- if (typeof window === 'undefined') return
174
- window.history.back()
175
- }, [])
176
-
177
- const context = {
178
- href,
179
- pages,
180
- language,
181
- defaultLanguage,
182
- supportedLanguages,
183
- params,
184
- searchParams: {
185
- ...Array.from(searchParams.entries()).reduce((all, [key, value]) => ({ ...all, [key]: value }), {}),
186
- // set: setSearchParam
187
- },
188
- navigate,
189
- getHref,
190
- back,
191
- }
192
-
193
- if (activePage?.redirect) {
194
- navigate({ id: activePage.redirect })
195
- }
196
-
197
- const renderedPage = activePage?.element || activePage?.render?.()
198
-
199
- return (
200
- <RouterContext.Provider value={context}>
201
- { renderedPage }
202
- </RouterContext.Provider>
203
- )
204
-
205
- }
206
-
207
- export interface RouterProps<T extends RouterPage> extends RouterOptions<T> {
208
- /**
209
- * Render page associated with the given url.
210
- * Used to render the page on server side where window.location is not available
211
- * @type string
212
- * @default undefined
213
- */
214
- url?: string;
215
- }
216
-
217
- export type RouterPage = SingleLanguageRouterPage | MultiLanguageRouterPage
218
-
219
- export interface SingleLanguageRouterPage extends SingleLanguagePage {
220
- /** If provided the page will redirect to the given page id
221
- * @default undefined
222
- * @type {string}
223
- * @example { redirect: '@home'}
224
- */
225
- redirect?: string;
226
- element?: React.ReactNode;
227
- render: () => React.ReactNode
228
- }
229
-
230
- export interface MultiLanguageRouterPage extends MultiLanguagePage {
231
- /** If provided the page will redirect to the given page id
232
- * @default undefined
233
- * @type {string}
234
- * @example { redirect: '@home'}
235
- */
236
- redirect?: string;
237
- element?: React.ReactNode;
238
- render: () => React.ReactNode
239
- }
240
-
241
- export interface GetHrefRequest {
242
- id?: string;
243
- language?: string;
244
- params?: Record<string, string>;
245
- }
246
-
247
- export interface GetHrefOfActivePageByLanguageRequest {
248
- language: string;
249
- }
250
-
251
- function isGetHrefOfActivePageByLanguageRequest(request: any): request is GetHrefOfActivePageByLanguageRequest {
252
- return !request.id && request.language !== undefined
253
- }
package/tsconfig.json DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es5",
4
- "lib": ["dom", "dom.iterable", "esnext"],
5
- "allowJs": true,
6
- "skipLibCheck": true,
7
- "strict": true,
8
- "forceConsistentCasingInFileNames": true,
9
- "esModuleInterop": true,
10
- "module": "esnext",
11
- "moduleResolution": "node",
12
- "resolveJsonModule": true,
13
- "isolatedModules": true,
14
- "jsx": "react",
15
- "incremental": false,
16
- "declaration": true,
17
- "declarationDir": "./build/types"
18
- },
19
- "exclude": [
20
- "build",
21
- "node_modules",
22
- "src/**/*.test.tsx",
23
- "src/**/*.stories.tsx",
24
- "rollup.config.js",
25
- "src/data.mock.ts"
26
- ]
27
- }