├── .editorconfig ├── .eslintignore ├── .eslintrc.json ├── .github ├── karma-problem-matcher.json └── workflows │ ├── preview.yml │ └── workflow.yml ├── .gitignore ├── .husky ├── .gitignore └── commit-msg ├── .prettierrc ├── .storybook └── main.js ├── .vscode └── settings.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── CREDITS.md ├── LICENSE ├── README.md ├── commitlint.config.mjs ├── package-lock.json ├── package.json ├── src ├── index.ts ├── load.ts ├── match.ts ├── router.ts ├── use-hash-param.ts ├── use-route-events.ts ├── use-router.ts └── use-routes.ts ├── stories ├── .eslintrc.json ├── cosmoz-router.stories.js └── views │ ├── .eslintrc.json │ ├── home.js │ ├── param-reading-view.js │ ├── view-1.js │ ├── view-2.js │ └── view-3.js ├── test └── basic.test.ts ├── tsconfig.build.json ├── tsconfig.json ├── web-dev-server.config.mjs └── web-test-runner.config.mjs /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | indent_style = tab 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.yml] 13 | indent_style = space 14 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /coverage/ 2 | /dist/ 3 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/@neovici/cfg/eslint", 3 | "globals": { 4 | "Cosmoz": "readonly" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.github/karma-problem-matcher.json: -------------------------------------------------------------------------------- 1 | { 2 | "problemMatcher": [{ 3 | "owner": "karma-eval", 4 | "pattern": [{ 5 | "regexp": "^\\w+\\s\\d+\\.\\d+\\.\\d+\\s\\(\\w+\\s\\d+\\.\\d+\\.\\d+\\)\\sERROR$" 6 | }, { 7 | "regexp": "^\\s{2}(.*)$", 8 | "message": 1 9 | }, { 10 | "regexp": "^\\s{2}at\\s([^:]*):(\\d+):(\\d+)$", 11 | "file": 1, 12 | "line": 2, 13 | "column": 3 14 | }] 15 | }, { 16 | "owner": "karma-test-error", 17 | "pattern": [{ 18 | "regexp": "^\\w+\\s\\d+\\.\\d+\\.\\d+\\s\\(\\w+\\s\\d+\\.\\d+\\.\\d+\\)\\s(.*)FAILED$", 19 | "code": 1 20 | }, { 21 | "regexp": "^\\t(.*)$", 22 | "message": 1 23 | }, { 24 | "regexp": "^\\t {4}at\\s[^\\s]*\\s\\(([^:]*):(\\d+):(\\d+)\\)$", 25 | "file": 1, 26 | "line": 2, 27 | "column": 3 28 | }] 29 | }] 30 | } -------------------------------------------------------------------------------- /.github/workflows/preview.yml: -------------------------------------------------------------------------------- 1 | name: Deploy PR previews 2 | concurrency: preview-${{ github.ref }} 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - reopened 8 | - synchronize 9 | - closed 10 | permissions: 11 | contents: write 12 | pull-requests: write 13 | jobs: 14 | storybook: 15 | uses: Neovici/cfg/.github/workflows/preview.yml@master 16 | secrets: inherit 17 | -------------------------------------------------------------------------------- /.github/workflows/workflow.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Github CI 3 | 4 | on: 5 | pull_request: 6 | branches: 7 | - master 8 | - beta 9 | push: 10 | branches: 11 | - master 12 | - beta 13 | 14 | jobs: 15 | build: 16 | uses: Neovici/cfg/.github/workflows/forge.yml@master 17 | secrets: inherit 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | dist/ 4 | debug.log 5 | yarn-error.log 6 | .eslintcache 7 | .DS_Store 8 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | npx --no-install commitlint --edit $1 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | "@neovici/cfg/prettier" 2 | -------------------------------------------------------------------------------- /.storybook/main.js: -------------------------------------------------------------------------------- 1 | import esbuild from 'rollup-plugin-esbuild'; 2 | 3 | /** @type { import('@web/storybook-framework-web-components').StorybookConfig } */ 4 | const config = { 5 | stories: ['../stories/**/*.stories.{js,ts,mdx}'], 6 | addons: ['@storybook/addon-essentials', '@storybook/addon-links'], 7 | framework: { 8 | name: '@web/storybook-framework-web-components', 9 | }, 10 | /* Try to make the build parse TS files */ 11 | async rollupFinal(config) { 12 | // add extra configuration for rollup 13 | // e.g. a new plugin 14 | config.plugins.push(esbuild({})); 15 | 16 | return config; 17 | }, 18 | }; 19 | 20 | export default config; 21 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "eslint.validate": [ "javascript" ], 3 | "editor.codeActionsOnSave": { 4 | "source.fixAll.eslint": true 5 | } 6 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [11.2.2](https://github.com/neovici/cosmoz-router/compare/v11.2.1...v11.2.2) (2025-03-25) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * commitlint ([4a0a9c5](https://github.com/neovici/cosmoz-router/commit/4a0a9c552bbfc4396964ca268b7f290933c808c9)) 7 | 8 | ## [11.2.1](https://github.com/neovici/cosmoz-router/compare/v11.2.0...v11.2.1) (2025-03-25) 9 | 10 | 11 | ### Bug Fixes 12 | 13 | * config commitlint and update ([49b8218](https://github.com/neovici/cosmoz-router/commit/49b821815f4de9dbe9833441d6ad4a35e4e7ff52)) 14 | 15 | ## [11.2.0](https://github.com/neovici/cosmoz-router/compare/v11.1.0...v11.2.0) (2024-01-11) 16 | 17 | 18 | ### Features 19 | 20 | * update exported type def ([158ce6d](https://github.com/neovici/cosmoz-router/commit/158ce6de49e88c7a96df72c5aad2d4b7ca3a8550)) 21 | 22 | ## [11.1.0](https://github.com/neovici/cosmoz-router/compare/v11.0.0...v11.1.0) (2024-01-11) 23 | 24 | 25 | ### Features 26 | 27 | * **router:** adjust exported type ([8c4d472](https://github.com/neovici/cosmoz-router/commit/8c4d472c14b0cd2323581d7d289baec7f5c45500)) 28 | 29 | ## [11.0.0](https://github.com/neovici/cosmoz-router/compare/v10.8.0...v11.0.0) (2024-01-11) 30 | 31 | 32 | ### ⚠ BREAKING CHANGES 33 | 34 | * Upgrade to @pionjs/pion 35 | 36 | ### Features 37 | 38 | * update to pion ([a9b4e40](https://github.com/neovici/cosmoz-router/commit/a9b4e400ad479c4e85dc35a4e54b72d23c4543f5)) 39 | 40 | ## [10.8.0](https://github.com/neovici/cosmoz-router/compare/v10.7.0...v10.8.0) (2023-12-21) 41 | 42 | 43 | ### Features 44 | 45 | * **router:** improve type def ([99f76ed](https://github.com/neovici/cosmoz-router/commit/99f76ed09aa2401a481d97b058b75526dfe83162)) 46 | 47 | ## [10.7.0](https://github.com/neovici/cosmoz-router/compare/v10.6.0...v10.7.0) (2023-11-06) 48 | 49 | 50 | ### Features 51 | 52 | * **use-hash-param:** adjust return type ([c62226e](https://github.com/neovici/cosmoz-router/commit/c62226e1ccabb4d225f8185c6d6e37a1463ce1ab)) 53 | 54 | ## [10.6.0](https://github.com/neovici/cosmoz-router/compare/v10.5.0...v10.6.0) (2023-11-02) 55 | 56 | 57 | ### Features 58 | 59 | * update deps & workflow ([f709386](https://github.com/neovici/cosmoz-router/commit/f70938655e6500075f5c41ef3dab5925a07d585d)) 60 | 61 | ## [10.5.0](https://github.com/neovici/cosmoz-router/compare/v10.4.0...v10.5.0) (2023-01-19) 62 | 63 | 64 | ### Features 65 | 66 | * **load:** set route property on matched elemetn ([6b92649](https://github.com/neovici/cosmoz-router/commit/6b926491db59961ecee7273be38a5d3ea33bad60)) 67 | 68 | ## [10.4.0](https://github.com/neovici/cosmoz-router/compare/v10.3.0...v10.4.0) (2022-10-18) 69 | 70 | 71 | ### Features 72 | 73 | * add dynamic import load helper ([d111dfb](https://github.com/neovici/cosmoz-router/commit/d111dfb91dba9fd5c7fb729ae3573920b8cb52a8)) 74 | * add test ([bc84e69](https://github.com/neovici/cosmoz-router/commit/bc84e696dcc9819379a9a8c8c18a11332176dde9)) 75 | 76 | 77 | ### Bug Fixes 78 | 79 | * template error createElement ([8911ebd](https://github.com/neovici/cosmoz-router/commit/8911ebd50cc457ef4adc801e259c20a9ec81f1da)) 80 | 81 | ## [10.3.0](https://github.com/neovici/cosmoz-router/compare/v10.2.0...v10.3.0) (2022-10-18) 82 | 83 | 84 | ### Features 85 | 86 | * **match:** access original route object ([7b85ec5](https://github.com/neovici/cosmoz-router/commit/7b85ec5a6bb1fdd3f5e9cb759d446530b2141f39)) 87 | 88 | ## [10.2.0](https://github.com/neovici/cosmoz-router/compare/v10.1.0...v10.2.0) (2022-10-18) 89 | 90 | 91 | ### Features 92 | 93 | * **use-router:** adjust Route handle type def ([4dfc6d1](https://github.com/neovici/cosmoz-router/commit/4dfc6d1d227e878bec3f5588186005221c0d9cb6)) 94 | 95 | ## [10.1.0](https://github.com/neovici/cosmoz-router/compare/v10.0.1...v10.1.0) (2022-10-18) 96 | 97 | 98 | ### Features 99 | 100 | * add use-router ([78fd1ae](https://github.com/neovici/cosmoz-router/commit/78fd1ae496aeda4fc0d84b29fac34ce338f07ec0)) 101 | 102 | ## [10.0.1](https://github.com/neovici/cosmoz-router/compare/v10.0.0...v10.0.1) (2022-09-21) 103 | 104 | 105 | ### Bug Fixes 106 | 107 | * **use-route-events:** handle non promise ([335f4a2](https://github.com/neovici/cosmoz-router/commit/335f4a293facc5c0239710a810baa8e5ea0cc0aa)) 108 | 109 | ## [10.0.0](https://github.com/neovici/cosmoz-router/compare/v9.0.0...v10.0.0) (2022-07-18) 110 | 111 | 112 | ### ⚠ BREAKING CHANGES 113 | 114 | * rename module and repo 115 | 116 | ### Features 117 | 118 | * rename ([81d403a](https://github.com/neovici/cosmoz-router/commit/81d403a4fc1a242d76fb6b3986cc4670449bcfa4)) 119 | 120 | ## [9.0.0](https://github.com/neovici/cosmoz-page-router/compare/v8.1.2...v9.0.0) (2022-06-21) 121 | 122 | 123 | ### ⚠ BREAKING CHANGES 124 | 125 | * **lit:** upgrade to haunted 5 & lit 2 126 | 127 | ### Features 128 | 129 | * **ci:** exports dist folder ([d5489c2](https://github.com/neovici/cosmoz-page-router/commit/d5489c27f67a19f3e754c159f9b75950e75f21ca)) 130 | * init typescript ([8a677b8](https://github.com/neovici/cosmoz-page-router/commit/8a677b8d93f00b3a2ba0b7c731721fee20ba1831)) 131 | * **lit:** upgrade to haunted 5 & lit 2 ([0169365](https://github.com/neovici/cosmoz-page-router/commit/0169365bb61392ef376500d707184eebf72d609b)) 132 | * typescript init ([25fbfba](https://github.com/neovici/cosmoz-page-router/commit/25fbfbac9b43c855613f33bc1f5625323f9cf7b3)) 133 | * **typescript:** convert tests to typescript ([5eab3e9](https://github.com/neovici/cosmoz-page-router/commit/5eab3e9aeb41bcb821fc9890afcfec5ee951c48d)) 134 | 135 | 136 | ### Bug Fixes 137 | 138 | * adjust exports map ([d9ff93f](https://github.com/neovici/cosmoz-page-router/commit/d9ff93fef25d18089c783aaa3a3b3401004ab4f8)) 139 | * **deps:** update ([9ec8374](https://github.com/neovici/cosmoz-page-router/commit/9ec8374ceee8819e2ef1960eb1d764369f802fed)) 140 | * **deps:** update ([2418f49](https://github.com/neovici/cosmoz-page-router/commit/2418f4997f7d816ceabce04062e9cf2e405bb5ea)) 141 | * import paths ([896a9f0](https://github.com/neovici/cosmoz-page-router/commit/896a9f07f4ce20d9431091681b87e50e5c559f59)) 142 | 143 | ## [9.0.0-beta.3](https://github.com/neovici/cosmoz-page-router/compare/v9.0.0-beta.2...v9.0.0-beta.3) (2022-06-16) 144 | 145 | 146 | ### Bug Fixes 147 | 148 | * adjust exports map ([36009db](https://github.com/neovici/cosmoz-page-router/commit/36009db62d9c432fc4cd0c8e4017c8737f7fddde)) 149 | 150 | ## [9.0.0-beta.2](https://github.com/neovici/cosmoz-page-router/compare/v9.0.0-beta.1...v9.0.0-beta.2) (2022-06-16) 151 | 152 | 153 | ### Bug Fixes 154 | 155 | * **deps:** update ([3e75753](https://github.com/neovici/cosmoz-page-router/commit/3e75753ee53324a4809065b07593e4c731bf0b58)) 156 | 157 | ## [9.0.0-beta.1](https://github.com/neovici/cosmoz-page-router/compare/v8.1.2...v9.0.0-beta.1) (2022-06-02) 158 | 159 | 160 | ### ⚠ BREAKING CHANGES 161 | 162 | * **lit:** upgrade to haunted 5 & lit 2 163 | 164 | ### Features 165 | 166 | * **ci:** exports dist folder ([e27fc18](https://github.com/neovici/cosmoz-page-router/commit/e27fc187fe5f07efd9d8d4683ff7d8c654538c55)) 167 | * init typescript ([7cb5c1c](https://github.com/neovici/cosmoz-page-router/commit/7cb5c1cd679986ce2014ec0d0eef9757982283c8)) 168 | * **lit:** upgrade to haunted 5 & lit 2 ([9f87bd6](https://github.com/neovici/cosmoz-page-router/commit/9f87bd6abe7f662ccbb6ddad6630695e461662a4)) 169 | * typescript init ([84100e6](https://github.com/neovici/cosmoz-page-router/commit/84100e62c6adfa2acc9b538f3416a94f63c03208)) 170 | * **typescript:** convert tests to typescript ([915a415](https://github.com/neovici/cosmoz-page-router/commit/915a4152c276ecc59b6c2375e4c45f6efba129b9)) 171 | 172 | 173 | ### Bug Fixes 174 | 175 | * import paths ([a525324](https://github.com/neovici/cosmoz-page-router/commit/a525324c35a8bc371bd145e76273ec71970d4377)) 176 | 177 | ### [8.1.2](https://github.com/neovici/cosmoz-page-router/compare/v8.1.1...v8.1.2) (2022-05-20) 178 | 179 | 180 | ### Bug Fixes 181 | 182 | * **use-hash-param:** setState only when changed ([d8e1d5a](https://github.com/neovici/cosmoz-page-router/commit/d8e1d5a5ca35f576080c5aeaf9f2dbd0adabd968)) 183 | 184 | ### [8.1.1](https://github.com/neovici/cosmoz-page-router/compare/v8.1.0...v8.1.1) (2022-05-19) 185 | 186 | 187 | ### Bug Fixes 188 | 189 | * **use-hash-param:** fix wrong url in setter ([8e192d9](https://github.com/neovici/cosmoz-page-router/commit/8e192d9c8e56ebaa57b4d5598447926c74641048)) 190 | 191 | ## [8.1.0](https://github.com/neovici/cosmoz-page-router/compare/v8.0.0...v8.1.0) (2022-05-19) 192 | 193 | 194 | ### Features 195 | 196 | * update deps ([40d99e8](https://github.com/neovici/cosmoz-page-router/commit/40d99e8ac9b820d8eb03b8fee06ba8f5f514b924)) 197 | 198 | ## [8.0.0](https://github.com/neovici/cosmoz-page-router/compare/v7.0.0...v8.0.0) (2022-05-18) 199 | 200 | 201 | ### ⚠ BREAKING CHANGES 202 | 203 | * **hash-param:** add setter support 204 | 205 | ### Features 206 | 207 | * **hash-param:** add setter support ([2244cd6](https://github.com/neovici/cosmoz-page-router/commit/2244cd65bda8f8f01f7e91afd8bad80961ea565d)) 208 | 209 | ## [7.0.0](https://github.com/neovici/cosmoz-page-router/compare/v6.0.6...v7.0.0) (2022-03-01) 210 | 211 | 212 | ### ⚠ BREAKING CHANGES 213 | 214 | * remove deprecated cosmoz-page-location 215 | 216 | ### Features 217 | 218 | * drop cosmoz-page-location ([462ec49](https://github.com/neovici/cosmoz-page-router/commit/462ec49f19ee84807f4d2d158f422d30c1af2496)) 219 | * **use-hash-param:** implement ([4026c08](https://github.com/neovici/cosmoz-page-router/commit/4026c0817fc410a62a120d1697f5fb7527105635)) 220 | 221 | 222 | ### Bug Fixes 223 | 224 | * lint ([8e34243](https://github.com/neovici/cosmoz-page-router/commit/8e342434e1b4fea618d6bb80b4e2f3aca8916177)) 225 | * re-use test-runner config ([c56e5ae](https://github.com/neovici/cosmoz-page-router/commit/c56e5aeff0351e60f577d079282c775763a46256)) 226 | * test cfg ([cb9536d](https://github.com/neovici/cosmoz-page-router/commit/cb9536d7a5292e44ebab2c153c43115cd2810e31)) 227 | * use hashchange event ([571119d](https://github.com/neovici/cosmoz-page-router/commit/571119ddd2399f924cb54dc0e9b9f207be47e328)) 228 | 229 | ### [6.0.6](https://github.com/neovici/cosmoz-page-router/compare/v6.0.5...v6.0.6) (2021-12-22) 230 | 231 | 232 | ### Bug Fixes 233 | 234 | * update repo ([3cd4440](https://github.com/neovici/cosmoz-page-router/commit/3cd44409f6b57c98aec6e4a5e1209fdcd4db04c2)) 235 | 236 | ### [6.0.5](https://github.com/neovici/cosmoz-page-router/compare/v6.0.4...v6.0.5) (2020-05-25) 237 | 238 | 239 | ### Bug Fixes 240 | 241 | * npm packaging, eslint/karma problem matchers, deps upgrade ([9955ae3](https://github.com/neovici/cosmoz-page-router/commit/9955ae342c3df04759264be3bc65d0b6af82ab89)) 242 | 243 | ### [6.0.4](https://github.com/neovici/cosmoz-page-router/compare/v6.0.3...v6.0.4) (2020-05-14) 244 | 245 | 246 | ### Bug Fixes 247 | 248 | * **create-element:** document.createElement breaks useContext ([2b947d8](https://github.com/neovici/cosmoz-page-router/commit/2b947d8c5ea8fa9dfa3cbaaea328b500c620103e)) 249 | * **router:** `until` directive breaks haunted effects ([951e886](https://github.com/neovici/cosmoz-page-router/commit/951e8868c94ef02183ce29b5d4feeb6bce2c1dfe)) 250 | 251 | ### [6.0.3](https://github.com/neovici/cosmoz-page-router/compare/v6.0.2...v6.0.3) (2020-03-25) 252 | 253 | 254 | ### Bug Fixes 255 | 256 | * handles encoded `#` in hash ([#85](https://github.com/neovici/cosmoz-page-router/issues/85)) ([add4812](https://github.com/neovici/cosmoz-page-router/commit/add48121c64228f73db03b177960c474772225c7)) 257 | 258 | ### [6.0.2](https://github.com/neovici/cosmoz-page-router/compare/v6.0.1...v6.0.2) (2020-03-24) 259 | 260 | 261 | ### Bug Fixes 262 | 263 | * update deps ([2debffb](https://github.com/neovici/cosmoz-page-router/commit/2debffb73ea02a54bee3c8618ce763505b8e1e30)) 264 | 265 | ### [6.0.1](https://github.com/neovici/cosmoz-page-router/compare/v6.0.0...v6.0.1) (2020-03-17) 266 | 267 | 268 | ### Bug Fixes 269 | 270 | * correct context in history.pushState(replaceState) ([31bcf0d](https://github.com/neovici/cosmoz-page-router/commit/31bcf0dc54de22f5d39a8343684aee507b15a0ac)) 271 | 272 | ## [6.0.0](https://github.com/neovici/cosmoz-page-router/compare/v5.0.0...v6.0.0) (2020-03-12) 273 | 274 | 275 | ### ⚠ BREAKING CHANGES 276 | 277 | * add cosmoz-router haunted implementation 278 | 279 | ### Features 280 | 281 | * add cosmoz-router haunted implementation ([9f04e7f](https://github.com/neovici/cosmoz-page-router/commit/9f04e7f4fbb851417e2998986703f5309e680aa4)) 282 | 283 | # [5.0.0](https://github.com/neovici/cosmoz-page-router/compare/v4.0.2...v5.0.0) (2020-03-02) 284 | 285 | 286 | ### Documentation 287 | 288 | * add maintainability/coverage badges ([bd65658](https://github.com/neovici/cosmoz-page-router/commit/bd656580cae7dc6ad0134051f24c7184707e1d8e)) 289 | 290 | 291 | ### BREAKING CHANGES 292 | 293 | * Refactored cosmoz-page-route(r) as LitElements, lots dropped. 294 | 295 | Signed-off-by: Patrik Kullman 296 | 297 | ## [4.0.2](https://github.com/neovici/cosmoz-page-router/compare/v4.0.1...v4.0.2) (2020-02-28) 298 | 299 | 300 | ### Bug Fixes 301 | 302 | * refresh repo ([5254603](https://github.com/neovici/cosmoz-page-router/commit/52546031a503abc60092228cbb505c3d64d79a6c)) 303 | 304 | ## [4.0.1](https://github.com/neovici/cosmoz-page-router/compare/v4.0.0...v4.0.1) (2019-10-09) 305 | 306 | 307 | ### Bug Fixes 308 | 309 | * **readme:** missing depfu badge ([f649685](https://github.com/neovici/cosmoz-page-router/commit/f649685)) 310 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Coding guidelines 2 | 3 | We follow the [Polymer](https://www.polymer-project.org) guidelines as well as [JSLint](http://jslint.com/) as best possible, but with some exceptions. 4 | 5 | Most importantly, we skip the check for `$` properties since Polymer populates `this.$` and we also skip the check for `_variable` since that's the way Polymer wants to do private properties and methods. Finally we allow the use of `this`. 6 | 7 | In addition to this we also choose to indent with tabs. 8 | 9 | ## JSLint 10 | 11 | To lint the JavaScript, you will need to install [node-jslint](https://github.com/reid/node-jslint), download our [jslint edition](https://raw.githubusercontent.com/Neovici/JSLint/all-patches/jslint.js) and save it as `jslint-cosmoz.js` in the node-jslint lib folder. 12 | 13 | * Linux: `/usr/local/lib/node_modules/jslint/lib` 14 | * Windows: `%APPDATA%\npm\node_modules\jslint\lib` 15 | 16 | ## Sublime Text 3 17 | 18 | The easiest way to conform to the guidelines is to run Sublime Text 3 and install the following packages: 19 | 20 | * SublimeLinter 21 | * SublimeLinter-contrib-jslint 22 | * TrailingSpaces 23 | 24 | ### Settings 25 | 26 | * SublimeLinter: `"show_errors_on_save": true` 27 | * TrailingSpaces: ` "trailing_spaces_trim_on_save": true` 28 | 29 | # Contributing code 30 | 31 | Just follow the [standard fork and pull request workflow](https://guides.github.com/activities/forking/). -------------------------------------------------------------------------------- /CREDITS.md: -------------------------------------------------------------------------------- 1 | # Credits 2 | 3 | cosmoz-router is based on Erik Ringsmuth's app-router component (https://github.com/erikringsmuth/app-router), licensed under the MIT License. 4 | 5 | The MIT License (MIT) 6 | 7 | Copyright (c) 2015 Erik Ringsmuth 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 Neovici AB 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | cosmoz-router 2 | ================== 3 | 4 | [![Build Status](https://github.com/Neovici/cosmoz-router/workflows/Github%20CI/badge.svg)](https://github.com/Neovici/cosmoz-router/actions?workflow=Github+CI) 5 | [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) 6 | 7 | ## <cosmoz-router> 8 | 9 | **cosmoz-router** is a haunted component to handle client side URL routing 10 | and view loading / management. 11 | 12 | By default **cosmoz-router** listens to `popstate` event 13 | , gets current location href and matches it against the routes defined. 14 | 15 | ## Getting started 16 | 17 | ### Installing 18 | 19 | Using npm: 20 | ```bash 21 | npm install --save @neovici/cosmoz-router 22 | ``` 23 | 24 | ### Importing 25 | 26 | The **cosmoz-router** element can be imported using: 27 | ```javascript 28 | import '@neovici/cosmoz-router/cosmoz-page-router'; 29 | ``` 30 | 31 | ## Usage 32 | 33 | ### Routes 34 | Routes are defined as an Array of Objects: 35 | ``` javascript 36 | import { html } from 'lit-html'; 37 | import { creteElement, navigate } from '@neovici/cosmoz-router/lib/use-routes'; 38 | 39 | const routes = [ 40 | { 41 | name: 'home', // optional (can be used to identity the route), 42 | rule: /^\/$/iu/, // a Regexp used to matched the route, 43 | handle: ({ 44 | url, // the current url string ( that matched the route) 45 | match, // the result of matching route against the rule, 46 | }) => html`` 47 | }, 48 | { 49 | name: 'some-page', 50 | rule: (url) => url.startsWith('/some-page'), // function called with current url string 51 | handle: ({ url })=>import('page.js') 52 | .then(()=> createElement('some-element', Object.fromEntries(url.searchParams))) 53 | }, 54 | { 55 | name: 'redirect', 56 | rule: /^\/some\-redirect$/iu, 57 | handle: ()=> navigate('#!/', null, { 58 | replace: true, // true to use replaceState,false to use pushState, 59 | notify: true // true to dispatch a `popstate` event 60 | }) 61 | } 62 | ]; 63 | ``` 64 | and passed to cosmoz-router: 65 | 66 | ``` javascript 67 | html``; 68 | ``` 69 | 70 | 71 | ## Documentation 72 | 73 | See http://neovici.github.io/cosmoz-router (outdated) 74 | 75 | TODO 76 | -------------------------------------------------------------------------------- /commitlint.config.mjs: -------------------------------------------------------------------------------- 1 | export default { 2 | extends: ['@commitlint/config-conventional'], 3 | rules: { 4 | 'body-max-line-length': [1, 'always', 600], 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@neovici/cosmoz-router", 3 | "version": "11.2.2", 4 | "description": "A Polymer component to handle client side URL routing and view loading / management", 5 | "keywords": [ 6 | "polymer", 7 | "web-components" 8 | ], 9 | "type": "module", 10 | "homepage": "https://github.com/neovici/cosmoz-router#readme", 11 | "bugs": { 12 | "url": "https://github.com/neovici/cosmoz-router/issues" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git+https://github.com/neovici/cosmoz-router.git" 17 | }, 18 | "license": "Apache-2.0", 19 | "author": "", 20 | "main": "dist/index.js", 21 | "directories": { 22 | "test": "test" 23 | }, 24 | "files": [ 25 | "dist/*" 26 | ], 27 | "scripts": { 28 | "lint": "tsc && eslint --cache .", 29 | "build": "tsc -p tsconfig.build.json", 30 | "start": "wds", 31 | "storybook:build": "storybook build", 32 | "test": "wtr --coverage", 33 | "test:watch": "wtr --watch", 34 | "prepare": "husky" 35 | }, 36 | "release": { 37 | "plugins": [ 38 | "@semantic-release/commit-analyzer", 39 | "@semantic-release/release-notes-generator", 40 | "@semantic-release/changelog", 41 | "@semantic-release/github", 42 | "@semantic-release/npm", 43 | "@semantic-release/git" 44 | ], 45 | "branch": "master", 46 | "preset": "conventionalcommits" 47 | }, 48 | "publishConfig": { 49 | "access": "public" 50 | }, 51 | "exports": { 52 | ".": "./dist/index.js", 53 | "./use-hash-param": "./dist/use-hash-param.js" 54 | }, 55 | "dependencies": { 56 | "@pionjs/pion": "^2.0.0" 57 | }, 58 | "devDependencies": { 59 | "@commitlint/cli": "^19.0.0", 60 | "@commitlint/config-conventional": "^19.0.0", 61 | "@neovici/cfg": "^1.15.0", 62 | "@open-wc/testing": "^4.0.0", 63 | "@semantic-release/changelog": "^6.0.0", 64 | "@semantic-release/git": "^10.0.0", 65 | "@storybook/addon-essentials": "^7.6.19", 66 | "@storybook/addon-links": "^7.6.19", 67 | "@storybook/builder-vite": "7.6.17", 68 | "@storybook/storybook-deployer": "^2.8.16", 69 | "@storybook/web-components": "7.6.17", 70 | "@types/mocha": "^10.0.3", 71 | "@web/dev-server": "^0.4.0", 72 | "@web/dev-server-storybook": "^2.0.0", 73 | "@web/storybook-builder": "^0.1.16", 74 | "@web/storybook-framework-web-components": "^0.1.2", 75 | "@web/test-runner": "^0.18.0", 76 | "husky": "^9.0.0", 77 | "rollup-plugin-esbuild": "^6.1.1", 78 | "semantic-release": "^23.0.0", 79 | "sinon": "^18.0.0", 80 | "storybook": "^7.6.19" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './match'; 2 | export * from './load'; 3 | export * from './use-routes'; 4 | export * from './use-router'; 5 | export { default as Router } from './router'; 6 | -------------------------------------------------------------------------------- /src/load.ts: -------------------------------------------------------------------------------- 1 | import { html as htm } from '@pionjs/pion'; 2 | import { RuleRet, BaseRoute } from './match'; 3 | 4 | const html: typeof htm = (arr, ...thru) => 5 | htm( 6 | Object.assign(arr, { raw: true }) as unknown as TemplateStringsArray, 7 | ...thru 8 | ); 9 | export const tagFromPath = ({ pathname }: URL) => 10 | pathname.substring(1).replace(/\//gu, '-'); 11 | 12 | export const createElement = (tag: string, props = {}) => { 13 | if (!customElements.get(tag)) { 14 | throw new Error(`Element ${tag} is not defined`); 15 | } 16 | 17 | // NOTE: previously this code used document.createElement, but it breaks some 18 | // expectations that lit-haunted makes: the fresh element is not attached to the DOM, 19 | // causing the useContext registration mechanism to fail 20 | 21 | // using a lit TemplateResult makes sure the element is connected when created 22 | // lit-html does not have support for dynamic tags, but we can create a TemplateResult 23 | // by calling the template tag function with the appropriate parameters 24 | // `html(strings[], ...values)` 25 | if (Object.keys(props).length > 0) { 26 | const strings = Object.keys(props).map((prop) => ` .${prop}=`); 27 | return html( 28 | [ 29 | `<${tag}${strings[0]}`, 30 | ...strings.slice(1), 31 | '>', 32 | ] as unknown as TemplateStringsArray, 33 | ...Object.values(props) 34 | ); 35 | } 36 | 37 | return html([`<${tag}>`] as unknown as TemplateStringsArray); 38 | }; 39 | 40 | export const load = 41 | ( 42 | pack: (params: Record) => T, 43 | tag: string | ((u: URL) => string) = tagFromPath 44 | ) => 45 |

({ match, route }: P) => { 46 | const url = match.url; 47 | const params = { 48 | ...match.result?.groups, 49 | ...Object.fromEntries(url.searchParams ?? []), 50 | }; 51 | return Promise.resolve(pack(params)).then(() => 52 | createElement(typeof tag === 'function' ? tag(url) : tag, { 53 | params, 54 | route, 55 | }) 56 | ); 57 | }; 58 | -------------------------------------------------------------------------------- /src/match.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/group-exports */ 2 | export type SRule = string | RegExp; 3 | export interface RuleRet { 4 | result: ReturnType; 5 | url: URL; 6 | } 7 | export type FnRule = (url: string) => RuleRet | null; 8 | export type Rule = SRule | FnRule; 9 | 10 | export interface BaseRoute { 11 | rule: Rule; 12 | } 13 | 14 | export const hashbang = (rule: SRule) => (url: string) => { 15 | const origin = document.location.origin, 16 | /* Chrome on iOS bug encodes second `#` in url as `%23` 17 | * https://github.com/Neovici/cosmoz-frontend/issues/1524 18 | * https://github.com/angular/angular.js/issues/7699 19 | */ 20 | hash = new URL(url, origin).hash.replace(/^#!?/iu, '').replace('%23', '#'), 21 | hashUrl = new URL(hash, origin), 22 | result = hashUrl.pathname.match(rule); 23 | return ( 24 | result && { 25 | result, 26 | url: hashUrl, 27 | } 28 | ); 29 | }; 30 | 31 | export const href = 32 | (rule: SRule) => 33 | (url: string): RuleRet | null => { 34 | const result = url.match(rule); 35 | return result && { result, url: new URL(url, document.location.origin) }; 36 | }; 37 | 38 | export const match = (routes: T[], url: string) => { 39 | for (const route of routes) { 40 | const rule = route.rule, 41 | match = typeof rule === 'function' ? rule(url) : href(rule)(url); 42 | if (match) { 43 | return { 44 | ...route, 45 | route, 46 | match, 47 | url, 48 | }; 49 | } 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /src/router.ts: -------------------------------------------------------------------------------- 1 | import { nothing } from 'lit-html'; 2 | import { guard } from 'lit-html/directives/guard.js'; 3 | import { until } from 'lit-html/directives/until.js'; 4 | import { component } from '@pionjs/pion'; 5 | 6 | import { useRouter, Route } from './use-router'; 7 | import { useRouteEvents } from './use-route-events'; 8 | 9 | interface Props { 10 | routes: Route[]; 11 | } 12 | interface RouterT extends HTMLElement, Props {} 13 | 14 | const Router = (host: RouterT) => { 15 | const routes: Route[] = host.routes, 16 | { route, result } = useRouter(routes); 17 | 18 | useRouteEvents(host, route, result); 19 | 20 | return guard([result], () => 21 | until( 22 | Promise.resolve(result).catch(() => nothing), 23 | nothing, 24 | ), 25 | ); 26 | }; 27 | 28 | customElements.define('cosmoz-router', component(Router)); 29 | 30 | export default Router; 31 | -------------------------------------------------------------------------------- /src/use-hash-param.ts: -------------------------------------------------------------------------------- 1 | import { useState, useEffect, useMemo, useRef } from '@pionjs/pion'; 2 | 3 | const hashUrl = () => 4 | new URL( 5 | location.hash.replace(/^#!?/iu, '').replace('%23', '#'), 6 | location.origin, 7 | ), 8 | parameterize = (hashParam?: string) => 9 | hashParam 10 | ? () => 11 | new URLSearchParams(hashUrl().hash.replace('#', '')).get(hashParam) 12 | : undefined; 13 | 14 | export const link = (hashParam: string, value?: string | null) => { 15 | if (!hashParam) { 16 | return; 17 | } 18 | const url = hashUrl(), 19 | sp = new URLSearchParams(url.hash.replace('#', '')); 20 | 21 | if (value == null) { 22 | sp.delete(hashParam); 23 | } else { 24 | sp.set(hashParam, value); 25 | } 26 | 27 | return ( 28 | '#!' + Object.assign(url, { hash: sp }).href.replace(location.origin, '') 29 | ); 30 | }; 31 | 32 | export const useHashParam = (hashParam?: string) => { 33 | const parameterized = useMemo(() => parameterize(hashParam), [hashParam]), 34 | [param, setParam] = useState(parameterized), 35 | ref = useRef(param); 36 | 37 | // eslint-disable-next-line no-void 38 | useEffect(() => void (ref.current = param), [param]); 39 | 40 | useEffect(() => { 41 | if (parameterized == null) { 42 | return; 43 | } 44 | const readParam = () => { 45 | const newParam = parameterized(); 46 | if (ref.current === newParam) { 47 | return; 48 | } 49 | setParam(newParam); 50 | }; 51 | readParam(); 52 | window.addEventListener('popstate', readParam); 53 | window.addEventListener('hashchange', readParam); 54 | return () => { 55 | window.removeEventListener('popstate', readParam); 56 | window.removeEventListener('hashchange', readParam); 57 | }; 58 | }, [parameterized]); 59 | 60 | const set = useMemo( 61 | () => 62 | hashParam 63 | ? (v: string | null) => { 64 | setParam(v); 65 | history.pushState({}, '', link(hashParam, v)); 66 | } 67 | : setParam, 68 | [hashParam], 69 | ); 70 | 71 | return [param, set] as const; 72 | }; 73 | -------------------------------------------------------------------------------- /src/use-route-events.ts: -------------------------------------------------------------------------------- 1 | import { useEffect } from '@pionjs/pion'; 2 | import type { BaseRoute } from './match'; 3 | 4 | const dispatch = (el: HTMLElement, type: string, opts?: object) => 5 | el.dispatchEvent( 6 | new CustomEvent(type, { 7 | bubbles: false, 8 | cancelable: false, 9 | composed: true, 10 | ...opts, 11 | }) 12 | ); 13 | 14 | export const useRouteEvents = ( 15 | el: HTMLElement, 16 | route?: T, 17 | result?: P 18 | ) => { 19 | useEffect(() => { 20 | if (!result) { 21 | dispatch(el, 'route-not-found'); 22 | return; 23 | } 24 | dispatch(el, 'route-loading', { detail: route }); 25 | Promise.resolve(result) 26 | .then(() => dispatch(el, 'route-loaded', { detail: route })) 27 | .catch((error) => 28 | dispatch(el, 'route-error', { 29 | detail: { 30 | route, 31 | error, 32 | }, 33 | }) 34 | ); 35 | }, [result]); 36 | }; 37 | -------------------------------------------------------------------------------- /src/use-router.ts: -------------------------------------------------------------------------------- 1 | import { useMemo } from '@pionjs/pion'; 2 | 3 | import { useRoutes } from './use-routes'; 4 | import type { BaseRoute } from './match'; 5 | 6 | export type MatchedRoute = NonNullable>; 7 | 8 | export interface Route extends BaseRoute { 9 | handle: (r: MatchedRoute) => T; 10 | } 11 | 12 | export const useRouter = = Route>( 13 | routes: T[], 14 | ) => { 15 | const route = useRoutes(routes); 16 | 17 | return { 18 | route, 19 | result: useMemo(() => { 20 | if (route) { 21 | const { handle, ..._route } = route; 22 | return handle(_route); 23 | } 24 | }, [route]), 25 | }; 26 | }; 27 | -------------------------------------------------------------------------------- /src/use-routes.ts: -------------------------------------------------------------------------------- 1 | import { useState, useEffect, useMemo } from '@pionjs/pion'; 2 | import { match, BaseRoute } from './match'; 3 | 4 | export const documentUrl = () => 5 | window.location.href.replace(window.location.origin, ''); 6 | 7 | export const useUrl = () => { 8 | const [url, setUrl] = useState(documentUrl); 9 | useEffect(() => { 10 | const onPopState = () => setUrl(documentUrl); 11 | window.addEventListener('popstate', onPopState); 12 | return () => window.removeEventListener('popstate', onPopState); 13 | }, [setUrl]); 14 | 15 | return url; 16 | }; 17 | 18 | export const useRoutes = (routes: T[]) => { 19 | const url = useUrl(); 20 | return useMemo(() => match(routes, url), [routes, url]); 21 | }; 22 | 23 | export const navigate = ( 24 | url: string, 25 | state = null, 26 | { notify = true, replace = true } = {} 27 | ) => { 28 | (replace ? history.replaceState : history.pushState).call( 29 | history, 30 | state, 31 | '', 32 | url 33 | ); 34 | if (notify) { 35 | queueMicrotask(() => 36 | window.dispatchEvent( 37 | new CustomEvent('popstate', { 38 | bubbles: false, 39 | }) 40 | ) 41 | ); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /stories/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "no-console": "off" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /stories/cosmoz-router.stories.js: -------------------------------------------------------------------------------- 1 | import { html, component } from '@pionjs/pion'; 2 | import { hashbang, createElement } from '../src/index.ts'; 3 | 4 | export default { 5 | title: 'Cosmoz Router', 6 | }; 7 | 8 | customElements.define( 9 | 'demo-router', 10 | component(() => { 11 | const routes = [ 12 | { 13 | rule: hashbang(/^\/$/u), 14 | handle: () => 15 | import('./views/home.js').then(() => createElement('demo-home')), 16 | }, 17 | { 18 | rule: hashbang(/^\/view-1/u), 19 | handle: () => 20 | import('./views/view-1.js').then(() => createElement('view-1')), 21 | }, 22 | { 23 | rule: hashbang(/^\/view-2/u), 24 | handle: () => 25 | import('./views/view-2.js').then(() => createElement('view-2')), 26 | }, 27 | { 28 | rule: hashbang(/^\/view-3/u), 29 | handle: () => 30 | import('./views/view-3.js').then(() => createElement('view-3')), 31 | }, 32 | ]; 33 | return html``; 34 | }) 35 | ); 36 | 37 | const Router = () => ` 38 | 63 |

64 |

cosmoz-router test

65 | 71 | 72 |
73 | 74 |
75 |
`; 76 | 77 | export { Router }; 78 | -------------------------------------------------------------------------------- /stories/views/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "new-cap": "off" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /stories/views/home.js: -------------------------------------------------------------------------------- 1 | import { html, component } from '@pionjs/pion'; 2 | 3 | customElements.define( 4 | 'demo-home', 5 | component(() => html`

Welcome to the home page

`) 6 | ); 7 | -------------------------------------------------------------------------------- /stories/views/param-reading-view.js: -------------------------------------------------------------------------------- 1 | import { html, component } from '@pionjs/pion'; 2 | 3 | customElements.define( 4 | 'param-reading-view', 5 | component(({ p1, p2 }) => html` p1: ${p1}; p2: ${p2}`) 6 | ); 7 | -------------------------------------------------------------------------------- /stories/views/view-1.js: -------------------------------------------------------------------------------- 1 | import { html, component, useState, useEffect } from '@pionjs/pion'; 2 | 3 | customElements.define( 4 | 'view-1', 5 | component(() => { 6 | const [count, setCount] = useState(0); 7 | useEffect(() => { 8 | console.log('I\'ve been activated !'); 9 | }, []); 10 | 11 | return html` 12 |

Welcome to the test view 1

13 |
count = ${count}.
14 |
    15 | ${Array(count) 16 | .fill(1) 17 | .map((_, item) => html`
  • ${item}
  • `)} 18 |
19 | 20 | `; 21 | }) 22 | ); 23 | -------------------------------------------------------------------------------- /stories/views/view-2.js: -------------------------------------------------------------------------------- 1 | import { html, component, useState, useEffect } from '@pionjs/pion'; 2 | 3 | customElements.define( 4 | 'view-2', 5 | component(() => { 6 | const [count, setCount] = useState(0); 7 | useEffect(() => { 8 | console.log('I\'ve been activated !'); 9 | }, []); 10 | 11 | return html` 12 |

Welcome to the test view 2

13 |
count = ${count}.
14 |
    15 | ${Array(count) 16 | .fill(1) 17 | .map((_, item) => html`
  • ${item}
  • `)} 18 |
19 | 20 | `; 21 | }) 22 | ); 23 | -------------------------------------------------------------------------------- /stories/views/view-3.js: -------------------------------------------------------------------------------- 1 | import { html, component, useState, useEffect } from '@pionjs/pion'; 2 | 3 | customElements.define( 4 | 'view-3', 5 | component(() => { 6 | const [count, setCount] = useState(0); 7 | useEffect(() => { 8 | console.log('I\'ve been activated !'); 9 | }, []); 10 | 11 | return html` 12 |

Welcome to the test view 3

13 |
count = ${count}.
14 |
    15 | ${Array(count) 16 | .fill(1) 17 | .map((_, item) => html`
  • ${item}
  • `)} 18 |
19 | 20 | `; 21 | }) 22 | ); 23 | -------------------------------------------------------------------------------- /test/basic.test.ts: -------------------------------------------------------------------------------- 1 | import { 2 | assert, 3 | html, 4 | fixtureSync, 5 | oneEvent, 6 | nextFrame, 7 | } from '@open-wc/testing'; 8 | import { mock } from 'sinon'; 9 | 10 | import { navigate, documentUrl } from '../src/use-routes'; 11 | import { createElement, load } from '../src/load'; 12 | import { hashbang } from '../src/match'; 13 | import { Route } from '../src/use-router'; 14 | 15 | /* eslint-disable max-lines-per-function */ 16 | suite('cosmoz-router', () => { 17 | const routes: Route[] = [ 18 | { 19 | rule: /^\/$/u, 20 | handle: () => 21 | import('../stories/views/home.js').then(() => 22 | createElement('demo-home'), 23 | ), 24 | }, 25 | { 26 | rule: hashbang(/^\/view-1/u), 27 | handle: load(() => import('../stories/views/view-1.js'), 'view-1'), 28 | }, 29 | { 30 | rule: hashbang(/^\/param-reading-view/u), 31 | handle: (result) => 32 | import('../stories/views/param-reading-view.js').then(() => { 33 | const entries = result.match.url?.searchParams?.entries(); 34 | return createElement( 35 | 'param-reading-view', 36 | entries ? Object.fromEntries(entries) : {}, 37 | ); 38 | }), 39 | }, 40 | { 41 | rule: hashbang(/^\/error/u), 42 | handle: () => Promise.reject(new Error('testing')), 43 | }, 44 | ]; 45 | let url: string; 46 | 47 | suiteSetup(async () => { 48 | url = documentUrl(); 49 | await import('../src/router'); 50 | }); 51 | suiteTeardown(() => navigate(url, null, { notify: false })); 52 | 53 | test('renders home', async () => { 54 | navigate('/'); 55 | const router = fixtureSync(html``); 56 | await oneEvent(router, 'route-loaded'); 57 | await nextFrame(); 58 | assert.shadowDom.equal(router, ''); 59 | }); 60 | 61 | test('renders view-1', async () => { 62 | navigate('#!/view-1'); 63 | const router = fixtureSync(html``); 64 | await oneEvent(router, 'route-loaded'); 65 | await nextFrame(); 66 | assert.shadowDom.equal(router, ''); 67 | }); 68 | 69 | test('renders not-found', async () => { 70 | navigate('#/not-found'); 71 | const router = fixtureSync(html``); 72 | await oneEvent(router, 'route-not-found'); 73 | await nextFrame(); 74 | assert.shadowDom.equal(router, ''); 75 | }); 76 | 77 | test('renders home, then view-1', async () => { 78 | navigate('/'); 79 | const router = fixtureSync(html``); 80 | await oneEvent(router, 'route-loaded'); 81 | await nextFrame(); 82 | assert.shadowDom.equal(router, ''); 83 | 84 | navigate('#!/view-1'); 85 | await oneEvent(router, 'route-loaded'); 86 | await nextFrame(); 87 | assert.shadowDom.equal(router, ''); 88 | }); 89 | 90 | test('error', async () => { 91 | navigate('#!/error'); 92 | const router = fixtureSync(html``), 93 | { detail } = await oneEvent(router, 'route-error'); 94 | assert.equal(detail.error.message, 'testing'); 95 | }); 96 | 97 | test('params', async () => { 98 | navigate('#!/param-reading-view?p1=1&p2=2'); 99 | const router = fixtureSync(html``); 100 | await oneEvent(router, 'route-loaded'); 101 | await nextFrame(); 102 | assert.shadowDom.equal( 103 | router.shadowRoot?.querySelector('param-reading-view'), 104 | 'p1: 1; p2: 2', 105 | ); 106 | }); 107 | }); 108 | 109 | suite('use-routes', () => { 110 | test('createElement', () => { 111 | assert.throws(() => createElement('definetly-undefined')); 112 | }); 113 | 114 | test('navigate', () => { 115 | const historyMock = mock(history), 116 | replaceState = historyMock.expects('replaceState'), 117 | pushState = historyMock.expects('pushState'); 118 | 119 | navigate('/asd'); 120 | assert(replaceState.withArgs(null, '', '/asd')); 121 | 122 | navigate('/das', null, { 123 | replace: false, 124 | notify: false, 125 | }); 126 | assert(pushState.withArgs(null, '', '/das')); 127 | 128 | historyMock.restore(); 129 | }); 130 | }); 131 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "dist", 5 | "declaration": true, 6 | "noEmit": false 7 | }, 8 | "include": ["src"] 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "noEmit": true, 5 | "module": "esnext", 6 | "moduleResolution": "bundler", 7 | "strict": true, 8 | "target": "esnext", 9 | "allowJs": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /web-dev-server.config.mjs: -------------------------------------------------------------------------------- 1 | import cfg from '@neovici/cfg/web/dev-server.mjs'; 2 | import { storybookPlugin } from '@web/dev-server-storybook'; 3 | 4 | export default { 5 | ...cfg, 6 | plugins: [ 7 | ...cfg.plugins, 8 | storybookPlugin({ type: 'web-components' }), 9 | ], 10 | }; 11 | -------------------------------------------------------------------------------- /web-test-runner.config.mjs: -------------------------------------------------------------------------------- 1 | export { default } from '@neovici/cfg/web/test-runner.mjs'; 2 | --------------------------------------------------------------------------------