feat(ui): refresh the planner interface #361

Merged
nessar merged 12 commits from feature/planner-ui-refresh into develop 2026-11-14 16:42:38 +01:00
13 changed files with 561 additions and 1 deletions
Showing only changes of commit b165245aa0 - Show all commits

No files matched your search

@@ -2710,6 +2710,161 @@ describe('CalendarYear planning outcome boundary', () => {
},
);
describe('time-off period list', () => {
const periods: PlanOutcome = {
...plan,
timeOffPeriods: [
{
start: '2024-05-04',
end: '2024-05-08',
duration: 5,
placementDates: ['2024-05-06'],
nonWorkingDates: ['2024-05-04', '2024-05-05', '2024-05-07', '2024-05-08'],
nonWorkingDayGain: 4,
},
// Plain weekend: no leave placement and no declared day, so not listed.
{
start: '2024-05-11',
end: '2024-05-12',
duration: 2,
placementDates: [],
nonWorkingDates: ['2024-05-11', '2024-05-12'],
nonWorkingDayGain: 2,
},
{
start: '2024-05-02',
end: '2024-05-03',
duration: 2,
placementDates: ['2024-05-03'],
declaredDates: ['2024-05-02'],
nonWorkingDates: [],
nonWorkingDayGain: 0,
},
],
};
async function show(outcome: PlanningOutcome, explained?: PlanningExplanation) {
const { calendar, creation } = calendarFor(outcome, explained);
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
spyOnCreation().mockImplementation(creation);
TestBed.inject(TranslationService).setLanguage('en');
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
return {
fixture,
root,
details: root.querySelector<HTMLDetailsElement>(
'.plan-insights > .time-off-periods',
),
};
}
it('lists the periods with leave in a closed disclosure among the others', async () => {
const { fixture, root, details } = await show(periods, explanation);
expect(details!.open).toBe(false);
const summary = details!.querySelector('summary')!.textContent?.replace(/\s+/g, ' ');
expect(summary).toContain('Your time-off periods');
expect(summary).toContain('Periods : 2');
const translation = TestBed.inject(TranslationService);
for (const [language, copy] of Object.entries(translationsMap)) {
translation.setLanguage(language);
fixture.detectChanges();
const shown = details!.querySelector('summary')!.textContent;
expect(shown).toContain(copy.planning.timeOffPeriods.title);
expect(shown).toContain(copy.planning.timeOffPeriods.count);
expect(details!.querySelector('.help')!.textContent).toBe(
copy.planning.timeOffPeriods.help,
);
}
expect(
[...details!.querySelectorAll<HTMLElement>('li > button')].map(
(b) => b.dataset['start'],
),
).toEqual(['2024-05-02', '2024-05-04']);
const follows = (earlier: Element, later: Element) =>
Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING);
expect(follows(root.querySelector('.plan-summary')!, details!)).toBe(true);
expect(follows(root.querySelector('.plan-details')!, details!)).toBe(true);
expect(follows(details!, root.querySelector('.month-grid')!)).toBe(true);
});
it.each([
['without any period', plan],
[
'without a period with leave',
{ ...periods, timeOffPeriods: [periods.timeOffPeriods[1]] },
],
['without a plan', { kind: 'InvalidInput', reasons: [] } as PlanningOutcome],
])('is absent %s', async (_label, outcome) => {
const { root, details } = await show(outcome);
expect(details).toBeNull();
expect(root.querySelector('app-time-off-periods')).toBeNull();
});
it('follows the partial plan of an interrupted calculation', async () => {
const { details } = await show({
kind: 'PlanningIncomplete',
incumbent: periods,
completedStages: [],
reasons: [{ code: 'user-cancelled', message: 'Cancelled' }],
});
expect(details!.querySelectorAll('li > button')).toHaveLength(2);
});
describe.each([
[false, 'smooth'],
[true, 'auto'],
])('choosing a period (reduced motion: %s)', (reduced, behavior) => {
const scrollIntoView = vi.fn();
beforeEach(() => {
scrollIntoView.mockClear();
Element.prototype.scrollIntoView = scrollIntoView;
const base = window.matchMedia('(prefers-reduced-motion: reduce)');
vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({
...base,
matches: reduced,
media: query,
}));
});
afterEach(() => {
vi.restoreAllMocks();
delete (Element.prototype as Partial<Element>).scrollIntoView;
});
it('scrolls to its first leave day and focuses it', async () => {
const { fixture, details } = await show(periods, explanation);
// A keyboard user opens the disclosure, then activates the second period.
activateWithKeyboard(details!.querySelector('summary')!);
const [, second] = details!.querySelectorAll<HTMLButtonElement>('li > button');
activateWithKeyboard(second);
fixture.detectChanges();
const day = fixture.nativeElement.querySelector('button[data-date="2024-05-06"]');
expect(document.activeElement).toBe(day);
expect(scrollIntoView).toHaveBeenCalledOnce();
expect(scrollIntoView.mock.contexts[0]).toBe(day);
expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior });
});
it('prefers a declared day when it comes first', async () => {
const { fixture, details } = await show(periods, explanation);
activateWithKeyboard(details!.querySelector<HTMLButtonElement>('li > button')!);
expect(document.activeElement).toBe(
fixture.nativeElement.querySelector('button[data-date="2024-05-02"]'),
);
});
});
});
it('shows muted, disabled context dates in an adjacent year', async () => {
if (explanation.kind !== 'PlanExplanation') throw new Error('Expected plan explanation');
const boundaryPlan: PlanOutcome = {
@@ -563,6 +563,23 @@
</div>
</details>
}
@if (timeOffPeriodCount(); as count) {
<details class="time-off-periods">
<summary>
<mat-icon aria-hidden="true">date_range</mat-icon>
<span
>{{ tr().planning.timeOffPeriods.title
}}<small
>{{ tr().planning.timeOffPeriods.count }} : {{ count }}</small
></span
>
<mat-icon class="disclosure-chevron" aria-hidden="true"
>expand_more</mat-icon
>
</summary>
<app-time-off-periods [plan]="plan" (dateChosen)="showDate($event)" />
</details>
}
}
</div>
@@ -110,10 +110,12 @@ code {
.plan-insights {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
// Closed disclosures share a row (three on a wide screen); an open one takes the full row.
grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr));
align-items: start;
gap: 0.75rem;
> details {
container-type: inline-size;
min-width: 0;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-md);
@@ -151,6 +153,20 @@ code {
font-weight: 400;
}
}
// Three disclosures share a wide row: drop the decorative icon to keep the row as low as two.
@container (max-width: 20rem) {
> summary {
gap: 0.5rem;
padding: 0.625rem 0.875rem;
min-height: 0;
> mat-icon:first-child {
display: none;
}
small {
margin-top: 0.125rem;
}
}
}
&[open] {
grid-column: 1 / -1;
> summary {
@@ -27,6 +27,7 @@ import {
import { CalendarMonth, DeclarationPreview } from '../calendar-month/calendar-month';
import { DateComparison } from '../date-comparison/date-comparison';
import { PlanningCriteria } from '../planning-criteria/planning-criteria';
import { TimeOffPeriods, timeOffPeriodRows } from '../time-off-periods/time-off-periods';
import { addPlanningDays } from '../../services/planning-date';
import { isWorkingPlanningDate } from '../../services/declared-non-working-days';
import { CalendarService, SelectedDates } from '../../services/calendar-service';
@@ -58,6 +59,7 @@ type PlacementExplanation = PlanExplanation['placements'][number];
CalendarMonth,
DateComparison,
PlanningCriteria,
TimeOffPeriods,
MatCardContent,
MatProgressSpinner,
MatIcon,
@@ -172,6 +174,10 @@ export class CalendarYear {
this.declaredPeriods().length
);
});
protected readonly timeOffPeriodCount = computed(() => {
const plan = this.displayedPlan();
return plan ? timeOffPeriodRows(plan).length : 0;
});
protected readonly weekendConnectedHolidays = computed(() => {
const isWeekend = (date: string) => {
const day = new Date(`${date}T00:00:00Z`).getUTCDay();
@@ -571,6 +577,17 @@ export class CalendarYear {
}
}
/** Brings a date of the calendar into view and moves focus to its day button. */
protected showDate(date: string): void {
const day = this.monthGrid()?.nativeElement.querySelector<HTMLElement>(
`[data-date="${date}"]`,
);
if (!day) return;
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
day.scrollIntoView({ block: 'center', behavior: reduced ? 'auto' : 'smooth' });
day.focus({ preventScroll: true });
}
protected selectCalendarDate(date: string): void {
if (this.declarationEntry()) {
const horizon = this.calendarHorizon();
@@ -0,0 +1,31 @@
<p class="help">{{ tr().planning.timeOffPeriods.help }}</p>
<ul class="periods">
@for (row of rows(); track row.start) {
<li>
<button
type="button"
[attr.data-start]="row.start"
(click)="dateChosen.emit(row.firstDate)"
>
<span class="range">{{ range(row) }}</span>
<span class="counts">
@for (leave of row.leave; track leave.type) {
<span class="count">
<span class="swatch" [class]="leave.type" aria-hidden="true"></span>
{{ typeLabel(leave.type) }} : <strong>{{ leave.days }}</strong>
</span>
}
@if (row.declared) {
<span class="count">
<span class="swatch declared" aria-hidden="true"></span>
{{ tr().bookedDays.booked }} : <strong>{{ row.declared }}</strong>
</span>
}
</span>
<span class="duration">
<strong>{{ row.duration }}</strong> {{ tr().planning.explanation.daysOff }}
</span>
</button>
</li>
}
</ul>
@@ -0,0 +1,99 @@
:host {
display: block;
min-width: 0;
}
.help {
margin: 0;
padding: 0.75rem 1rem 0;
color: var(--ui-text-secondary);
font-size: 0.875rem;
}
// A long plan scrolls here instead of pushing the calendar down.
.periods {
max-height: min(22rem, 60dvh);
margin: 0;
padding: 0.5rem;
overflow-y: auto;
list-style: none;
}
li + li {
border-top: 1px solid var(--ui-border);
}
button {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.375rem 1rem;
width: 100%;
min-height: 2.75rem;
padding: 0.5rem 0.75rem;
border: 0;
border-radius: var(--ui-radius-sm);
background: transparent;
color: inherit;
font: inherit;
text-align: start;
cursor: pointer;
transition: background-color 150ms ease;
&:hover {
background: var(--ui-panel-bg);
}
}
.range {
flex: 1 1 11rem;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.counts {
display: flex;
flex-wrap: wrap;
gap: 0.375rem 0.75rem;
font-size: 0.8125rem;
}
.count {
display: inline-flex;
align-items: center;
gap: 0.375rem;
color: var(--ui-text-secondary);
strong {
color: var(--mat-sys-on-surface);
font-variant-numeric: tabular-nums;
}
}
.duration {
flex: 0 0 auto;
min-width: 9rem;
color: var(--ui-text-secondary);
font-size: 0.8125rem;
text-align: end;
strong {
color: var(--mat-sys-on-surface);
font-size: 1rem;
font-variant-numeric: tabular-nums;
}
}
.swatch {
flex-shrink: 0;
width: 1rem;
height: 1rem;
border-radius: 0.25rem;
&.cp {
background: var(--cp-bg);
}
&.rtt {
background: var(--rtt-bg);
}
&.other {
background: var(--other-bg);
}
&.declared {
background-image: var(--declared-day-pattern);
border: 1px solid var(--ui-border);
}
}
@@ -0,0 +1,132 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import type { LeavePlacement, PlanOutcome } from '../../services/leave-planner.service';
import { TranslationService } from '../../services/translation-service';
import { TimeOffPeriods, timeOffPeriodRows } from './time-off-periods';
const placement = (date: string, type: LeavePlacement['type']): LeavePlacement => ({
date,
balanceId: type,
type,
ruleIds: [],
supporting: false,
});
// Deliberately out of order, with a plain public-holiday weekend between the two listed periods.
const plan: Pick<PlanOutcome, 'placements' | 'timeOffPeriods'> = {
placements: [
placement('2024-05-06', 'rtt'),
placement('2024-05-07', 'cp'),
placement('2024-05-03', 'cp'),
placement('2024-05-08', 'cp'),
],
timeOffPeriods: [
{
start: '2024-05-04',
end: '2024-05-12',
duration: 9,
placementDates: ['2024-05-06', '2024-05-07', '2024-05-08'],
nonWorkingDates: ['2024-05-04', '2024-05-05', '2024-05-09', '2024-05-10'],
nonWorkingDayGain: 4,
},
{
start: '2024-05-25',
end: '2024-05-26',
duration: 2,
placementDates: [],
nonWorkingDates: ['2024-05-25', '2024-05-26'],
nonWorkingDayGain: 2,
},
{
start: '2024-05-01',
end: '2024-05-05',
duration: 5,
placementDates: ['2024-05-03'],
declaredDates: ['2024-05-02'],
nonWorkingDates: ['2024-05-01', '2024-05-04', '2024-05-05'],
nonWorkingDayGain: 3,
},
],
};
describe('timeOffPeriodRows', () => {
it('lists chronologically the periods with leave or a declared day, with their leave by type', () => {
expect(timeOffPeriodRows(plan)).toEqual([
{
start: '2024-05-01',
end: '2024-05-05',
duration: 5,
leave: [{ type: 'cp', days: 1 }],
declared: 1,
firstDate: '2024-05-02',
},
{
start: '2024-05-04',
end: '2024-05-12',
duration: 9,
leave: [
{ type: 'cp', days: 2 },
{ type: 'rtt', days: 1 },
],
declared: 0,
firstDate: '2024-05-06',
},
]);
});
it('lists nothing for a plan without leave', () => {
expect(
timeOffPeriodRows({ placements: [], timeOffPeriods: [plan.timeOffPeriods[1]] }),
).toEqual([]);
});
});
describe('TimeOffPeriods', () => {
async function render(language: string) {
await TestBed.configureTestingModule({
imports: [TimeOffPeriods],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
TestBed.inject(TranslationService).setLanguage(language);
const fixture = TestBed.createComponent(TimeOffPeriods);
fixture.componentRef.setInput('plan', plan);
fixture.detectChanges();
return { fixture, root: fixture.nativeElement as HTMLElement };
}
const text = (element: Element) => element.textContent?.replace(/\s+/g, ' ').trim();
it('shows the range, the leave days per type, the declared days and the duration of each period', async () => {
const { root } = await render('en');
const buttons = [...root.querySelectorAll<HTMLButtonElement>('li > button')];
expect(buttons.map((button) => button.dataset['start'])).toEqual([
'2024-05-01',
'2024-05-04',
]);
const range = (start: string, end: string) =>
new Intl.DateTimeFormat(TestBed.inject(TranslationService).locale(), {
dateStyle: 'medium',
timeZone: 'UTC',
}).formatRange(new Date(start), new Date(end));
expect(text(buttons[0])).toBe(
`${range('2024-05-01', '2024-05-05')} Paid Leave : 1 Already booked : 1 5 days off in a row`,
);
expect(text(buttons[1])).toBe(
`${range('2024-05-04', '2024-05-12')} Paid Leave : 2 RTT : 1 9 days off in a row`,
);
expect(buttons[1].querySelector('.swatch.rtt')).not.toBeNull();
});
it('shows dates in the active locale', async () => {
const { root } = await render('de');
expect(root.querySelector('.range')?.textContent).toContain('01.–05.05.2024');
});
it('chooses the first leave placement or declared day of a period', async () => {
const { fixture, root } = await render('en');
const chosen: string[] = [];
fixture.componentInstance.dateChosen.subscribe((date) => chosen.push(date));
for (const button of root.querySelectorAll<HTMLButtonElement>('li > button'))
button.click();
expect(chosen).toEqual(['2024-05-02', '2024-05-06']);
});
});
@@ -0,0 +1,72 @@
import { ChangeDetectionStrategy, Component, computed, inject, input, output } from '@angular/core';
import type { LeaveType, PlanOutcome, TimeOffPeriod } from '../../services/leave-planner.service';
import { TranslationService } from '../../services/translation-service';
const LEAVE_TYPES: readonly LeaveType[] = ['cp', 'rtt', 'other'];
export interface TimeOffPeriodRow extends Pick<TimeOffPeriod, 'start' | 'end' | 'duration'> {
/** Leave days to place in the period, by leave type; types without a day are left out. */
leave: readonly { type: LeaveType; days: number }[];
declared: number;
/** The first leave placement or declared non-working day of the period. */
firstDate: string;
}
/** The periods of a plan worth reading dates from, in chronological order: those with leave or a declared day. */
export function timeOffPeriodRows(
plan: Pick<PlanOutcome, 'placements' | 'timeOffPeriods'>,
): TimeOffPeriodRow[] {
const typeOf = new Map(plan.placements.map(({ date, type }) => [date, type]));
return plan.timeOffPeriods
.filter(
({ placementDates, declaredDates }) => placementDates.length || declaredDates?.length,
)
.map(({ start, end, duration, placementDates, declaredDates = [] }) => ({
start,
end,
duration,
leave: LEAVE_TYPES.map((type) => ({
type,
days: placementDates.filter((date) => typeOf.get(date) === type).length,
})).filter(({ days }) => days),
declared: declaredDates.length,
firstDate: [...placementDates, ...declaredDates].sort()[0],
}))
.sort((a, b) => a.start.localeCompare(b.start));
}
/** The time-off periods of a plan, each a button that asks for its first leave day to be shown. */
@Component({
selector: 'app-time-off-periods',
templateUrl: './time-off-periods.html',
styleUrl: './time-off-periods.scss',
// A button's name is read from its content: keep the spaces between its parts.
preserveWhitespaces: true,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TimeOffPeriods {
readonly plan = input.required<Pick<PlanOutcome, 'placements' | 'timeOffPeriods'>>();
/** The first leave placement or declared day of the chosen period. */
readonly dateChosen = output<string>();
private readonly translationService = inject(TranslationService);
protected readonly rows = computed(() => timeOffPeriodRows(this.plan()));
private readonly dateFormat = computed(
() =>
new Intl.DateTimeFormat(this.translationService.locale(), {
dateStyle: 'medium',
timeZone: 'UTC',
}),
);
get tr() {
return this.translationService.tr;
}
protected range({ start, end }: TimeOffPeriodRow): string {
return this.dateFormat().formatRange(new Date(start), new Date(end));
}
protected typeLabel(type: LeaveType): string {
return this.translationService.getDayTypeLabel(type);
}
}
+1
View File
@@ -257,6 +257,7 @@ export interface AppTranslations {
explanationHelp: string;
technicalDetails: string;
appliedRules: { title: string; entries: string };
timeOffPeriods: { title: string; count: string; help: string };
compareDates: string;
stopComparing: string;
daysPlaced: string;
+5
View File
@@ -370,6 +370,11 @@
"title": "Details zu angewendeten Regeln",
"entries": "Einträge"
},
"timeOffPeriods": {
"title": "Ihre freien Zeiträume",
"count": "Zeiträume",
"help": "Die zu nehmenden Tage, Zeitraum für Zeitraum. Wählen Sie einen aus, um ihn im Kalender anzuzeigen."
},
"compareDates": "Andere Termine vergleichen",
"stopComparing": "Datumsvergleich schließen",
"explanation": {
+5
View File
@@ -370,6 +370,11 @@
"title": "Applied rules detail",
"entries": "Entries"
},
"timeOffPeriods": {
"title": "Your time-off periods",
"count": "Periods",
"help": "The days to take, period by period. Choose one to show it in the calendar."
},
"compareDates": "Compare other dates",
"stopComparing": "Close date comparison",
"explanation": {
+5
View File
@@ -370,6 +370,11 @@
"title": "Detalle de las reglas aplicadas",
"entries": "Elementos"
},
"timeOffPeriods": {
"title": "Tus periodos de descanso",
"count": "Periodos",
"help": "Los días que pedir, periodo a periodo. Elige uno para verlo en el calendario."
},
"compareDates": "Comparar otras fechas",
"stopComparing": "Cerrar comparación",
"explanation": {
+5
View File
@@ -370,6 +370,11 @@
"title": "Détail des règles appliquées",
"entries": "Éléments"
},
"timeOffPeriods": {
"title": "Vos périodes de repos",
"count": "Périodes",
"help": "Les jours à poser, période par période. Choisissez-en une pour l’afficher dans le calendrier."
},
"compareDates": "Comparer d’autres dates",
"stopComparing": "Fermer la comparaison",
"explanation": {