Repository: kazzkiq/svero Branch: master Commit: e27f95048097 Files: 24 Total size: 29.4 KB Directory structure: gitextract_dvw8sfi4/ ├── .gitattributes ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── nightwatch.json ├── package.json ├── rollup.config.js ├── src/ │ ├── Link.svelte │ ├── Route.svelte │ ├── Router.svelte │ ├── main.js │ └── utils.js └── test/ ├── About.svelte ├── App.svelte ├── Index.svelte ├── User.svelte ├── e2e/ │ ├── link.js │ ├── navigateTo.js │ ├── route.js │ └── router.js ├── main.js └── public/ ├── 404.html └── index.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ package-lock.json -diff build/* -diff ================================================ FILE: .gitignore ================================================ .DS_Store node_modules yarn.lock chromedriver.log *.xml dist tests_output test/public/test.js test/public/test.js.map ================================================ FILE: .travis.yml ================================================ sudo: required addons: chrome: stable language: node_js node_js: - "lts/*" deploy: provider: npm email: $NPM_EMAIL api_key: $NPM_TOKEN on: tags: true notifications: email: false ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 Claudio Holanda 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. ================================================ FILE: README.md ================================================ ⚠️⚠️ THIS LIBRARY IS DEPRECATED AND SHOULD NOT BE USED IN NEW PROJECTS ⚠️⚠️ ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️
⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️ ⚠️⚠️ MORE DETAILS [HERE](https://github.com/kazzkiq/svero/issues/68). ⚠️⚠️ ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️
⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️ [![npm version](https://badge.fury.io/js/svero.svg)](https://www.npmjs.com/package/svero) [![Build Status](https://travis-ci.org/kazzkiq/svero.svg?branch=master)](https://travis-ci.org/kazzkiq/svero)

svero (Svelte Router): A simple router for Svelte 3.

## First things first svero is intented to be used in SPA (Single Page Applications) making usage of `pushState` and History API. We're assuming that you already know how to configure your front-end server (being it dev or production) to serve all path requests to `index.html`. If you're not familiar with the terms SPA, `pushState` or History API, you should probably be reading these first: http://krasimirtsonev.com/blog/article/deep-dive-into-client-side-routing-navigo-pushstate-hash
https://css-tricks.com/using-the-html5-history-api/
https://diveinto.html5doctor.com/history.html
https://developer.mozilla.org/pt-BR/docs/Web/API/History
## Installation Since it's exported in CommonJS format, you should be using it with a module bundler such as [Rollup](https://github.com/sveltejs/template/tree/v3) or Webpack. You can install svero via npm: ``` npm install --save svero ``` ## Usage The usage is super simple: ```html ``` The `*` wildcard simply works as a fallback. If a route fails to meet any other path, it then loads the path with the `*`. If there is no wildcard route and the route did not meet any other path, nothing is loaded. Your custom props can be passed by putting your component in the Route `slot` (Employees example above). Paths with parameters (`:param`) are passed to components via props: `router.params`. > Parameters like `*param` will capture the rest of segments. You can access them as `router.params._` like other params. A component loaded by `` receives a property with route details: ```html ``` Additional properties are passed to the mounted component, e.g. ```html ``` Also, you can pass an object: ```html ``` > `Route` props are omitted, but all remaining ones are passed to `Test`. Routes can also render any given markup when they're active, e.g. ```html

It works!

``` > You can access `router` within `` renders by declaring `let:router` on `` or `` components (see below). If you're building an SPA or simply want to leverage on hash-based routing for certain components try the following: ```html

Info: {JSON.stringify(router.params)}

``` Standard anchors and `` components will work as usual: ```html View README.md ``` Declaring a component `` will serve as fallback when `location.hash` is empty. ### Nesting You can render `svero` components inside anything, e.g. ```html
Routing: {router.params.bar}! Foo

Not found: {router.params._}

{router.failure}
[...] not found? A C {JSON.stringify(router.params)}
``` Properties determine how routing will match and render routes: - Use the `nofallback` prop for telling `` to disable the _fallback_ mechanism by default - Any route using the `fallback` prop will catch unmatched routes or potential look-up errors - Use the `exact` prop to skip this route from render just in case it does not matches - A `` without `path` will render only if `` is active! > Note that all `` paths MUST begin from the root as `/sub` and `/sub/nested` in the example. ### Redirects Sometimes you just want a route to send user to another place. You can use the `redirect` attribute for that. A redirect should always be a string with a path. It uses the same pattern as `path` attribute. For a redirect to run, there must be a Route with the equivalent path. ```html ``` ### Conditions If you need to meet a condition in order to run a route, you can use the `condition` attribute. Conditions can also be used with `redirect` for graceful route fallback. A condition should be either `boolean` or a function returning `boolean`. There is no support for asynchronous conditions at the moment (so keep it simple). ```html ``` Think of it as a simpler middleware. A condition will run *before* the route loads your component, so there is no wasteful component mounting, and no screen blinking the unwanted view. ### Link Component There is also an useful `` component that overrides `` elements: ```html Hello! ``` The difference between `` and `` is that it uses `pushState` whenever possible, with fallback to `` behavior. This means that when you use ``, svero can update the view based on your URL trigger, without reloading the entire page. > Given `href` values will be normalized (on-click) if they don't start with a slash, e.g. when `location.pathname === '/foo'` then `#bar` would become `/foo#bar` as result. ### navigateTo() In some cases you want to navigate to routes programatically instead of letting user click on links. For this scenario we have `navigateto()` which takes a route as parameter and navigates imediatelly to said route. `navigateTo()` receives the same treatment as ``: It will always try to use `pushState` for better performance, fallbacking to a full page redirect if it isn't supported. Usage: ```html ``` ### Webpack issues If you're having trouble with Webpack failing to load svero, please replace the following rule (in Svelte rule): ```js exclude: /node_modules/, ``` with: ```js exclude: /node_modules\/(?!(svero)\/).*/, ``` More information [here](https://github.com/kazzkiq/svero/issues/23). ================================================ FILE: nightwatch.json ================================================ { "src_folders" : ["test/e2e"], "webdriver" : { "start_process": true, "server_path": "node_modules/.bin/chromedriver", "port": 9515 }, "test_settings" : { "default" : { "desiredCapabilities": { "browserName": "chrome", "chromeOptions": { "args": [ "--headless" ] } } } } } ================================================ FILE: package.json ================================================ { "name": "svero", "version": "1.0.0", "description": "Simple Router for Svelte 3", "main": "dist/svero.js", "svelte": "src/main.js", "module": "dist/svero.es.js", "browser": "dist/svero.min.js", "files": [ "src/**", "dist/*" ], "peerDependencies": { "svelte": "3.x" }, "devDependencies": { "chromedriver": "^78.0.1", "http-server": "^0.11.1", "kill-port": "^1.3.2", "nightwatch": "^1.0.19", "rollup": "^1.14.4", "rollup-plugin-commonjs": "^10.0.0", "rollup-plugin-node-resolve": "^5.0.1", "rollup-plugin-svelte": "^5.0.3", "rollup-plugin-terser": "^5.0.0", "svelte": "^3.4.4" }, "dependencies": { "abstract-nested-router": "^0.1.3" }, "scripts": { "test": "kill-port 5001 && npm run test:server & npm run test:build && npm run test:run", "debug": "kill-port 5001 && npm run test:build && npm run test:server", "test:server": "http-server test/public -s -p 5001", "test:build": "NODE_ENV=test rollup -c", "test:run": "nightwatch", "build": "NODE_ENV=production rollup -c", "prepublishOnly": "npm run test && npm run build" }, "repository": { "type": "git", "url": "git+https://github.com/kazzkiq/svero.git" }, "keywords": [ "router", "svelte", "svelte3" ], "author": "Claudio Holanda", "license": "MIT", "bugs": { "url": "https://github.com/kazzkiq/svero/issues" }, "homepage": "https://github.com/kazzkiq/svero" } ================================================ FILE: rollup.config.js ================================================ import svelte from 'rollup-plugin-svelte'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import { terser } from 'rollup-plugin-terser'; const isDev = process.env.ROLLUP_WATCH; const isProd = process.env.NODE_ENV === 'production'; function bundle(file, format) { return { sourcemap: false, name: 'svero', format, file, }; } export default { input: isProd ? 'src/main.js' : 'test/main.js', output: isProd ? [ bundle('dist/svero.js', 'cjs'), bundle('dist/svero.es.js', 'es'), bundle('dist/svero.min.js', 'umd'), ] : bundle('test/public/test.js', 'iife'), external: isProd ? ['svelte', 'svelte/store', 'svelte/internal'] : [], plugins: [ svelte({ dev: isDev, }), resolve(), commonjs(), isProd && terser(), ], }; ================================================ FILE: src/Link.svelte ================================================ ================================================ FILE: src/Route.svelte ================================================ {#if activeRouter} {#if component} {:else} {/if} {/if} ================================================ FILE: src/Router.svelte ================================================ {#if failure && !nofallback}
Router failure: {path}
{failure}
{/if} ================================================ FILE: src/main.js ================================================ import Router from './Router.svelte'; import Route from './Route.svelte'; import Link from './Link.svelte'; import { navigateTo } from './utils'; export { Router, Route, Link, navigateTo }; ================================================ FILE: src/utils.js ================================================ export const CTX_ROUTER = {}; export function navigateTo(path) { // If path empty or no string, throws error if (!path || typeof path !== 'string') { throw Error(`svero expects navigateTo() to have a string parameter. The parameter provided was: ${path} of type ${typeof path} instead.`); } if (path[0] !== '/' && path[0] !== '#') { throw Error(`svero expects navigateTo() param to start with slash or hash, e.g. "/${path}" or "#${path}" instead of "${path}".`); } // If no History API support, fallbacks to URL redirect if (!history.pushState || !window.dispatchEvent) { window.location.href = path; return; } // If has History API support, uses it history.pushState({}, '', path); window.dispatchEvent(new Event('popstate')); } ================================================ FILE: test/About.svelte ================================================

Hello from About!

{#if description}

{description}

{/if} ================================================ FILE: test/App.svelte ================================================

Not found

It works!

Show params | Static test | Reset hash

Params: {JSON.stringify(router.params)} Static placeholder is shown No hash is present

Anchored. {router.params._}

Routing: {router.params.bar}! Foo

Not found: {router.params._}

{router.failure}
[...] not found? A C {JSON.stringify(router.params)}
================================================ FILE: test/Index.svelte ================================================

Hello from Index!

================================================ FILE: test/User.svelte ================================================ {#if router.params.age}

Hello {router.params.name}, {router.params.age}yo!

{:else}

Hello {router.params.name}!

{/if} {#if window.location.pathname === '/admin-true'}

Admin Panel

{/if} {#if router.params.name === 'Classious'} Go to About {:else} Go to About {/if}

{ navigateTo('') }}>Does nothing
{ navigateTo('about') }}>Does nothing
No Class Link ================================================ FILE: test/e2e/link.js ================================================ module.exports = { ' Href Attribute Tests': (browser) => { browser .url('http://localhost:5001/user/Amanda') .waitForElementVisible('a') .click('a') .pause(100) .assert.containsText('h1', 'Hello from About!') .assert.urlContains('/about') .end(); }, ' ClassName Attribute Tests': (browser) => { browser .url('http://localhost:5001/user/Amanda') .waitForElementVisible('a.red') .end(); }, ' Class Attribute Tests': (browser) => { browser .url('http://localhost:5001/user/Classious') .waitForElementVisible('a.purple') .end(); }, ' Empty Class Attribute Shouldn\'t be "undefined"': (browser) => { browser .url('http://localhost:5001/user/Josh') .waitForElementVisible('a[href="/test-no-class"]:not(.undefined)') .end(); }, ' Text Tests': (browser) => { browser .url('http://localhost:5001/user/Amanda') .waitForElementVisible('a.red') .assert.containsText('a.red', 'Go to About') .end(); }, }; ================================================ FILE: test/e2e/navigateTo.js ================================================ module.exports = { 'navigateTo(path) navigate to new path': (browser) => { browser .url('http://localhost:5001/user/Jon') .waitForElementVisible('button') .click('button') .pause(100) .assert.containsText('h1', 'Hello from About!') .assert.urlContains('/about') .end(); }, 'navigateTo(path) empty parameter does nothing': (browser) => { browser .url('http://localhost:5001/user/Jon') .waitForElementVisible('em') .click('em') .pause(100) .assert.containsText('h1', 'Hello Jon!') .assert.urlContains('/user/Jon') .end(); }, 'navigateTo(path) parameter not starting with slash (/) does nothing': (browser) => { browser .url('http://localhost:5001/user/Jon') .waitForElementVisible('strong') .click('strong') .pause(100) .assert.containsText('h1', 'Hello Jon!') .assert.urlContains('/user/Jon') .end(); } }; ================================================ FILE: test/e2e/route.js ================================================ module.exports = { ' Wildcard (*) Tests': (browser) => { browser // Checking if "/" Route loads Index Component .url('http://localhost:5001') .waitForElementVisible('h1') .assert.containsText('h1', 'Hello from Index!') // Checking if non-existent route redirects to About Page .url('http://localhost:5001/does-not-exists') .waitForElementVisible('h1') .assert.containsText('h1', 'Not found') .end(); }, ' Slot rendering (/slot) Tests': (browser) => { browser .url('http://localhost:5001/slot') .waitForElementVisible('h3') .assert.containsText('h3', 'It works!') .end(); }, ' Basic path (/{name}) Tests': (browser) => { browser .url('http://localhost:5001/about') .waitForElementVisible('h1') .assert.containsText('h1', 'Hello from About!') .end(); }, ' Single param (/:name) Tests': (browser) => { browser .url('http://localhost:5001/user/Amanda') .waitForElementVisible('h1') .assert.containsText('h1', 'Hello Amanda!') .end(); }, ' Multiple params (/:name/:age) Tests': (browser) => { browser .url('http://localhost:5001/user/Amanda/30') .waitForElementVisible('h1') .assert.containsText('h1', 'Hello Amanda, 30yo!') .end(); }, ' Redirect Attribute Tests': (browser) => { browser .url('http://localhost:5001/company') .waitForElementVisible('h1') .assert.containsText('h1', 'Hello from About!') .assert.urlContains('/about') .end(); }, ' Redirect Attribute Tests': (browser) => { browser // Check if /admin-false redirects to index .url('http://localhost:5001/admin-false') .pause(100) .waitForElementVisible('h1') .assert.containsText('h1', 'Hello from Index!') .assert.urlContains('/') // Check if /admin-true redirects to the right page .url('http://localhost:5001/admin-true') .waitForElementVisible('h2') .assert.containsText('h2', 'Admin Panel') .assert.urlContains('/admin-true') .end(); }, ' should work with hash-based routes': (browser) => { browser .url('http://localhost:5001/nested#') .waitForElementVisible('p') .assert.containsText('p', 'No hash is present') .click('a[href="#abc/def/ghi"]') .assert.containsText('p', 'Params: {"any":"abc","path":"def/ghi"}') .click('a[href="#test"]') .assert.containsText('p', 'Static placeholder is shown') .end(); }, ' use fallback for unreachable nested-routes': (browser) => { browser .url('http://localhost:5001/nested/im_not_exists') .waitForElementVisible('h1') .assert.containsText('h1', 'Not found') .end(); }, ' hash-based paths can all catch-all': (browser) => { browser .url('http://localhost:5001/#whatever') .waitForElementVisible('h1') .assert.containsText('h1', 'Hello from Index!') .waitForElementVisible('p') .assert.containsText('p', 'Anchored. whatever') .end(); }, ' can receive additional props': (browser) => { browser .url('http://localhost:5001/about') .waitForElementVisible('p') .assert.containsText('p', 'Company and such.') .end(); }, }; ================================================ FILE: test/e2e/router.js ================================================ module.exports = { ' Render inside elements': (browser) => { browser .url('http://localhost:5001') .waitForElementVisible('main h1') .assert.containsText('main h1', 'Hello from Index!') .url('http://localhost:5001/does-not-exists') .waitForElementVisible('main h1') .assert.containsText('main h1', 'Not found') .end(); }, ' can be nested indefinitely': (browser) => { browser .url('http://localhost:5001/sub') .waitForElementVisible('fieldset') .url('http://localhost:5001/sub/val') .waitForElementVisible('fieldset') .assert.containsText('fieldset', 'val!') .url('http://localhost:5001/sub/foo') .waitForElementVisible('fieldset') .assert.containsText('fieldset', 'Foo') .url('http://localhost:5001/sub/im/not/exists') .waitForElementVisible('fieldset') .assert.containsText('fieldset', 'im!') .assert.containsText('fieldset', 'Not found: sub/im/not/exists') .url('http://localhost:5001/sub/nested') .waitForElementVisible('fieldset') .assert.containsText('fieldset', '[...]') .url('http://localhost:5001/sub/nested/a') .waitForElementVisible('fieldset') .assert.containsText('fieldset', '[...] A') .url('http://localhost:5001/sub/nested/b') .waitForElementVisible('fieldset') .assert.containsText('fieldset', '[...] C') .url('http://localhost:5001/sub/nested/b/d') .waitForElementVisible('fieldset') .assert.containsText('fieldset', '[...] C') .url('http://localhost:5001/sub/nested/b/c/d') .waitForElementVisible('fieldset') .assert.containsText('fieldset', '[...] not found? C') .assert.containsText('fieldset', 'Not found: sub/nested/b/c/d') .url('http://localhost:5001/sub/nested/something') .waitForElementVisible('fieldset') .assert.containsText('fieldset', '[...] {"value":"something"}') .end(); }, }; ================================================ FILE: test/main.js ================================================ import App from './App.svelte'; document.addEventListener('DOMContentLoaded', () => { new App({ target: document.body }); }); ================================================ FILE: test/public/404.html ================================================ Svero Testing Page ================================================ FILE: test/public/index.html ================================================ Svero Testing Page