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
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
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 { CustomizableProjectItemUrlService } from './customizable-project-item-url.service';

describe('CustomizableProjectItemUrlService', () => {
let service: CustomizableProjectItemUrlService;
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: [
CustomizableProjectItemUrlService,
{ provide: Router, useValue: routerMock },
{ provide: UrlStateService, useValue: urlStateServiceMock },
],
});
});

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

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

it('returns null for isTopProject/compact by default', () => {
service = createService();

expect(service.getIsTopProject('project-id-1')).toBeNull();
expect(service.getCompact('project-id-1')).toBeNull();
});

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

expect(service.getIsTopProject('project-id-2')).toBe(true);
expect(service.getCompact('project-id-2')).toBeNull();
});

it('parses multiple projects with multiple properties from the URL', () => {
routerMock.url =
'/?customProjItems=project-id-2:(top:true);project-id-5:(compact:false);project-id-7:(top:false;compact:false)';
service = createService();

expect(service.getIsTopProject('project-id-2')).toBe(true);
expect(service.getCompact('project-id-2')).toBeNull();

expect(service.getIsTopProject('project-id-5')).toBeNull();
expect(service.getCompact('project-id-5')).toBe(false);

expect(service.getIsTopProject('project-id-7')).toBe(false);
expect(service.getCompact('project-id-7')).toBe(false);
});

it('ignores projects not present in the URL', () => {
routerMock.url = '/?customProjItems=project-id-2:(top:true)';
service = createService();

expect(service.getIsTopProject('unknown-project')).toBeNull();
expect(service.getCompact('unknown-project')).toBeNull();
});

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

expect(service.getIsTopProject('project-id-2')).toBe(true);
expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customProjItems: 'project-id-2:(top:true)',
});
});

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

expect(service.getCompact('project-id-5')).toBe(false);
expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customProjItems: 'project-id-5:(compact:false)',
});
});

it('merges multiple set properties for the same project', () => {
service = createService();
service.setIsTopProject('project-id-7', false);
service.setCompact('project-id-7', false);

expect(service.getIsTopProject('project-id-7')).toBe(false);
expect(service.getCompact('project-id-7')).toBe(false);
expect(urlStateServiceMock.updateValue).toHaveBeenLastCalledWith({
customProjItems: 'project-id-7:(top:false;compact:false)',
});
});

it('preserves customizations of other projects when setting a new one', () => {
routerMock.url = '/?customProjItems=project-id-2:(top:true)';
service = createService();
service.setCompact('project-id-5', false);

expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customProjItems: 'project-id-2:(top:true);project-id-5:(compact:false)',
});
});

it('serializes projects in stable project-id order independent of set order', () => {
service = createService();
service.setCompact('project-id-5', false);
service.setIsTopProject('project-id-2', true);

expect(urlStateServiceMock.updateValue).toHaveBeenLastCalledWith({
customProjItems: 'project-id-2:(top:true);project-id-5:(compact:false)',
});
});

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

service.setIsTopProject('project-id-2', true);

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

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

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

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

it('removes compact from URL when set to null and keeps other project values', () => {
service = createService();
service.setCompact('project-id-2', false);
service.setIsTopProject('project-id-5', true);
urlStateServiceMock.updateValue.mockClear();

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

expect(service.getCompact('project-id-2')).toBeNull();
expect(service.getIsTopProject('project-id-5')).toBe(true);
expect(urlStateServiceMock.updateValue).toHaveBeenCalledWith({
customProjItems: 'project-id-5:(top:true)',
});
});

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

expect(service.getIsTopProject('project-id-2')).toBe(true);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { DestroyRef, inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { UrlStateService } from '@portfolio/url-state';
import isEqual from 'lodash/isEqual';
import { distinctUntilChanged, filter, map } from 'rxjs';

interface ProjectItemCustomization {
isTopProject?: boolean | null;
compact?: boolean | null;
}

type CustomizationMap = Record<string, ProjectItemCustomization>;

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

/**
* Aggregates the customizations of all rendered `CustomizableProjectItemComponent`s
* into a single URL query param and keeps them in sync with URL changes.
*/
@Injectable({
providedIn: 'root',
})
export class CustomizableProjectItemUrlService {
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));
}

getIsTopProject(projectId: string): boolean | null {
return this.customizations()[projectId]?.isTopProject ?? null;
}

getCompact(projectId: string): boolean | null {
return this.customizations()[projectId]?.compact ?? null;
}

setIsTopProject(projectId: string, isTopProject: boolean | null): void {
this.updateCustomization(projectId, { isTopProject });
}

setCompact(projectId: string, compact: boolean | null): void {
this.updateCustomization(projectId, { compact });
}

private updateCustomization(
projectId: string,
partial: ProjectItemCustomization
): void {
const current = this.customizations();
const next: CustomizationMap = {
...current,
[projectId]: { ...current[projectId], ...partial },
};
Comment thread
Waog marked this conversation as resolved.

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 [, projectId, propsPart] = match;
const customization: ProjectItemCustomization = {};

for (const prop of propsPart.split(';')) {
const [key, value] = prop.split(':');
if (key === 'top') {
customization.isTopProject = value === 'true';
} else if (key === 'compact') {
customization.compact = value === 'true';
}
Comment thread
Waog marked this conversation as resolved.
}

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

return result;
}

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

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

return [...entries]
.sort(([projectIdA], [projectIdB]) =>
projectIdA.localeCompare(projectIdB)
)
.map(([projectId, customization]) => {
const props: string[] = [];
if (customization.isTopProject != null) {
props.push(`top:${customization.isTopProject}`);
}
if (customization.compact != null) {
props.push(`compact:${customization.compact}`);
}
return `${projectId}:(${props.join(';')})`;
})
.join(';');
}
}
Loading
Loading