From 580f2b34396461389da0126d64c3c6ffde99e87b Mon Sep 17 00:00:00 2001 From: Ali Mihandoost Date: Sun, 29 Jan 2023 16:24:15 +0330 Subject: [PATCH] feat(route): new url method --- core/router/src/core.ts | 54 ++++++++++++++++++++++++++++++++++++++-- core/router/src/index.ts | 2 +- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/core/router/src/core.ts b/core/router/src/core.ts index 1c79bb40c..7e1a30a53 100644 --- a/core/router/src/core.ts +++ b/core/router/src/core.ts @@ -1,10 +1,16 @@ -import {createLogger} from '@alwatr/logger'; +import {createLogger, globalAlwatr} from '@alwatr/logger'; import {isNumber} from '@alwatr/math'; import {contextConsumer} from '@alwatr/signal'; -import {ParamValueType} from '@alwatr/type'; import {RouteContext, RoutesConfig} from './type.js'; +import type {ParamValueType, QueryParameters} from '@alwatr/type'; + +globalAlwatr.registeredList.push({ + name: '@alwatr/router', + version: _ALWATR_VERSION_, +}); + export const logger = createLogger('alwatr/router'); export const routeContextConsumer = contextConsumer.bind('route-context'); @@ -98,3 +104,47 @@ export function sanitizeValue(value?: string | null): ParamValueType { // else return value; } + +const documentBaseUrl = document.querySelector('base')?.href || '/'; + +/** + * Make anchor valid href from RouteContext format. + * + * Example: + * + * ```html + * + * ``` + */ +export function url(route: Partial>): string { + logger.logMethodArgs('url', {route}); + + let href = ''; + + if (Array.isArray(route.sectionList) && route.sectionList.length > 0) { + href += documentBaseUrl + route.sectionList.join('/'); + } + + href += toQueryParamString(route.queryParamList); + + if (route.hash != null && route.hash !== '') { + if (route.hash.indexOf('#') !== 0) { + route.hash = '#' + route.hash; + } + href += route.hash; + } + + return href; +} + +/** + * Make query string from QueryParameters object. + */ +export function toQueryParamString(parameterList?: QueryParameters): string { + if (parameterList == null) return ''; + const list: Array = []; + for (const key of Object.keys(parameterList)) { + list.push(`${key}=${String(parameterList[key])}`); + } + return '?' + list.join('&'); +} diff --git a/core/router/src/index.ts b/core/router/src/index.ts index 2768f9eca..51d9a5b5a 100644 --- a/core/router/src/index.ts +++ b/core/router/src/index.ts @@ -1 +1 @@ -export {routerOutlet, routeContextConsumer} from './core.js'; +export {routerOutlet, routeContextConsumer, url} from './core.js';