feat: per-project workflow settings, statistics and "my work" home

Per-project settings (owners/admins, «Configuración» tab):
- Statuses with category (TODO, IN_PROGRESS, QA, DONE, CANCELLED), colour and
  "requires reason"; configurable transitions; ticket types (icon, colour) and
  areas. Defaults are the previous fixed values; projects created before keep
  them without migration.
- Values are archived, never deleted: tickets, history and statistics keep
  referring to them. Validated in the domain (ProjectSettingsChangedEvent).
- Releases, board, tracking and "my work" use categories, so custom statuses
  keep working. Status changes carry name/category metadata for history.
- GraphQL: status/type/area are strings (breaking for clients sending enum
  literals); Project.settings, updateProjectSettings, statusCategory,
  myIssues(categories). REST: PUT /projects/{project}/settings, category filters.
- Read model: statusCategory on issues (backfilled at startup).

Statistics («Estadísticas» tab):
- New issue_timeline projection; pure functions compute created vs resolved,
  cumulative flow, cycle/lead time (avg + p85), throughput per person, QA
  pass/fail and release burnup. GraphQL Project.analytics(days),
  Release.burnup; REST /projects/{project}/analytics, /releases/{id}/burnup.
- Web: SVG charts with validated light/dark palette, crosshair tooltip,
  keyboard navigation, legend and data table.

Home "Mi trabajo": my open tickets across projects grouped by category (QA
failures first), tickets waiting for QA, upcoming releases and "Ir a…".

Tests: domain/application specs, e2e scenario for settings and analytics,
facade tests. Docs, READMEs, schema.gql/openapi.json and Word/PDF updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-06 20:53:45 +02:00
parent 240ea9a539
commit 0e301ad545
143 changed files with 10291 additions and 1052 deletions

View File

