Skip to content
This repository has been archived by the owner on Jan 14, 2022. It is now read-only.

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
nikitakoschelenko committed Nov 1, 2021
0 parents commit dc35c14
Show file tree
Hide file tree
Showing 14 changed files with 1,804 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"sourceType": "module"
},
"plugins": [
"@typescript-eslint/eslint-plugin"
],
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"root": true,
"env": {
"node": true,
"jest": true
},
"rules": {
"@typescript-eslint/interface-name-prefix": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-non-null-assertion": "off"
}
}
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*

lib/
node_modules/
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "none"
}
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) 2021 cteam

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.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# router
🔪 Многофункциональный роутер для приложений на React и VKUI
39 changes: 39 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "@cteamdev/router",
"version": "0.0.1",
"description": "🔪 Многофункциональный роутер для приложений на React и VKUI",
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"types": "./lib/esm/index.d.ts",
"repository": "https://github.com/cteamdev/router",
"author": "ItzNeviKat",
"license": "MIT",
"files": [
"/lib"
],
"scripts": {
"build": "yarn build:esm && yarn build:cjs",
"build:esm": "tsc",
"build:cjs": "tsc --module commonjs --outDir lib/cjs"
},
"devDependencies": {
"@types/react": "^17.0.33",
"@types/react-dom": "^17.0.10",
"@typescript-eslint/eslint-plugin": "^5.2.0",
"@typescript-eslint/parser": "^5.2.0",
"eslint": "^8.1.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.26.1",
"prettier": "^2.4.1",
"typescript": "^4.4.4"
},
"peerDependencies": {
"@vkontakte/vkui": "^4.20.0",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"dependencies": {
"querystring": "^0.2.1"
}
}
75 changes: 75 additions & 0 deletions src/components.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { FC, DetailedReactHTMLElement } from 'react';

import React, { Children, useEffect, useState, cloneElement } from 'react';
import {
Root as VKUIRoot,
Epic as VKUIEpic,
View as VKUIView,
RootProps,
EpicProps,
ViewProps
} from '@vkontakte/vkui';

import { Router } from './router';
import { RouterContext } from './context';

type RouterProps = {
value: Router;
};

export const RouterProvider: FC<RouterProps> = ({ value, children }) => {
const [, setState] = useState(value.state);

useEffect(() => value.subscribe((_, state) => setState(state)), []);

return (
<RouterContext.Provider value={value}>
{Children.map(children, (child) =>
cloneElement(child as DetailedReactHTMLElement<any, HTMLElement>, null)
)}
</RouterContext.Provider>
);
};

export const Root = (props: Omit<RootProps, 'activeView'>) => (
<RouterContext.Consumer>
{(router) =>
router && (
<VKUIRoot activeView={router.state.view} {...props}>
{props.children}
</VKUIRoot>
)
}
</RouterContext.Consumer>
);

export const Epic = (props: Omit<EpicProps, 'activeStory'>) => (
<RouterContext.Consumer>
{(router) =>
router && (
<VKUIEpic activeStory={router.state.view} {...props}>
{props.children}
</VKUIEpic>
)
}
</RouterContext.Consumer>
);

export const View = (
props: Omit<ViewProps, 'activePanel' | 'history' | 'onSwipeBack'>
) => (
<RouterContext.Consumer>
{(router) =>
router && (
<VKUIView
activePanel={router.state.panel}
history={router.viewHistory}
onSwipeBack={router.back}
{...props}
>
{props.children}
</VKUIView>
)
}
</RouterContext.Consumer>
);
5 changes: 5 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createContext } from 'react';

import { Router } from './router';

export const RouterContext = createContext<Router | null>(null);
19 changes: 19 additions & 0 deletions src/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useContext } from 'react';

import { RouterContext } from './context';
import { Meta, Params } from './types';

export const useRouter = () => useContext(RouterContext)!;

// TODO: Смена параметров при анимации
export const useParams = <T extends Params>(): T => {
const router = useRouter();

return (router.state.params as T) ?? {};
};

