Skip to content

Commit

Permalink
Merge pull request #1 from Djess-V/router
Browse files Browse the repository at this point in the history
Added router
  • Loading branch information
Djess-V committed Jul 4, 2023
2 parents ffb9b7d + 6c4f6da commit 84af536
Show file tree
Hide file tree
Showing 17 changed files with 1,210 additions and 159 deletions.
12 changes: 4 additions & 8 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,19 @@ module.exports = {
endOfLine: "auto",
},
],
"import/extensions": ["warn", { ts: "never" }],
"import/prefer-default-export": "off",
"import/no-extraneous-dependencies": [
"error",
{
packageDir: __dirname,
packageDir: "./",
},
],
"@typescript-eslint/no-var-requires": "off",
"import/extensions": ["warn", { ts: "never" }],
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-var-requires": "off",
"no-param-reassign": "off",
"no-nested-ternary": "off",
"no-console": "off",
"no-eval": "off",
"no-promise-executor-return": "off",
"no-use-before-define": "off",
"no-restricted-syntax": "off",
"default-param-last": "off",
},
};
4 changes: 2 additions & 2 deletions .github/workflows/sanity-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
- name: Lint
run: |
npm run lint
- name: Test
run: |
npm run test
npm run test
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Meta Platforms, Inc. and affiliates.

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.
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<h1 align="center">Библиотека клиентского роутинга</h1>

<p align="center">
<img alt="Badge" src="https://github.com/djess-v/otus--homework--18/actions/workflows/sanity-check.yml/badge.svg" />
</p>

## Getting Started

Install @djess-v/router using [`npm`](https://www.npmjs.com/package/@djess-v/router):

```bash
npm install @djess-v/router
```

Typing

```bash
export interface IArgs {
currentPath: string;
previousPath: string | null;
state: Record<string, any>;
}
export type IState = Record<string, any>;
export type IMatch = RegExp | string | ((path: string) => boolean);
export type IHook = (...args: IArgs[]) => Promise<any> | any;
export interface IHooks {
onEnter?: IHook;
onLeave?: IHook;
onBeforeEnter?: IHook;
}
export interface IListener {
id: string;
match: IMatch;
hooks: IHooks;
}
export interface IRouter {
on: (match: IMatch, hooks?: IHooks) => () => void;
go: (url: string, state: IState) => void;
unsubscribeAll: () => void;
}
declare class Router implements IRouter {
private listeners;
private previousPath;
private currentPath;
private mode;
constructor(mode?: "history" | "hash");
static isMatch: (match: IMatch, path: string) => boolean;
static getQueryParams: () => IState;
private init;
unsubscribeAll: () => void;
private getPath;
private handleListener;
private handleAllListeners;
on: (match: IMatch, hooks?: IHooks) => (() => void);
go: (url: string, state?: IState) => void;
private handleClick;
private bindHandleClick;
private handlePopState;
private bindHandlePopState;
private handleHashChange;
private bindHandleHashChange;
}
```
Using
```bash
const router = new Router();
router.on("/", {
onEnter: () => {
// your code
},
// other hooks
});
```
## License
@djess-v/router is [MIT licensed](./LICENSE).
2 changes: 2 additions & 0 deletions example/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
declare const PRODUCTION: boolean;
declare const PREFIX: string;
35 changes: 35 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Роутинг</title>
</head>
<body>
<header>
<h1>Пример работы клиентского роутинга</h1>
<p id="message">
Отработка хуков: onBeforeEnter, onEnter, onLeave будет видна в консоли!
</p>
<p data-name="terms" data-id="hash" style="color: blue; cursor: pointer">
Hash API
</p>
<p
data-name="terms"
data-id="history"
style="color: blue; cursor: pointer"
>
History API
</p>
<nav id="nav" style="justify-content: space-around; display: none">
<a href="/">Home</a>
<a id="contacts" href="/contacts">Contacts</a>
<a href="/about">About</a>
<a href="/about/us">About / Us</a>
<a href="/login">Login</a>
</nav>
</header>
<article id="root" style="display: none"></article>
</body>
</html>
99 changes: 99 additions & 0 deletions example/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { Router, IArgs } from "../src/router";

const createRender =
(content: string) =>
(...args: IArgs[]) => {
console.log(`${content} args=${JSON.stringify(args)}`);
(<HTMLElement>document.getElementById("root")).innerHTML = `${content}`;
};

const drawInfo =
(content: string) =>
(...args: IArgs[]) => {
console.log(`${content} args=${JSON.stringify(args)}`);
};

const createLogger =
(content: string) =>
(...args: IArgs[]) => {
console.log(`${content} args=${JSON.stringify(args)}`);
};

const connectHooks = (router: Router, mode: "hash" | "history") => {
let prefix = PREFIX;

if (PRODUCTION && mode === "hash") {
prefix = "";
}

router.on(new RegExp(`^${prefix}/$`), {
onEnter: createRender(`/`),
onLeave: createLogger(`[onLeave] /`),
});
const unsubscribe = router.on((path) => path === `${prefix}/contacts`, {
onEnter: createRender(`/contacts`),
onBeforeEnter: drawInfo(`[onBeforeEnter] /contacts`),
});
router.on(`${prefix}/about`, {
onEnter: createRender(`/about`),
onLeave: createLogger(`[onLeave] /about`),
});
router.on(`${prefix}/about/us`, {
onEnter: createRender(`/about/us`),
});
router.on(new RegExp(`^${prefix}/login$`), {
onEnter: createRender(`/login`),
onBeforeEnter: drawInfo(`[onBeforeEnter] /login`),
});

const contacts = document.getElementById("contacts");

const handleClickContacts = (e: Event) => {
e.preventDefault();

setTimeout(() => {
unsubscribe();
console.log(
`------ Произведена отписка от выполнения хуков при последующих кликах на ссылку - '/contacts' ------`
);
}, 0);

contacts?.removeEventListener("click", handleClickContacts);
};

contacts?.addEventListener("click", handleClickContacts);
};

const connectRouter = (mode: "hash" | "history") => {
const nav = document.getElementById("nav") as HTMLElement;
const root = document.getElementById("root") as HTMLElement;

nav.style.display = "flex";
root.style.display = "";

connectHooks(new Router(mode), mode);
};

window.addEventListener("load", () => {
const links = document.querySelectorAll(
"[data-name=terms]"
) as NodeListOf<HTMLAnchorElement>;

links.forEach((link) =>
link.addEventListener("click", () => {
if (link.dataset.id === "history") {
if (PRODUCTION) {
document.querySelectorAll("a").forEach((ref) => {
ref.href = PREFIX + ref.pathname;
});
}
}

connectRouter(link.dataset.id as "hash" | "history");

links.forEach((a) => {
a.remove();
});
})
);
});
22 changes: 0 additions & 22 deletions index.html

This file was deleted.

Loading

0 comments on commit 84af536

Please sign in to comment.