Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated to Typescript and Vue 3 compatibility #37

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 0 additions & 12 deletions .eslintrc.js

This file was deleted.

1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'vue-smart-route';
51 changes: 18 additions & 33 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
{
"name": "vue-smart-route",
"version": "0.3.2",
"version": "0.4.0",
"description": "Smart Router for vue-router",
"main": "dist/vue-smart-route.js",
"main": "dist/index.js",
"files": [
"dist"
"dist",
"index.d.ts"
],
"scripts": {
"test": "exit 0;",
"build": "poi src/vue-smart-route.js --prod --format umd --module-name VueSmartRoute --file-names.js vue-smart-route.js",
"dev": "poi example/main.js --serve",
"gh-pages": "poi example/main.js --prod --public-url ./ --out-dir=example/dist && gh-pages -d example/dist"
"build": "rollup -c",
"prepublishOnly": "yarn build"
},
"repository": {
"type": "git",
Expand All @@ -27,35 +26,21 @@
"url": "https://github.com/f/vue-smart-route/issues"
},
"homepage": "https://github.com/f/vue-smart-route#readme",
"lint-staged": {
"src/**/*.js": [
"prettier --single-quote --write",
"git add"
],
"example/**/*.js": [
"prettier --single-quote --write",
"git add"
]
},
"peerDependencies": {
"vue": "^2.5.17",
"vue-router": "^3.0.2"
"tslib": "^2.6.0",
"vue": "^3.3.4",
"vue-router": "^4.2.4"
},
"devDependencies": {
"cross-env": "^5.2.0",
"eslint": "^5.9.0",
"gh-pages": "^2.0.1",
"husky": "^1.2.0",
"lint-staged": "^8.1.0",
"poi": "^12.0.0-beta.6",
"prettier": "^1.15.3",
"vue": "^2.5.17",
"vue-router": "^3.0.2",
"vue-template-compiler": "^2.5.17"
"vue": "^3.3.4",
"vue-router": "^4.2.4"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
"dependencies": {
"rollup": "^3.26.2",
"rollup-plugin-clear": "^2.0.7",
"rollup-plugin-typescript": "^1.0.1",
"rollup-plugin-typescript2": "^0.35.0",
"rollup-plugin-vue": "^6.0.0",
"typescript": "^5.1.6"
}
}
20 changes: 20 additions & 0 deletions rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import typescript from 'rollup-plugin-typescript2';
import vue from 'rollup-plugin-vue';
import clear from 'rollup-plugin-clear';

export default {
input: 'src/index.ts',
output: {
dir: 'dist',
format: 'esm',
},
external: ['vue'],
plugins: [
typescript({
experimentalDecorators: true,
module: 'esnext',
clean: true,
}),
vue()
],
}
115 changes: 115 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import type { App, AppConfig } from 'vue'
import { ref } from 'vue'
import {
Query,
SplitMatchResult,
SmartRouteMetaOptions,
SmartRouteRecord
} from './types'

function flattenRoutes(routes: SmartRouteRecord[] = [], level: number = 0): SmartRouteRecord[] {
if (Array.isArray(routes)) {
return routes.reduce(
(accumulator: SmartRouteRecord[], { name, path, children = [], meta }) => {
const newMeta = { ...meta, level }
accumulator.push({ name, path, children, meta: newMeta });
if (children && children.length) {
accumulator = accumulator.concat(flattenRoutes(children, level + 1));
}
return accumulator;
},
[]
);
}
return [];
}

function splitMatch(path: string, query: Query): SplitMatchResult {
const matches = path.match(/(:[0-9a-z_\-]+)/gi);
if (!matches) return { query, params: {} };

const params = matches.map(m => m.slice(1).trim());
const splitted: SplitMatchResult = { query: {}, params: {} };
Object.keys(query).forEach(key => {
splitted[params.includes(key) ? 'params' : 'query'][key] = query[key];
});
return splitted;
}

function buildRoute(route: any, title: string, smart: SmartRouteMetaOptions, next: Function) {
return {
...route,
title: title.replace(/\*([^*]+)\*/g, '<mark>$1</mark>'),
handler: () => smart.handler!(route, next)
};
}

async function findSmartRoutes(value: string, config: AppConfig) {

const routes: SmartRouteRecord[] = config.globalProperties.$router.getRoutes();

const allRoutes = flattenRoutes(routes);

// Find Smart Routes
const smartRoutes = allRoutes
.filter(route => route.meta?.smart)
.map(({ name, path, meta }) => ({ name, path, meta }));

// Find Matching Routes with the Value
const matchingRoutes = smartRoutes.map(async ({ name, path, meta }) => {
if (!meta?.smart || !meta?.smart.matcher) {
throw new Error('Smart routes must have matchers!');
}

const next = (route: any) => config.globalProperties.$router.push(route);
if (!meta?.smart.handler) {
meta.smart.handler = next;
}

const matching = (typeof meta?.smart.matcher.search === 'function'
? meta?.smart.matcher.search(config.globalProperties)
: meta?.smart.matcher.search
)
.map((matcher: any) => value.toString().match(matcher))
.filter(Boolean);

const routes = await Promise.all(
matching.map(async (match: any) => {
if (!match) return;
const query = match.groups ? match.groups : match;
const route = {
name,
path,
...splitMatch(path, match.groups)
};

if (typeof meta.smart?.matcher?.routes === 'function') {
const routesToBuild = await meta?.smart.matcher.routes(query);
return routesToBuild.map((r: any) => buildRoute(r, r.title, meta?.smart!, next));
}

const title = meta?.smart?.matcher?.title(query);
return buildRoute(route, title!, meta?.smart!, next);
})
);
return [].concat.apply([], routes).filter(Boolean);
});
const doneRoutes = await Promise.all(matchingRoutes);
return [].concat(...doneRoutes);
}


export default {
install(app: App) {
const valueRef = ref('');
app.directive('smart-routes', {
async updated(el, binding, vnode: any, oldVnode: any) {
if (valueRef.value != el.value) {
valueRef.value = el.value;
const smartRoutes = await findSmartRoutes(String(el.value), app.config);
binding.value(smartRoutes)
}
}
});
}
}
29 changes: 29 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { RouteRecordRaw } from 'vue-router';

export interface Query {
[key: string]: any;
}

export interface SplitMatchResult {
query: Query;
params: Query;
}

export interface SmartRouteMetaOptions {
handler?: (route: SmartRouteRecord, next: Function) => void;
matcher?: {
search: any;
title: (query: Query) => string;
routes?: (query: Query) => Promise<any[]>;
};
}

export interface SmartRouteMeta {
smart?: SmartRouteMetaOptions;
level?: number;
}

export type SmartRouteRecord = RouteRecordRaw & {
meta?: SmartRouteMeta;
children?: SmartRouteRecord[];
};
106 changes: 0 additions & 106 deletions src/vue-smart-route.js

This file was deleted.

Loading