feat(): Add possible to switch navigation type

Use queryParam navigation type
This commit is contained in:
Depickere Sven 2023-02-21 14:52:52 +01:00
parent 33be51a7a4
commit de146726dd
2 changed files with 38 additions and 5 deletions

View File

@ -1,26 +1,36 @@
import { bind, debounce } from 'decko';
import { EventEmitter } from 'eventemitter3';
import { IS_BROWSER } from '../utils/';
import { RedocNormalizedOptions } from './RedocNormalizedOptions';
const EVENT = 'hashchange';
export class HistoryService {
private _emiter;
private options: RedocNormalizedOptions;
constructor() {
constructor(options: RedocNormalizedOptions) {
this.options = options;
this._emiter = new EventEmitter();
this.bind();
}
get currentId(): string {
return IS_BROWSER ? decodeURIComponent(window.location.hash.substring(1)) : '';
if (IS_BROWSER) {
if (this.shouldQueryParamNavigationBeUsed()) {
return this.getQueryParams(window.location.search);
} else {
return decodeURIComponent(window.location.hash.substring(1));
}
}
return '';
}
linkForId(id: string) {
if (!id) {
return '';
}
return '#' + id;
return this.getHrefSplitCharacter() + id;
}
subscribe(cb): () => void {
@ -58,14 +68,34 @@ export class HistoryService {
window.history.replaceState(
null,
'',
window.location.href.split('#')[0] + this.linkForId(id),
window.location.href.split(this.getHrefSplitCharacter())[0] + this.linkForId(id),
);
return;
}
window.history.pushState(null, '', window.location.href.split('#')[0] + this.linkForId(id));
window.history.pushState(
null,
'',
window.location.href.split(this.getHrefSplitCharacter())[0] + this.linkForId(id),
);
this.emit();
}
private shouldQueryParamNavigationBeUsed(): boolean {
return this.options?.userQueryParamToNavigate;
}
private getQueryParams(search: string): string {
const queryParams = new URLSearchParams(search);
if (search != null) {
return queryParams.get('redoc') != null ? (queryParams.get('redoc') as string) : '';
}
return '';
}
private getHrefSplitCharacter(): string {
return this.shouldQueryParamNavigationBeUsed() ? '#' : '?redoc';
}
}
export const history = new HistoryService();

View File

@ -56,6 +56,7 @@ export interface RedocRawOptions {
hideFab?: boolean;
minCharacterLengthToInitSearch?: number;
showWebhookVerb?: boolean;
userQueryParamToNavigate?: boolean;
}
export function argValueToBoolean(val?: string | boolean, defaultValue?: boolean): boolean {
@ -256,6 +257,7 @@ export class RedocNormalizedOptions {
hideFab: boolean;
minCharacterLengthToInitSearch: number;
showWebhookVerb: boolean;
userQueryParamToNavigate: boolean;
nonce?: string;
@ -335,5 +337,6 @@ export class RedocNormalizedOptions {
this.hideFab = argValueToBoolean(raw.hideFab);
this.minCharacterLengthToInitSearch = argValueToNumber(raw.minCharacterLengthToInitSearch) || 3;
this.showWebhookVerb = argValueToBoolean(raw.showWebhookVerb);
this.userQueryParamToNavigate = argValueToBoolean(raw.userQueryParamToNavigate);
}
}