Skip to content
Merged
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
1 change: 1 addition & 0 deletions libs/feature/customizable-color-chip-list/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './lib/customizable-color-chip-list.component';
export * from './lib/customizable-color-chip-list-url.service';
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import { TestBed } from '@angular/core/testing';
import {
DefaultUrlSerializer,
NavigationEnd,
Router,
UrlTree,
} from '@angular/router';
import { UrlStateService } from '@portfolio/url-state';
import { Subject } from 'rxjs';

import { CustomizableColorChipListUrlService } from './customizable-color-chip-list-url.service';

describe('CustomizableColorChipListUrlService', () => {
let service: CustomizableColorChipListUrlService;
let routerMock: {
url: string;
events: Subject<NavigationEnd>;
parseUrl: (url: string) => UrlTree;
};
let urlStateServiceMock: { updateValue: jest.Mock };

beforeEach(() => {
const urlSerializer = new DefaultUrlSerializer();

routerMock = {
url: '/',
events: new Subject<NavigationEnd>(),
parseUrl: (url: string) => urlSerializer.parse(url),
};

urlStateServiceMock = {
updateValue: jest.fn(),
};

TestBed.configureTestingModule({
providers: [
CustomizableColorChipListUrlService,
{ provide: Router, useValue: routerMock },
{ provide: UrlStateService, useValue: urlStateServiceMock },
],
});
});

function createService(): CustomizableColorChipListUrlService {
return TestBed.inject(CustomizableColorChipListUrlService);
}

it('can create', () => {
service = createService();
expect(service).toBeInstanceOf(CustomizableColorChipListUrlService);
});

it('returns null for spacing and rows by default', () => {
service = createService();

expect(service.getSpacing('project-id-1')).toBeNull();
expect(service.getRows('project-id-1')).toBeNull();
});

it('parses a single component with a single property from the URL', () => {
routerMock.url = '/?customColorChipLists=project-id-2:(spacing:small)';
service = createService();

expect(service.getSpacing('project-id-2')).toBe('small');
expect(service.getRows('project-id-2')).toBeNull();
});

it('parses multiple components with multiple properties from the URL', () => {
routerMock.url =
'/?customColorChipLists=project-id-2:(spacing:small);project-id-5:(rows:3);project-id-7:(spacing:medium;rows:4)';
service = createService();

expect(service.getSpacing('project-id-2')).toBe('small');
expect(service.getRows('project-id-2')).toBeNull();

expect(service.getSpacing('project-id-5')).toBeNull();
expect(service.getRows('project-id-5')).toBe(3);

expect(service.getSpacing('project-id-7')).toBe('medium');
expect(service.getRows('project-id-7')).toBe(4);
});

it('ignores entries without a recognized customization', () => {
routerMock.url = '/?customColorChipLists=project-id-2:(unknown:value)';
service = createService();

expect(service.getSpacing('project-id-2')).toBeNull();
expect(service.getRows('project-id-2')).toBeNull();
});

it('can set spacing explicitly and pushes the serialized param to the URL', () => {
service = createService();
service.setSpacing('project-id-2', 'small');

expect(service.getSpacing('project-id-2')).toBe('small');
expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customColorChipLists: 'project-id-2:(spacing:small)',
});
});

it('can set rows explicitly and pushes the serialized param to the URL', () => {
service = createService();
service.setRows('project-id-5', 3);

expect(service.getRows('project-id-5')).toBe(3);
expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customColorChipLists: 'project-id-5:(rows:3)',
});
});

it('merges multiple set properties for the same component', () => {
service = createService();
service.setSpacing('project-id-7', 'large');
service.setRows('project-id-7', 4);

expect(service.getSpacing('project-id-7')).toBe('large');
expect(service.getRows('project-id-7')).toBe(4);
expect(urlStateServiceMock.updateValue).toHaveBeenLastCalledWith({
customColorChipLists: 'project-id-7:(spacing:large;rows:4)',
});
});

it('preserves customizations of other components when setting a new one', () => {
routerMock.url = '/?customColorChipLists=project-id-2:(spacing:small)';
service = createService();
service.setRows('project-id-5', 3);

expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customColorChipLists:
'project-id-2:(spacing:small);project-id-5:(rows:3)',
});
});

it('serializes components in stable key order independent of set order', () => {
service = createService();
service.setRows('project-id-5', 3);
service.setSpacing('project-id-2', 'small');

expect(urlStateServiceMock.updateValue).toHaveBeenLastCalledWith({
customColorChipLists:
'project-id-2:(spacing:small);project-id-5:(rows:3)',
});
});

it('does not update the URL when setting the same value again', () => {
service = createService();
service.setSpacing('project-id-2', 'small');
urlStateServiceMock.updateValue.mockClear();

service.setSpacing('project-id-2', 'small');

expect(urlStateServiceMock.updateValue).not.toHaveBeenCalled();
});

