Skip to content

Commit

Permalink
feat(route): new url method
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Jan 29, 2023
1 parent 2b26a8d commit 580f2b3
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
54 changes: 52 additions & 2 deletions core/router/src/core.ts
Original file line number Diff line number Diff line change
@@ -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<RouteContext>('route-context');
Expand Down Expand Up @@ -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
* <a href=${ url({sectionList: ['product', 100]}) }>
* ```
*/
export function url(route: Partial<Pick<RouteContext, 'sectionList' | 'queryParamList' | 'hash'>>): 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<string> = [];
for (const key of Object.keys(parameterList)) {
list.push(`${key}=${String(parameterList[key])}`);
}
return '?' + list.join('&');
}
2 changes: 1 addition & 1 deletion core/router/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export {routerOutlet, routeContextConsumer} from './core.js';
export {routerOutlet, routeContextConsumer, url} from './core.js';

0 comments on commit 580f2b3

Please sign in to comment.