@@ -1,12 +1,12 @@
import { DatasetColor } from '@pi/ui';
import {
IssueArea,
Release,
IssueLinkType,
IssuePriority,
IssueStatus,
IssueType,
ProjectRole,
ReleaseStatus,
SettingColor,
StatusCategory,
Workflow,
} from '@task-stream/web/tracker/domain';
type ChipColor =
@@ -16,111 +16,88 @@ type ChipColor =
| 'primary'
| 'success'
| 'warn';
type IconColor =
| 'primary'
| 'accent'
| 'warn'
| 'success'
| 'grey'
| 'highlighted';
/* UI copy (es) and the visual language of the tracker. */
/** `tone`: CSS colour token of the status/type (see `--ts-s-*`, `--ts-t-*` in styles.scss). */
export const STATUS: Record<
IssueStatus,
{ label: string; color: ChipColor; chart: DatasetColor; tone: string }
/** CSS colour of a settings colour token (`--ts-c-*` in styles.scss). */
export const tone = (color: string) => `var(--ts-c-${color}, var(--ts-muted))`;
/** A status as the UI shows it: the project's name and colour. */
export function statusLook(workflow: Workflow, id: string) {
const status = workflow.status(id);
return {
label: status.name,
tone: tone(status.color),
category: status.category,
};
}
/** A ticket type as the UI shows it: name, icon and colour. */
export function typeLook(workflow: Workflow, id: string) {
const type = workflow.type(id);
return { label: type.name, icon: type.icon, tone: tone(type.color) };
}
/** What each category means, whatever the project calls its statuses. */
export const CATEGORY: Record<
StatusCategory,
{ label: string; hint: string; tone: string }
> = {
[IssueStatus.BACKLOG]: {
label: 'Backlog',
color: 'grey',
chart: DatasetColor.grey,
tone: 'var(--ts-s-backlog)',
[StatusCategory.TODO]: {
label: 'Pendiente',
hint: 'Aún no empezado. Los tickets nuevos entran en el primero.',
tone: tone('slate'),
},
[IssueStatus.TODO]: {
label: 'Por hacer',
color: 'grey',
chart: DatasetColor.grey300,
tone: 'var(--ts-s-todo)',
},
[IssueStatus.IN_PROGRESS]: {
[StatusCategory.IN_PROGRESS]: {
label: 'En curso',
color: 'primary',
chart: DatasetColor.primary,
tone: 'var(--ts-s-progress)',
hint: 'Alguien trabaja en él (mide el tiempo de ciclo).',
tone: tone('violet'),
},
[IssueStatus.IN_REVIEW]: {
label: 'En revisión',
color: 'accent',
chart: DatasetColor.accent,
tone: 'var(--ts-s-review)',
[StatusCategory.QA]: {
label: 'QA',
hint: 'Esperando o en pruebas. Salir a «hecho» cuenta como QA superado.',
tone: tone('amber'),
},
[IssueStatus.READY_FOR_QA]: {
label: 'Listo para QA',
color: 'highlighted',
chart: DatasetColor.highlighted,
tone: 'var(--ts-s-ready)',
},
[IssueStatus.IN_QA]: {
label: 'En QA',
color: 'highlighted',
chart: DatasetColor.highlighted50,
tone: 'var(--ts-s-qa)',
},
[IssueStatus.QA_FAILED]: {
label: 'QA fallido',
color: 'warn',
chart: DatasetColor.warn,
tone: 'var(--ts-s-failed)',
},
[IssueStatus.DONE]: {
[StatusCategory.DONE]: {
label: 'Hecho',
color: 'success',
chart: DatasetColor.success,
tone: 'var(--ts-s-done)',
hint: 'Terminado: cuenta como resuelto en releases y estadísticas.',
tone: tone('green'),
},
[IssueStatus.CANCELLED]: {
[StatusCategory.CANCELLED]: {
label: 'Cancelado',
color: 'grey',
chart: DatasetColor.grey50,
tone: 'var(--ts-s-cancelled)',
hint: 'Descartado: no ocupa columna ni cuenta en el alcance.',
tone: tone('stone'),
},
};
export const TYPE: Record<
IssueType,
{ label: string; icon: string; color: IconColor; tone: string }
> = {
[IssueType.BUG]: {
label: 'Bug',
icon: 'bug',
color: 'warn',
tone: 'var(--ts-t-bug)',
},
[IssueType.FEATURE]: {
label: 'Feature',
icon: 'feature',
color: 'primary',
tone: 'var(--ts-t-feature)',
},
[IssueType.UI_CHANGE]: {
label: 'Cambio de UI',
icon: 'palette',
color: 'accent',
tone: 'var(--ts-t-ui)',
},
[IssueType.TASK]: {
label: 'Tarea',
icon: 'task',
color: 'grey',
tone: 'var(--ts-t-task)',
},
[IssueType.QA]: {
label: 'QA',
icon: 'qa',
color: 'highlighted',
tone: 'var(--ts-t-qa)',
},
/** Names of the icons a ticket type can pick (TYPE_ICONS). */
export const ICON_LABEL: Record<string, string> = {
bug: 'Bicho',
feature: 'Estrella',
palette: 'Paleta',
task: 'Casilla',
qa: 'Lupa',
flag: 'Bandera',
'star-fill': 'Estrella rellena',
rocket: 'Cohete',
document: 'Documento',
'light-bulb': 'Bombilla',
key: 'Llave',
support: 'Soporte',
};
export const COLOR_LABEL: Record<SettingColor, string> = {
slate: 'Pizarra',
stone: 'Piedra',
violet: 'Violeta',
blue: 'Azul',
sky: 'Cielo',
teal: 'Verde azulado',
green: 'Verde',
amber: 'Ámbar',
orange: 'Naranja',
red: 'Rojo',
pink: 'Rosa',
};
/** Signal strength of a priority, drawn as bars (1–4) like a phone signal. */
@@ -143,15 +120,6 @@ export const PRIORITY: Record<
[IssuePriority.LOWEST]: { label: 'Mínima', color: 'grey' },
};
export const AREA: Record<IssueArea, string> = {
[IssueArea.FRONTEND]: 'Frontend',
[IssueArea.BACKEND]: 'Backend',
[IssueArea.MOBILE]: 'Mobile',
[IssueArea.QA]: 'QA',
[IssueArea.DESIGN]: 'Diseño',
[IssueArea.DEVOPS]: 'DevOps',
};
export const LINK: Record<IssueLinkType, { outward: string; inward: string }> =
{
[IssueLinkType.BLOCKS]: {
@@ -249,3 +217,23 @@ export function clock(iso: string, now = new Date()): string {
? date.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' })
: date.toLocaleDateString('es', { day: 'numeric', month: 'short' });
}
/** "publicada hace 2 días", "objetivo 17 oct · en 14 d", "objetivo 3 oct · retrasada 2 d". */
export function releaseWhen(release: Release, now = Date.now()): string {
if (release.releasedAt)
return `publicada ${timeAgo(release.releasedAt, now)}`;
if (!release.targetDate) return 'sin fecha';
const target = new Date(release.targetDate);
const days = Math.ceil((target.getTime() - now) / 86_400_000);
const date = target.toLocaleDateString('es', {
day: 'numeric',
month: 'short',
});
if (days < 0) return `objetivo ${date} · retrasada ${-days} d`;
return days === 0 ? 'objetivo hoy' : `objetivo ${date} · en ${days} d`;
}
/** WEB-12 → WEB (the project key prefix of a ticket key). */
export function projectKeyOf(issueKey: string): string {
return issueKey.slice(0, issueKey.lastIndexOf('-'));
}

View File

@@ -0,0 +1,129 @@
import {
ChangeDetectionStrategy,
Component,
inject,
signal,
} from '@angular/core';
import { Router } from '@angular/router';
import { PiIconComponent } from '@pi/ui';
const ISSUE_KEY = /^([A-Za-z][A-Za-z0-9]{1,9})-(\d+)$/;
const PROJECT_KEY = /^[A-Za-z][A-Za-z0-9]{1,9}$/;
/** "Ir a…": type a ticket key (WEB-12) or a project key (WEB) and jump there. */
@Component({
selector: 'ts-go-to',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [PiIconComponent],
template: `
<form
class="ts-go"
role="search"
(submit)="$event.preventDefault(); go()"
novalidate
>
<label class="ts-go__field" [class.has-error]="!!error()">
<pi-icon icon="search" size="small" aria-hidden="true" />
<span class="visually-hidden">Ir a un ticket o proyecto</span>
<input
type="text"
name="goto"
placeholder="Ir a… WEB-12"
autocomplete="off"
spellcheck="false"
[value]="value()"
(input)="onInput($event)"
[attr.aria-invalid]="!!error()"
aria-describedby="ts-go-error"
/>
<kbd aria-hidden="true">↵</kbd>
</label>
<span id="ts-go-error" class="ts-go__error" aria-live="polite">{{
error()
}}</span>
</form>
`,
styles: `
.ts-go {
position: relative;
}
.ts-go__field {
display: flex;
align-items: center;
gap: 0.5rem;
width: min(16rem, 100%);
height: 2.75rem;
padding: 0 0.75rem 0 0.875rem;
box-sizing: border-box;
border: 1px solid var(--ts-line);
border-radius: 999px;
background: var(--ts-surface);
color: var(--ts-muted);
transition: border-color 0.15s ease;
&:focus-within {
border-color: var(--ts-brand);
box-shadow: 0 0 0 3px var(--pi-color-primary-50);
}
&.has-error {
border-color: var(--ts-s-failed);
}
@media (max-width: 640px) {
width: 100%;
}
}
input {
flex: 1;
min-width: 0;
border: 0;
outline: 0;
background: transparent;
color: var(--ts-ink);
font-family: var(--ts-font-mono);
font-size: 0.875rem;
text-transform: uppercase;
&::placeholder {
font-family: var(--ts-font-body);
text-transform: none;
color: var(--ts-muted);
}
}
kbd {
font-family: var(--ts-font-mono);
font-size: 0.75rem;
color: var(--ts-muted);
}
.ts-go__error {
position: absolute;
top: calc(100% + 0.25rem);
left: 1rem;
font-size: 0.75rem;
color: var(--ts-s-failed);
white-space: nowrap;
}
`,
})
export class GoToComponent {
private readonly router = inject(Router);
protected readonly value = signal('');
protected readonly error = signal('');
protected onInput(event: Event): void {
this.value.set((event.target as HTMLInputElement).value);
this.error.set('');
}
protected go(): void {
const ref = this.value().trim().toUpperCase();
if (!ref) return;
const issue = ISSUE_KEY.exec(ref);
if (issue) {
void this.router.navigate(['/p', issue[1], 'issues', ref]);
} else if (PROJECT_KEY.test(ref)) {
void this.router.navigate(['/p', ref]);
} else {
this.error.set('Escribe una clave como WEB-12 o WEB');
return;
}
this.value.set('');
}
}

View File

@@ -6,8 +6,8 @@ import {
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { PiIconComponent } from '@pi/ui';
import { IssueSummary } from '@task-stream/web/tracker/domain';
import { AREA, initials, PRIORITY, PRIORITY_LEVEL, TYPE } from './copy';
import { IssueSummary, Workflow } from '@task-stream/web/tracker/domain';
import { initials, PRIORITY, PRIORITY_LEVEL, typeLook } from './copy';
/** A ticket on the board / in lists: type stripe, key, title, signals. */
@Component({
@@ -206,11 +206,16 @@ import { AREA, initials, PRIORITY, PRIORITY_LEVEL, TYPE } from './copy';
})
export class IssueCardComponent {
readonly issue = input.required<IssueSummary>();
protected readonly type = computed(() => TYPE[this.issue().type]);
/** The project's settings: names, icons and colours of types and areas. */
readonly workflow = input.required<Workflow>();
protected readonly type = computed(() =>
typeLook(this.workflow(), this.issue().type),
);
protected readonly priority = computed(() => PRIORITY[this.issue().priority]);
protected readonly level = computed(
() => PRIORITY_LEVEL[this.issue().priority],
);
protected readonly areaLabel = (area: keyof typeof AREA) => AREA[area];
protected readonly areaLabel = (area: string) =>
this.workflow().area(area).name;
protected readonly initialsOf = initials;
}

View File

@@ -0,0 +1,582 @@
import {
afterNextRender,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
ElementRef,
inject,
input,
signal,
} from '@angular/core';
export interface ChartSeries {
label: string;
values: number[];
/** CSS colour (a `--ts-viz-*` token). */
color: string;
/** Wash the area under a line (~10%); ignored when stacked. */
area?: boolean;
}
export interface ChartMarker {
index: number;
label: string;
}
/** Last item (the web target predates Array.prototype.at). */
export const last = <T>(list: readonly T[]): T | undefined =>
list[list.length - 1];
const PAD = { top: 16, right: 20, bottom: 30, left: 40 };
/** 0 → max in 3-5 clean steps (1, 2, 5 × 10ⁿ). */
function niceTicks(max: number): number[] {
if (max <= 0) return [0, 1];
const raw = max / 4;
const power = 10 ** Math.floor(Math.log10(raw));
const step =
[1, 2, 5, 10].map((m) => m * power).find((s) => s >= raw) ?? power * 10;
const ticks: number[] = [];
for (let v = 0; v < max + step; v += step) {
ticks.push(Math.round(v * 1000) / 1000);
if (v >= max) break;
}
return ticks;
}
/**
* Lines or stacked areas over a shared x axis, drawn in SVG with the theme's
* tokens (so dark mode is its own palette). Crosshair + one tooltip with every
* series, keyboard (← →) as well as pointer, legend for 2+ series and a data
* table so nothing depends on hovering or on colour alone.
*/
@Component({
selector: 'ts-series-chart',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (series().length > 1) {
<ul class="ts-chart__legend">
@for (s of legend(); track s.label) {
<li>
<span
class="ts-chart__key"
[class.ts-chart__key--area]="stacked()"
[style.--key]="s.color"
></span>
{{ s.label }}
</li>
}
</ul>
}
<div
class="ts-chart__plot"
tabindex="0"
role="img"
[attr.aria-label]="summary()"
(pointermove)="onPointer($event)"
(pointerleave)="hover.set(null)"
(keydown)="onKey($event)"
(focus)="hover.set(hover() ?? count() - 1)"
(blur)="hover.set(null)"
>
<svg [attr.width]="width()" [attr.height]="height()" aria-hidden="true">
@for (tick of ticks(); track tick) {
<line
class="ts-chart__grid"
[attr.x1]="left"
[attr.x2]="width() - right"
[attr.y1]="y(tick)"
[attr.y2]="y(tick)"
/>
<text
class="ts-chart__tick"
[attr.x]="left - 8"
[attr.y]="y(tick)"
text-anchor="end"
dominant-baseline="middle"
>
{{ tick }}
</text>
}
@for (index of xTicks(); track index) {
<text
class="ts-chart__tick"
[attr.x]="x(index)"
[attr.y]="height() - 8"
[attr.text-anchor]="anchor(index)"
>
{{ labels()[index] }}
</text>
}
@if (marker(); as m) {
<line
class="ts-chart__marker"
[attr.x1]="x(m.index)"
[attr.x2]="x(m.index)"
[attr.y1]="top - 4"
[attr.y2]="y(0)"
/>
<text
class="ts-chart__marker-label"
[attr.x]="x(m.index) + 4"
[attr.y]="top + 6"
>
{{ m.label }}
</text>
}
@for (shape of shapes(); track shape.label) {
@if (shape.fill) {
<path
[class]="stacked() ? 'ts-chart__band' : 'ts-chart__wash'"
[attr.d]="shape.fill"
[style.fill]="shape.color"
/>
}
@if (shape.line) {
<path
[class]="stacked() ? 'ts-chart__gap' : 'ts-chart__line'"
[attr.d]="shape.line"
[style.stroke]="stacked() ? null : shape.color"
/>
}
}
@for (label of endLabels(); track label.text) {
<text
class="ts-chart__end"
[attr.x]="width() - right + 4"
[attr.y]="label.y"
dominant-baseline="middle"
>
{{ label.text }}
</text>
}
@if (hover() !== null) {
<line
class="ts-chart__crosshair"
[attr.x1]="x(hover()!)"
[attr.x2]="x(hover()!)"
[attr.y1]="top"
[attr.y2]="y(0)"
/>
@for (dot of dots(); track dot.label) {
<circle
class="ts-chart__dot"
[attr.cx]="x(hover()!)"
[attr.cy]="dot.y"
r="4"
[style.fill]="dot.color"
/>
}
}
</svg>
@if (tooltip(); as tip) {
<div
class="ts-chart__tooltip"
[class.is-left]="tip.left"
[style.left.px]="tip.x"
>
<p class="ts-chart__tooltip-title">{{ tip.title }}</p>
@for (row of tip.rows; track row.label) {
<p class="ts-chart__tooltip-row">
<span
class="ts-chart__tooltip-key"
[style.--key]="row.color"
></span>
<strong>{{ row.value }}</strong> {{ row.label }}
</p>
}
@if (tip.total !== null) {
<p class="ts-chart__tooltip-row ts-chart__tooltip-total">
<strong>{{ tip.total }}</strong> en total
</p>
}
</div>
}
</div>
<details class="ts-chart__data">
<summary>Ver los datos</summary>
<div class="ts-chart__table">
<table>
<thead>
<tr>
<th scope="col">{{ axisLabel() }}</th>
@for (s of series(); track s.label) {
<th scope="col">{{ s.label }}</th>
}
</tr>
</thead>
<tbody>
@for (label of fullLabels(); track $index; let i = $index) {
<tr>
<th scope="row">{{ label }}</th>
@for (s of series(); track s.label) {
<td>{{ s.values[i] }}</td>
}
</tr>
}
</tbody>
</table>
</div>
</details>
`,
styles: `
:host {
display: grid;
gap: 0.75rem;
min-width: 0;
}
.ts-chart__legend {
display: flex;
flex-wrap: wrap;
gap: 0.375rem 1rem;
margin: 0;
padding: 0;
list-style: none;
font-size: 0.8125rem;
color: var(--ts-ink-soft);
li {
display: inline-flex;
align-items: center;
gap: 0.4375rem;
}
}
.ts-chart__key {
width: 1rem;
height: 2px;
border-radius: 1px;
background: var(--key);
}
.ts-chart__key--area {
width: 0.75rem;
height: 0.75rem;
border-radius: 3px;
}
.ts-chart__plot {
position: relative;
border-radius: 0.5rem;
outline: none;
touch-action: pan-y;
&:focus-visible {
box-shadow: 0 0 0 2px var(--ts-brand);
}
}
svg {
display: block;
overflow: visible;
font-family: var(--ts-font-mono);
}
.ts-chart__grid {
stroke: var(--ts-line);
stroke-width: 1;
shape-rendering: crispEdges;
}
.ts-chart__tick {
fill: var(--ts-muted);
font-size: 0.6875rem;
font-variant-numeric: tabular-nums;
}
.ts-chart__line {
fill: none;
stroke-width: 2;
stroke-linejoin: round;
stroke-linecap: round;
}
.ts-chart__wash {
fill-opacity: 0.1;
}
/* The 2px surface gap between stacked bands. */
.ts-chart__gap {
fill: none;
stroke: var(--ts-surface);
stroke-width: 2;
stroke-linejoin: round;
}
.ts-chart__end {
fill: var(--ts-ink-soft);
font-size: 0.75rem;
font-weight: 600;
}
.ts-chart__marker {
stroke: var(--ts-ink-soft);
stroke-width: 1;
}
.ts-chart__marker-label {
fill: var(--ts-ink-soft);
font-size: 0.6875rem;
font-weight: 600;
}
.ts-chart__crosshair {
stroke: var(--ts-ink-soft);
stroke-width: 1;
shape-rendering: crispEdges;
}
.ts-chart__dot {
stroke: var(--ts-surface);
stroke-width: 2;
}
.ts-chart__tooltip {
position: absolute;
top: 0;
z-index: 2;
min-width: 9rem;
margin-left: 0.75rem;
padding: 0.5rem 0.625rem;
border-radius: 0.5rem;
background: var(--ts-surface-raised);
border: 1px solid var(--ts-line-strong);
box-shadow: 0 8px 24px -12px rgb(0 0 0 / 35%);
pointer-events: none;
font-size: 0.75rem;
color: var(--ts-ink-soft);
&.is-left {
margin-left: 0;
transform: translateX(calc(-100% - 0.75rem));
}
p {
margin: 0;
}
strong {
color: var(--ts-ink);
font-variant-numeric: tabular-nums;
}
}
.ts-chart__tooltip-title {
margin-bottom: 0.25rem !important;
font-weight: 600;
color: var(--ts-muted);
}
.ts-chart__tooltip-row {
display: flex;
align-items: center;
gap: 0.375rem;
line-height: 1.6;
}
.ts-chart__tooltip-key {
width: 0.625rem;
height: 2px;
border-radius: 1px;
background: var(--key);
}
.ts-chart__tooltip-total {
margin-top: 0.25rem !important;
padding-top: 0.25rem;
border-top: 1px solid var(--ts-line);
}
.ts-chart__data summary {
width: fit-content;
cursor: pointer;
font-size: 0.75rem;
color: var(--ts-muted);
}
.ts-chart__table {
max-height: 16rem;
margin-top: 0.5rem;
overflow: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
}
th,
td {
padding: 0.25rem 0.5rem;
border-bottom: 1px solid var(--ts-line);
text-align: right;
white-space: nowrap;
}
th:first-child {
text-align: left;
font-weight: 500;
}
thead th {
color: var(--ts-muted);
font-weight: 600;
}
`,
})
export class SeriesChartComponent {
/** Short x labels (axis). */
readonly labels = input.required<string[]>();
/** Long x labels (tooltip and table); defaults to `labels`. */
readonly longLabels = input<string[] | undefined>();
readonly series = input.required<ChartSeries[]>();
readonly stacked = input(false);
readonly marker = input<ChartMarker | null>(null);
/** What the chart shows, for screen readers. */
readonly summary = input.required<string>();
/** Header of the table's first column. */
readonly axisLabel = input('Fecha');
readonly height = input(240);
protected readonly left = PAD.left;
protected readonly right = PAD.right;
protected readonly top = PAD.top;
protected readonly width = signal(640);
protected readonly hover = signal<number | null>(null);
protected readonly count = computed(() => this.labels().length);
/** Stacked: top band first, as the reader sees them. */
protected readonly legend = computed(() =>
this.stacked() ? [...this.series()].reverse() : this.series(),
);
protected readonly fullLabels = computed(
() => this.longLabels() ?? this.labels(),
);
/** Lower/upper bound of every series at every x (stacked: cumulative). */
private readonly bands = computed(() => {
let base = new Array(this.count()).fill(0) as number[];
return this.series().map((s) => {
const lower = this.stacked() ? base : base.map(() => 0);
const upper = s.values.map((v, i) => (this.stacked() ? lower[i] : 0) + v);
if (this.stacked()) base = upper;
return { ...s, lower, upper };
});
});
protected readonly ticks = computed(() =>
niceTicks(Math.max(0, ...this.bands().flatMap((b) => b.upper))),
);
private readonly max = computed(() => last(this.ticks()) || 1);
protected x(index: number): number {
const plot = this.width() - PAD.left - PAD.right;
return this.count() <= 1
? PAD.left + plot / 2
: PAD.left + (index * plot) / (this.count() - 1);
}
protected y(value: number): number {
const plot = this.height() - PAD.top - PAD.bottom;
return PAD.top + plot - (value / this.max()) * plot;
}
protected anchor(index: number): string {
if (this.count() <= 1) return 'middle';
return index === 0
? 'start'
: index === this.count() - 1
? 'end'
: 'middle';
}
/** At most one label every ~90px, always the first and last. */
protected readonly xTicks = computed(() => {
const n = this.count();
if (n === 0) return [];
const slots = Math.max(
2,
Math.floor((this.width() - PAD.left - PAD.right) / 90),
);
const step = Math.max(1, Math.ceil((n - 1) / (slots - 1)));
const ticks: number[] = [];
for (let i = 0; i < n; i += step) ticks.push(i);
if (last(ticks) !== n - 1) {
if (n - 1 - (last(ticks) ?? 0) < step / 2) ticks.pop();
ticks.push(n - 1);
}
return ticks;
});
protected readonly shapes = computed(() =>
this.bands().map((band) => {
const points = band.upper.map((v, i) => `${this.x(i)},${this.y(v)}`);
const line = points.length ? `M${points.join('L')}` : '';
let fill: string | null = null;
if (this.stacked() || band.area) {
const floor = band.lower
.map((v, i) => `${this.x(i)},${this.y(v)}`)
.reverse();
fill = points.length
? `M${points.join('L')}L${floor.join('L')}Z`
: null;
}
return { label: band.label, color: band.color, line, fill };
}),
);
/** Last value at the line end, only while labels keep 14px apart. */
protected readonly endLabels = computed(() => {
if (this.stacked() || this.count() === 0) return [];
const labels = this.bands()
.map((band) => ({
text: String(last(band.upper) ?? 0),
y: this.y(last(band.upper) ?? 0),
}))
.sort((a, b) => a.y - b.y);
const apart = labels.every(
(l, i) => i === 0 || l.y - labels[i - 1].y >= 14,
);
return apart ? labels : [];
});
protected readonly dots = computed(() => {
const index = this.hover();
if (index === null) return [];
return this.bands().map((band) => ({
label: band.label,
color: band.color,
y: this.y(band.upper[index] ?? 0),
}));
});
protected readonly tooltip = computed(() => {
const index = this.hover();
if (index === null || index >= this.count()) return null;
const rows = this.series()
.map((s) => ({ label: s.label, color: s.color, value: s.values[index] }))
// Stacked: same order as the bands, top first.
.reverse();
if (!this.stacked()) rows.reverse();
const x = this.x(index);
return {
title: this.fullLabels()[index],
rows,
total: this.stacked() ? rows.reduce((sum, r) => sum + r.value, 0) : null,
x,
left: x > this.width() * 0.6,
};
});
constructor() {
const host = inject(ElementRef<HTMLElement>);
const destroyRef = inject(DestroyRef);
afterNextRender(() => {
const observer = new ResizeObserver(([entry]) =>
this.width.set(Math.max(240, Math.floor(entry.contentRect.width))),
);
observer.observe(host.nativeElement);
destroyRef.onDestroy(() => observer.disconnect());
});
}
/** The crosshair snaps to the nearest x. */
protected onPointer(event: PointerEvent): void {
const n = this.count();
if (n === 0) return;
const box = (event.currentTarget as HTMLElement).getBoundingClientRect();
const plot = this.width() - PAD.left - PAD.right;
const ratio = (event.clientX - box.left - PAD.left) / plot;
this.hover.set(Math.min(n - 1, Math.max(0, Math.round(ratio * (n - 1)))));
}
protected onKey(event: KeyboardEvent): void {
const n = this.count();
const current = this.hover() ?? n - 1;
const next =
event.key === 'ArrowLeft'
? current - 1
: event.key === 'ArrowRight'
? current + 1
: event.key === 'Home'
? 0
: event.key === 'End'
? n - 1
: null;
if (next === null) return;
event.preventDefault();
this.hover.set(Math.min(n - 1, Math.max(0, next)));
}
}