it('removes spacing from URL when set to null', () => {
service = createService();
service.setSpacing('project-id-2', 'small');
urlStateServiceMock.updateValue.mockClear();

service.setSpacing('project-id-2', null);

expect(service.getSpacing('project-id-2')).toBeNull();
expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customColorChipLists: null,
});
});

it('removes rows from URL when set to null and keeps other component values', () => {
service = createService();
service.setRows('project-id-2', 3);
service.setSpacing('project-id-5', 'medium');
urlStateServiceMock.updateValue.mockClear();

service.setRows('project-id-2', null);

expect(service.getRows('project-id-2')).toBeNull();
expect(service.getSpacing('project-id-5')).toBe('medium');
expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customColorChipLists: 'project-id-5:(spacing:medium)',
});
});

it('syncs customizations when the URL changes through navigation', () => {
service = createService();
routerMock.url =
'/?customColorChipLists=project-id-2:(spacing:small;rows:3)';
routerMock.events.next(
new NavigationEnd(1, routerMock.url, routerMock.url)
);

expect(service.getSpacing('project-id-2')).toBe('small');
expect(service.getRows('project-id-2')).toBe(3);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { DestroyRef, inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { ChipSpacing } from '@portfolio/color-chip';
Comment thread
Waog marked this conversation as resolved.
import { UrlStateService } from '@portfolio/url-state';
import isEqual from 'lodash/isEqual';
import { distinctUntilChanged, filter, map } from 'rxjs';

interface ColorChipListCustomization {
spacing?: ChipSpacing | null;
rows?: number | null;
}

type CustomizationMap = Record<string, ColorChipListCustomization>;

const QUERY_PARAM = 'customColorChipLists';
const ENTRY_PATTERN = /([^;()]+):\(([^)]*)\)/g;

/**
* Aggregates the customizations of all rendered
* `CustomizableColorChipListComponent`s into a single URL query param and
* keeps them in sync with URL changes.
*/
@Injectable({
providedIn: 'root',
})
export class CustomizableColorChipListUrlService {
private readonly router = inject(Router);
private readonly urlStateService = inject(UrlStateService);
private readonly destroyRef = inject(DestroyRef);

private readonly customizations = signal<CustomizationMap>(
this.getCustomizationsFromCurrentUrl()
);

constructor() {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.getCustomizationsFromCurrentUrl()),
distinctUntilChanged(isEqual),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(customizations => this.customizations.set(customizations));
}

getSpacing(urlPersistenceKey: string): ChipSpacing | null {
return this.customizations()[urlPersistenceKey]?.spacing ?? null;
}

getRows(urlPersistenceKey: string): number | null {
return this.customizations()[urlPersistenceKey]?.rows ?? null;
}

setSpacing(urlPersistenceKey: string, spacing: ChipSpacing | null): void {
this.updateCustomization(urlPersistenceKey, { spacing });
}

setRows(urlPersistenceKey: string, rows: number | null): void {
this.updateCustomization(urlPersistenceKey, { rows });
}

private updateCustomization(
urlPersistenceKey: string,
partial: ColorChipListCustomization
): void {
const current = this.customizations();
const next: CustomizationMap = {
...current,
[urlPersistenceKey]: { ...current[urlPersistenceKey], ...partial },
};

if (isEqual(current, next)) {
return;
}

this.customizations.set(next);
this.urlStateService.updateValue({
[QUERY_PARAM]: this.toUrlParam(next),
});
}

private getCustomizationsFromCurrentUrl(): CustomizationMap {
const urlTree = this.router.parseUrl(this.router.url);
return this.parseUrlParam(urlTree.queryParams[QUERY_PARAM] ?? null);
}

private parseUrlParam(param: string | null): CustomizationMap {
const result: CustomizationMap = {};
if (!param) {
return result;
}

for (const match of param.matchAll(ENTRY_PATTERN)) {
const [, urlPersistenceKey, propsPart] = match;
const customization: ColorChipListCustomization = {};

for (const prop of propsPart.split(';')) {
const [key, value] = prop.split(':');
if (key === 'spacing' && this.isChipSpacing(value)) {
customization.spacing = value;
} else if (key === 'rows') {
const rows = Number(value);
if (Number.isInteger(rows) && rows > 0) {
customization.rows = rows;
}
}
}

if (Object.keys(customization).length > 0) {
result[urlPersistenceKey] = customization;
}
}

return result;
}

private toUrlParam(customizations: CustomizationMap): string | null {
const entries = Object.entries(customizations).filter(
([, customization]) =>
customization.spacing != null || customization.rows != null
);

if (entries.length === 0) {
return null;
}

return [...entries]
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
.map(([urlPersistenceKey, customization]) => {
const props: string[] = [];
if (customization.spacing != null) {
props.push(`spacing:${customization.spacing}`);
}
if (customization.rows != null) {
props.push(`rows:${customization.rows}`);
}
return `${urlPersistenceKey}:(${props.join(';')})`;
})
.join(';');
}

private isChipSpacing(value: string): value is ChipSpacing {
return value === 'small' || value === 'medium' || value === 'large';
}
}
Loading
Loading