export const useMeta = <T extends Meta>(): T => {
const router = useRouter();

return (router.state.meta as T) ?? {};
};
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export * from './router';
export * from './context';
export * from './hooks';
export * from './components';
export * from './types';
135 changes: 135 additions & 0 deletions src/router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { parse } from 'querystring';

import {
Options,
State,
RootStructure,
Subscriber,
Unsubscriber,
UnknownStructure,
Mode,
Params,
Meta,
RouterEvent
} from './types';

export class Router {
public state: State = this.parse(this.options.defaultRoute);

public history: State[] = [this.state];
public subscribers: Subscriber[] = [];

constructor(
public readonly structure: RootStructure,
public readonly options: Options
) {
history.replaceState(
this.state,
this.options.defaultRoute,
this.getUrl(this.options.defaultRoute)
);

window.onpopstate = this.onPopState.bind(this);
}

public get viewHistory(): string[] {
const view: string = this.state.view;

return this.history
.filter((state) => state.view === view)
.map((state) => state.panel);
}

public subscribe(subscriber: Subscriber): Unsubscriber {
this.subscribers.push(subscriber);

return () => {
this.subscribers = this.subscribers.filter(
(currentSubscriber) => currentSubscriber !== subscriber
);
};
}

public push(path: string, meta?: Meta): void {
const state: State = this.parse(path, meta);
state.id = Math.floor(Math.random() * 9999) + 1;

history.pushState(state, path, this.getUrl(path));
this.history.push(state);

this.emit(RouterEvent.PUSH, state);
}

public back(): void {
history.back();
}

public go(delta: number): void {
history.go(delta);
}

public onPopState({ state }: PopStateEvent): void {
if (this.history.some((currentState) => currentState.id === state.id)) {
this.history.pop();
this.emit(RouterEvent.BACK, state);
} else {
this.history.push(state);
this.emit(RouterEvent.PUSH, state);
}
}

public createState(params?: Params, meta?: Meta): State {
return {
view: '/',
panel: '/',

id: 0,

meta: meta ?? {},
params: params ?? {}
};
}

public emit(event: RouterEvent, state: State): void {
this.state = state;
this.subscribers.forEach((subscriber) => subscriber(event, state));
}

public getUrl(path: string): string {
const urls: Record<Mode, string> = {
hash: '#' + path,
none: '',
path
};

return urls[this.options.mode];
}

public parse(path: string, meta?: Meta): State {
const [nav, params] = path.split('?');

const state: State = this.createState(
params ? (parse(params) as Params) : undefined,
meta
);

let navIndex: number = 0;
const navs: string[] = nav
.split('/')
.map((nav) => (nav.startsWith('/') ? nav : '/' + nav))
.slice(1);

const iterate = (structure: UnknownStructure): void => {
if ('nav' in structure && structure.nav === navs[navIndex]) {
state[structure.type] = structure.nav;
navIndex++;
}

if ('children' in structure)
for (const child of structure.children) iterate(child);
};
iterate(this.structure);

return state;
}
}
45 changes: 45 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
export type Mode = 'none' | 'path' | 'hash';

export type Options = {
mode: Mode;
defaultRoute: string;
};

export type Params = Record<string, string>;
export type Meta = Record<string, unknown>;

export type State = {
view: string;
panel: string;

id: number | null;

params: Params;
meta: Meta;
};

export enum RouterEvent {
BACK,
PUSH,
REPLACE
}
export type Unsubscriber = () => void;
export type Subscriber = (event: RouterEvent, state: State) => void;

export type RootStructure = {
type: 'epic' | 'root';
children: ViewStructure[];
};

export type ViewStructure = {
type: 'view';
nav: string;
children: PanelStructure[];
};

export type PanelStructure = {
type: 'panel';
nav: string;
};

export type UnknownStructure = RootStructure | ViewStructure | PanelStructure;
Loading

0 comments on commit dc35c14

Please sign in to comment.