Files
task-stream/libs/web/tracker/presenters/src/lib/pages/settings.page.ts
Josep Piguillem f7e850068b feat: custom fields per project
Text, number, date or option-list fields defined in the project settings
(archived, never removed; their type is fixed once saved). Tickets hold
them, edited in the side panel, listed under the title and filtered by
option in the list view; also over GraphQL, REST (?field=ID:value) and MCP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 09:31:12 +02:00

1487 lines
46 KiB
TypeScript

import { RouterLink } from '@angular/router';
import {
CdkDrag,
CdkDragDrop,
CdkDragHandle,
CdkDropList,
moveItemInArray,
} from '@angular/cdk/drag-drop';
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
signal,
untracked,
} from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { PiCheckboxComponent, PiIconComponent, PiNoteComponent } from '@pi/ui';
import { GitIntegrationComponent } from '../ui/git-integration';
import { WebhooksComponent } from '../ui/webhooks';
import { TransferComponent } from '../ui/transfer';
import { AutomationsComponent } from '../ui/automations';
import { ProjectFacade } from '@task-stream/web/tracker/application';
import {
CustomFieldType,
IssueTypeOption,
ProjectSettings,
SETTING_COLORS,
StatusCategory,
TYPE_ICONS,
} from '@task-stream/web/tracker/domain';
import { CATEGORY, COLOR_LABEL, ICON_LABEL, tone } from '../ui/copy';
type Section = 'statuses' | 'issueTypes' | 'areas' | 'customFields';
const FIELD_TYPES: { id: CustomFieldType; label: string }[] = [
{ id: CustomFieldType.TEXT, label: 'Texto' },
{ id: CustomFieldType.NUMBER, label: 'Número' },
{ id: CustomFieldType.DATE, label: 'Fecha' },
{ id: CustomFieldType.SELECT, label: 'Lista de opciones' },
];
const CATEGORIES = Object.values(StatusCategory);
/** "Datos y análisis" → "DATOS_Y_ANALISIS": ids of new values (they never change after saving). */
function idFrom(name: string): string {
const slug = name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.replace(/^[^A-Z]+/, '')
.slice(0, 30);
return slug || 'NUEVO';
}
/**
* "Configuración" (owners and admins): the project's statuses, how tickets
* move between them, ticket types and areas. Edits a local draft, saved in
* one go; values can be archived but not removed once saved.
*/
@Component({
selector: 'ts-settings-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
PiCheckboxComponent,
RouterLink,
GitIntegrationComponent,
WebhooksComponent,
TransferComponent,
AutomationsComponent,
CdkDropList,
CdkDrag,
CdkDragHandle,
NgTemplateOutlet,
PiIconComponent,
PiNoteComponent,
],
template: `
<div class="ts-section-header">
<div>
<h2>Configuración</h2>
<p>
Estados, transiciones, tipos de ticket, áreas y campos de este
proyecto. Lo que ya se usa no se borra: se archiva y deja de
ofrecerse.
</p>
</div>
</div>
@if (!facade.canManage()) {
<pi-note
gap="xs"
status="info"
appearance="fill"
type="status"
title="Solo lectura"
text="Solo el propietario y los admins pueden cambiar la configuración."
/>
}
@if (facade.project(); as project) {
<section
class="ts-panel ts-block ts-visibility"
aria-labelledby="vis-title"
>
<div>
<h3 id="vis-title">Visibilidad</h3>
<p class="ts-muted">
@if (project.isPublic) {
Público: cualquiera, también sin iniciar sesión, ve el tablero,
los tickets, los comentarios, las releases, la actividad y las
estadísticas (en la web, por GraphQL y por REST). Solo los
miembros pueden cambiar algo.
} @else {
Privado: solo los miembros del proyecto lo ven.
}
</p>
</div>
<label class="ts-switch">
<input
type="checkbox"
role="switch"
[checked]="project.isPublic"
[disabled]="!facade.canManage()"
(change)="facade.setPublic($any($event.target).checked)"
/>
<span class="ts-switch__track" aria-hidden="true"></span>
<span>{{ project.isPublic ? 'Público' : 'Privado' }}</span>
</label>
</section>
<section
class="ts-panel ts-block ts-visibility"
aria-labelledby="proposals-title"
>
<div>
<h3 id="proposals-title">Propuestas del público</h3>
<p class="ts-muted">
@if (!project.isPublic) {
Solo para proyectos públicos: hazlo público para abrir un
formulario donde cualquiera, sin cuenta, reporte un error o
proponga una idea.
} @else if (project.acceptsProposals) {
Abierto: cualquiera puede enviar un error o una idea desde
<a class="ts-plain-link" routerLink="../proponer">el formulario</a
>. Llegan como tickets con la etiqueta «propuesta», y se pueden
votar.
} @else {
Cerrado. Ábrelo para que cualquiera, sin cuenta, pueda reportar un
error o proponer una idea; llegarán como tickets con la etiqueta
«propuesta».
}
</p>
</div>
<label class="ts-switch">
<input
type="checkbox"
role="switch"
[checked]="project.isPublic && project.acceptsProposals"
[disabled]="!facade.canManage() || !project.isPublic"
(change)="facade.setAcceptsProposals($any($event.target).checked)"
/>
<span class="ts-switch__track" aria-hidden="true"></span>
<span>{{
project.isPublic && project.acceptsProposals ? 'Abierto' : 'Cerrado'
}}</span>
</label>
</section>
}
@if (draft(); as d) {
<form
class="ts-settings"
(submit)="$event.preventDefault(); save()"
novalidate
>
<fieldset [disabled]="!facade.canManage()">
<!-- Statuses -->
<section class="ts-panel ts-block" aria-labelledby="st-title">
<header class="ts-block__head">
<div>
<h3 id="st-title">Estados</h3>
<p class="ts-muted">
En el orden de las columnas del tablero. La categoría dice qué
significa cada uno para releases, «Mi trabajo» y estadísticas.
</p>
</div>
<button type="button" class="ts-add" (click)="addStatus()">
+ Añadir estado
</button>
</header>
<div class="ts-rows-head ts-status-grid" aria-hidden="true">
<span></span><span>Nombre</span><span>Categoría</span
><span>Color</span><span>Límite WIP</span><span>Pide motivo</span
><span></span>
</div>
<ol
class="ts-rows"
cdkDropList
[cdkDropListDisabled]="!facade.canManage()"
(cdkDropListDropped)="reorder($event)"
>
@for (status of d.statuses; track $index; let i = $index) {
<li
class="ts-row ts-status-grid"
cdkDrag
[class.is-archived]="status.archived"
[style.--tone]="toneOf(status.color)"
>
<span
class="ts-grip"
cdkDragHandle
title="Arrastra para reordenar"
aria-hidden="true"
>⠿</span
>
<span class="ts-name">
<span class="ts-swatch" aria-hidden="true"></span>
<input
class="ts-input"
maxlength="40"
[attr.aria-label]="'Nombre del estado ' + (i + 1)"
[value]="status.name"
(input)="setStatusName(i, $any($event.target).value)"
/>
<code class="ts-id">{{ status.id }}</code>
</span>
<select
class="ts-input"
aria-label="Categoría"
[value]="status.category"
[attr.title]="categoryHint(status.category)"
(change)="
edit('statuses', i, {
category: $any($event.target).value,
})
"
>
@for (c of categories; track c) {
<option [value]="c" [selected]="c === status.category">
{{ categoryLabel(c) }}
</option>
}
</select>
<select
class="ts-input"
aria-label="Color"
(change)="
edit('statuses', i, { color: $any($event.target).value })
"
>
@for (c of colors; track c) {
<option [value]="c" [selected]="c === status.color">
{{ colorLabel(c) }}
</option>
}
</select>
<input
class="ts-input"
type="number"
min="1"
max="999"
placeholder="—"
[attr.aria-label]="'Límite WIP de ' + status.name"
title="Cuántos tickets debería tener la columna como mucho (vacío: sin límite)"
[value]="status.wipLimit ?? ''"
(change)="
edit('statuses', i, {
wipLimit: wipFrom($any($event.target).value),
})
"
/>
<pi-checkbox
class="ts-check"
[checked]="status.requiresReason"
(checkedChange)="
edit('statuses', i, { requiresReason: $event })
"
><span class="visually-hidden"
>Pide motivo</span
></pi-checkbox
>
<ng-container
[ngTemplateOutlet]="archive"
[ngTemplateOutletContext]="{
section: 'statuses',
index: i,
item: status,
}"
/>
</li>
}
</ol>
</section>
<!-- Transitions -->
<section class="ts-panel ts-block" aria-labelledby="tr-title">
<header class="ts-block__head">
<div>
<h3 id="tr-title">Transiciones</h3>
<p class="ts-muted">
A qué estados puede pasar un ticket desde cada uno (fila →
columna). Los archivados no reciben tickets.
</p>
</div>
</header>
<div class="ts-matrix-wrap">
<table class="ts-matrix">
<thead>
<tr>
<th scope="col">
<span class="visually-hidden">Desde</span>
</th>
@for (to of activeStatuses(); track to.id) {
<th scope="col">
<span
class="ts-pill"
[style.--tone]="toneOf(to.color)"
>{{ to.name }}</span
>
</th>
}
</tr>
</thead>
<tbody>
@for (from of d.statuses; track from.id) {
<tr [class.is-archived]="from.archived">
<th scope="row">
<span
class="ts-pill"
[style.--tone]="toneOf(from.color)"
>{{ from.name }}</span
>
</th>
@for (to of activeStatuses(); track to.id) {
<td>
@if (from.id !== to.id) {
<pi-checkbox
[checked]="allows(from.id, to.id)"
(checkedChange)="
toggleTransition(from.id, to.id, $event)
"
><span class="visually-hidden"
>{{ from.name }} → {{ to.name }}</span
></pi-checkbox
>
}
</td>
}
</tr>
}
</tbody>
</table>
</div>
</section>
<div class="ts-settings__pair">
<!-- Ticket types -->
<section class="ts-panel ts-block" aria-labelledby="ty-title">
<header class="ts-block__head">
<div>
<h3 id="ty-title">Tipos de ticket</h3>
<p class="ts-muted">
Los de icono de paleta piden un frame de Figma.
</p>
</div>
<button type="button" class="ts-add" (click)="addType()">
+ Añadir tipo
</button>
</header>
<ol class="ts-rows">
@for (type of d.issueTypes; track $index; let i = $index) {
<li
class="ts-row ts-type-grid"
[class.is-archived]="type.archived"
[style.--tone]="toneOf(type.color)"
>
<span class="ts-type-icon" aria-hidden="true">
<pi-icon [icon]="type.icon" size="small" />
</span>
<span class="ts-name">
<input
class="ts-input"
maxlength="40"
[attr.aria-label]="'Nombre del tipo ' + (i + 1)"
[value]="type.name"
(input)="
setName('issueTypes', i, $any($event.target).value)
"
/>
<code class="ts-id">{{ type.id }}</code>
</span>
<select
class="ts-input"
aria-label="Icono"
(change)="
edit('issueTypes', i, {
icon: $any($event.target).value,
})
"
>
@for (icon of icons; track icon) {
<option [value]="icon" [selected]="icon === type.icon">
{{ iconLabel(icon) }}
</option>
}
</select>
<select
class="ts-input"
aria-label="Color"
(change)="
edit('issueTypes', i, {
color: $any($event.target).value,
})
"
>
@for (c of colors; track c) {
<option [value]="c" [selected]="c === type.color">
{{ colorLabel(c) }}
</option>
}
</select>
<button
type="button"
class="ts-add ts-template-toggle"
[class.has-template]="hasTemplate(type)"
[attr.aria-expanded]="openTemplate() === i"
[attr.aria-label]="'Plantilla de ' + type.name"
(click)="
openTemplate.set(openTemplate() === i ? null : i)
"
>
Plantilla{{ hasTemplate(type) ? ' ●' : '' }}
</button>
<ng-container
[ngTemplateOutlet]="archive"
[ngTemplateOutletContext]="{
section: 'issueTypes',
index: i,
item: type,
}"
/>
@if (openTemplate() === i) {
<div class="ts-template">
<label class="ts-template__field">
<span
>Descripción inicial (si el ticket llega sin
ella)</span
>
<textarea
class="ts-input"
rows="5"
maxlength="5000"
[value]="type.template?.description ?? ''"
(input)="
setTemplate(i, {
description: $any($event.target).value,
})
"
></textarea>
</label>
<label class="ts-template__field">
<span>Checklist (un paso por línea, hasta 20)</span>
<textarea
class="ts-input"
rows="4"
[value]="
(type.template?.checklist ?? []).join(
'
'
)
"
(input)="
setTemplate(i, {
checklist: $any($event.target).value.split(
'
'
),
})
"
></textarea>
</label>
</div>
}
</li>
}
</ol>
</section>
<!-- Areas -->
<section class="ts-panel ts-block" aria-labelledby="ar-title">
<header class="ts-block__head">
<div>
<h3 id="ar-title">Áreas</h3>
<p class="ts-muted">Equipo o capa a la que va el ticket.</p>
</div>
<button type="button" class="ts-add" (click)="addArea()">
+ Añadir área
</button>
</header>
<ol class="ts-rows">
@for (area of d.areas; track $index; let i = $index) {
<li
class="ts-row ts-area-grid"
[class.is-archived]="area.archived"
>
<span class="ts-name">
<input
class="ts-input"
maxlength="40"
[attr.aria-label]="'Nombre del área ' + (i + 1)"
[value]="area.name"
(input)="setName('areas', i, $any($event.target).value)"
/>
<code class="ts-id">{{ area.id }}</code>
</span>
<ng-container
[ngTemplateOutlet]="archive"
[ngTemplateOutletContext]="{
section: 'areas',
index: i,
item: area,
}"
/>
</li>
}
</ol>
</section>
<!-- Custom fields -->
<section class="ts-panel ts-block" aria-labelledby="cf-title">
<header class="ts-block__head">
<div>
<h3 id="cf-title">Campos personalizados</h3>
<p class="ts-muted">
Datos propios de este proyecto en cada ticket (navegador,
cliente, coste…). El tipo no cambia una vez guardado.
</p>
</div>
<button
type="button"
class="ts-add"
[disabled]="d.customFields.length >= 30"
(click)="addField()"
>
+ Añadir campo
</button>
</header>
@if (!d.customFields.length) {
<p class="ts-muted ts-empty-fields">Ningún campo todavía.</p>
}
<ol class="ts-rows">
@for (field of d.customFields; track $index; let i = $index) {
<li
class="ts-row ts-field-grid"
[class.is-archived]="field.archived"
>
<span class="ts-name">
<input
class="ts-input"
maxlength="40"
[attr.aria-label]="'Nombre del campo ' + (i + 1)"
[value]="field.name"
(input)="
setName('customFields', i, $any($event.target).value)
"
/>
<code class="ts-id">{{ field.id }}</code>
</span>
<select
class="ts-input ts-field-type"
aria-label="Tipo de campo"
[disabled]="!isNew('customFields', field.id)"
[attr.title]="
isNew('customFields', field.id)
? null
: 'Ya guardado: el tipo no se puede cambiar'
"
(change)="setFieldType(i, $any($event.target).value)"
>
@for (t of fieldTypes; track t.id) {
<option [value]="t.id" [selected]="t.id === field.type">
{{ t.label }}
</option>
}
</select>
<ng-container
[ngTemplateOutlet]="archive"
[ngTemplateOutletContext]="{
section: 'customFields',
index: i,
item: field,
}"
/>
@if (field.type === 'SELECT') {
<label class="ts-field-options">
<span>Opciones (una por línea)</span>
<textarea
rows="3"
[attr.aria-label]="'Opciones de ' + field.name"
[value]="
field.options.join(
'
'
)
"
(input)="setOptions(i, $any($event.target).value)"
></textarea>
</label>
}
</li>
}
</ol>
</section>
</div>
</fieldset>
@if (facade.canManage() && (dirty() || facade.savingSettings())) {
<footer class="ts-savebar" [class.is-dirty]="dirty()">
<div class="ts-savebar__status" aria-live="polite">
@if (problems().length) {
<ul class="ts-problems">
@for (problem of problems(); track problem) {
<li>
<pi-icon icon="exclamation" size="x-small" />
{{ problem }}
</li>
}
</ul>
} @else {
<span>Cambios sin guardar</span>
}
</div>
<button
type="button"
class="ts-secondary"
[disabled]="!dirty() || facade.savingSettings()"
(click)="discard()"
>
Descartar
</button>
<button
type="submit"
class="ts-primary"
[disabled]="
!dirty() || !!problems().length || facade.savingSettings()
"
>
{{ facade.savingSettings() ? 'Guardando…' : 'Guardar cambios' }}
</button>
</footer>
}
</form>
@if (facade.canManage() && facade.project(); as project) {
<ts-git-integration
[projectId]="project.id"
[projectKey]="project.key"
/>
<ts-automations [projectId]="project.id" />
<ts-webhooks [projectId]="project.id" />
<ts-transfer [projectId]="project.id" [projectKey]="project.key" />
}
@if (facade.isOwner() && facade.project(); as project) {
<section
class="ts-panel ts-block ts-danger"
aria-labelledby="danger-title"
>
<div>
<h3 id="danger-title">Eliminar el proyecto</h3>
<p class="ts-muted">
Se borran sus tickets, comentarios y releases, y los enlaces que
tickets de otros proyectos tengan hacia los suyos. La clave
{{ project.key }} queda libre. No se puede deshacer.
</p>
</div>
<div class="ts-danger__confirm">
<label class="ts-danger__label">
<span
>Escribe <code>{{ project.key }}</code> para confirmar</span
>
<input
class="ts-input"
autocomplete="off"
spellcheck="false"
[value]="confirmKey()"
(input)="confirmKey.set($any($event.target).value)"
/>
</label>
<button
type="button"
class="ts-delete"
[disabled]="
confirmKey().trim().toUpperCase() !== project.key ||
facade.deleting()
"
(click)="facade.deleteProject(confirmKey())"
>
{{ facade.deleting() ? 'Eliminando…' : 'Eliminar proyecto' }}
</button>
</div>
</section>
}
}
<ng-template
#archive
let-section="section"
let-index="index"
let-item="item"
>
@if (isNew(section, item.id)) {
<button
type="button"
class="ts-icon-button"
title="Quitar (aún no se ha guardado)"
[attr.aria-label]="'Quitar ' + item.name"
(click)="remove(section, index)"
>
<pi-icon icon="trash" size="small" />
</button>
} @else if (item.archived) {
<button
type="button"
class="ts-archive is-archived"
[attr.aria-label]="'Restaurar ' + item.name"
(click)="edit(section, index, { archived: false })"
>
Restaurar
</button>
} @else {
<button
type="button"
class="ts-archive"
[attr.aria-label]="'Archivar ' + item.name"
(click)="edit(section, index, { archived: true })"
>
Archivar
</button>
}
</ng-template>
`,
styles: `
:host {
display: grid;
gap: 1rem;
}
.ts-block.ts-visibility,
.ts-block.ts-danger {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1.5rem;
flex-wrap: wrap;
> div {
flex: 1 1 26rem;
}
p {
max-width: 46rem;
margin: 0.25rem 0 0;
font-size: 0.8125rem;
}
}
.ts-switch {
display: inline-flex;
align-items: center;
gap: 0.625rem;
font-size: 0.875rem;
font-weight: 600;
cursor: pointer;
input {
position: absolute;
opacity: 0;
width: 1px;
height: 1px;
}
input:focus-visible + .ts-switch__track {
outline: 2px solid var(--ts-brand);
outline-offset: 2px;
}
input:disabled ~ * {
opacity: 0.6;
cursor: default;
}
}
.ts-switch__track {
position: relative;
width: 2.5rem;
height: 1.375rem;
border-radius: 999px;
background: var(--ts-line-strong);
transition: background-color 0.15s ease;
&::after {
content: '';
position: absolute;
top: 3px;
left: 3px;
width: 1rem;
height: 1rem;
border-radius: 50%;
background: var(--ts-surface);
box-shadow: var(--ts-shadow);
transition: transform 0.15s ease;
}
}
.ts-switch input:checked + .ts-switch__track {
background: var(--ts-brand);
&::after {
transform: translateX(1.125rem);
}
}
.ts-danger {
border: 1px solid color-mix(in srgb, var(--ts-c-red) 45%, transparent);
h3 {
color: var(--ts-c-red);
}
}
.ts-danger__confirm {
display: flex;
align-items: flex-end;
gap: 0.75rem;
flex-wrap: wrap;
}
.ts-danger__label {
display: grid;
gap: 0.375rem;
font-size: 0.8125rem;
color: var(--ts-ink-soft);
code {
font-family: var(--ts-font-mono);
font-weight: 600;
}
.ts-input {
width: 12rem;
}
}
.ts-delete {
min-width: 0 !important;
height: 2.125rem;
padding: 0 1rem !important;
border: 0 !important;
border-radius: 999px !important;
background: var(--ts-c-red) !important;
color: #fff !important;
font: inherit;
font-size: 0.8125rem;
font-weight: 600;
cursor: pointer;
&:disabled {
opacity: 0.45;
cursor: default;
}
}
.ts-settings {
display: grid;
gap: 1rem;
padding-bottom: 0;
}
fieldset {
display: grid;
gap: 1rem;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.ts-settings__pair {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 26rem), 1fr));
gap: 1rem;
align-items: start;
}
.ts-block {
display: grid;
gap: 0.75rem;
min-width: 0;
padding: 1.25rem;
h3 {
margin: 0;
font-size: 1rem;
font-weight: 700;
}
}
.ts-block__head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
p {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
}
}
.ts-rows {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
list-style: none;
}
.ts-rows-head {
padding: 0 0.5rem;
font-size: 0.6875rem;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ts-muted);
}
.ts-status-grid {
display: grid;
grid-template-columns:
1.25rem minmax(10rem, 1fr)
9rem 8rem 5.5rem 5.5rem 6.5rem;
align-items: center;
gap: 0.5rem;
}
.ts-template {
display: grid;
grid-column: 1 / -1;
gap: 0.5rem;
padding: 0.5rem 0 0.25rem;
}
.ts-template__field {
display: grid;
gap: 0.25rem;
font-size: 0.8125rem;
color: var(--ts-muted);
textarea {
font: inherit;
color: var(--ts-ink);
resize: vertical;
}
}
.ts-template-toggle {
white-space: nowrap;
&.has-template {
border-color: var(--ts-brand) !important;
color: var(--ts-ink) !important;
}
}
.ts-type-grid {
display: grid;
grid-template-columns: 2rem minmax(8rem, 1fr) 7rem 7rem auto 6.5rem;
align-items: center;
gap: 0.5rem;
}
.ts-area-grid {
display: grid;
grid-template-columns: minmax(8rem, 1fr) 6.5rem;
align-items: center;
gap: 0.5rem;
}
/* Name and archive on top; the type (and options) below. */
.ts-field-grid {
display: grid;
grid-template-columns: minmax(8rem, 1fr) 6.5rem;
align-items: center;
gap: 0.5rem;
.ts-field-type {
grid-row: 2;
grid-column: 1 / -1;
}
}
.ts-field-options {
grid-column: 1 / -1;
display: grid;
gap: 0.25rem;
font-size: 0.8125rem;
color: var(--ts-muted);
textarea {
font: inherit;
color: var(--ts-ink);
background: var(--ts-surface);
border: 1px solid var(--ts-line);
border-radius: 0.5rem;
padding: 0.375rem 0.5rem;
resize: vertical;
}
}
.ts-empty-fields {
margin: 0;
}
.ts-row {
--tone: var(--ts-muted);
padding: 0.375rem 0.5rem;
border-radius: 0.625rem;
background: var(--ts-surface);
border: 1px solid var(--ts-line);
&.is-archived {
background: var(--ts-sunken);
.ts-input,
.ts-type-icon {
opacity: 0.6;
}
}
}
.cdk-drag-preview {
box-shadow: var(--ts-lift);
}
.cdk-drag-placeholder {
opacity: 0.35;
}
.ts-grip {
cursor: grab;
color: var(--ts-muted);
text-align: center;
user-select: none;
}
.ts-name {
position: relative;
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
.ts-input {
flex: 1;
min-width: 0;
}
}
.ts-swatch {
flex: none;
width: 0.625rem;
height: 0.625rem;
border-radius: 50%;
background: var(--tone);
}
.ts-id {
flex: 0 0 5.5rem;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--ts-font-mono);
font-size: 0.625rem;
color: var(--ts-muted);
}
.ts-input {
box-sizing: border-box;
height: 2.125rem;
width: 100%;
padding: 0 0.5rem;
border: 1px solid var(--ts-line);
border-radius: 0.5rem;
background: var(--ts-surface);
color: var(--ts-ink);
font: inherit;
font-size: 0.875rem;
&:focus-visible {
outline: 2px solid var(--ts-brand);
outline-offset: 1px;
}
&:disabled {
color: var(--ts-ink-soft);
background: transparent;
}
}
.ts-check {
display: grid;
place-items: center;
}
input[type='checkbox'] {
width: 1rem;
height: 1rem;
accent-color: var(--ts-brand);
cursor: pointer;
}
.ts-type-icon {
display: inline-grid;
place-items: center;
width: 2rem;
height: 2rem;
border-radius: 0.5rem;
color: var(--tone);
background: color-mix(in srgb, var(--tone) 12%, var(--ts-surface));
}
.ts-matrix-wrap {
overflow-x: auto;
}
.ts-matrix {
border-collapse: collapse;
font-size: 0.8125rem;
th,
td {
padding: 0.375rem 0.5rem;
border-bottom: 1px solid var(--ts-line);
text-align: center;
}
th[scope='row'] {
text-align: left;
white-space: nowrap;
}
thead th {
vertical-align: bottom;
}
tr.is-archived th[scope='row'] {
opacity: 0.6;
}
td:hover {
background: var(--pi-color-primary-25);
}
}
/* @pi/ui styles every <button>: these opt back into a compact look. */
.ts-add,
.ts-archive,
.ts-template-toggle,
.ts-primary,
.ts-secondary {
min-width: 0 !important;
height: 2.125rem;
padding: 0 0.875rem !important;
border-radius: 999px !important;
font: inherit;
font-size: 0.8125rem;
font-weight: 600;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
.ts-add,
.ts-archive,
.ts-secondary {
border: 1px solid var(--ts-line-strong) !important;
background: var(--ts-surface) !important;
color: var(--ts-ink-soft) !important;
}
.ts-archive.is-archived {
border-style: dashed !important;
}
.ts-primary {
border: 0 !important;
background: var(--ts-brand) !important;
color: #fff !important;
}
.ts-savebar {
position: sticky;
bottom: 1rem;
z-index: 3;
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
border-radius: 999px;
background: var(--ts-surface-raised);
border: 1px solid var(--ts-line-strong);
box-shadow: var(--ts-lift);
font-size: 0.875rem;
&.is-dirty {
border-color: var(--ts-brand);
}
}
.ts-savebar__status {
flex: 1;
min-width: 0;
}
.ts-problems {
display: grid;
gap: 0.125rem;
margin: 0;
padding: 0;
list-style: none;
color: var(--ts-c-red);
font-size: 0.8125rem;
li {
display: flex;
align-items: center;
gap: 0.375rem;
}
}
@media (max-width: 720px) {
.ts-rows-head {
display: none;
}
.ts-status-grid,
.ts-type-grid {
grid-template-columns: 1fr 1fr;
}
.ts-grip,
.ts-type-icon {
display: none;
}
.ts-name {
grid-column: 1 / -1;
}
.ts-savebar {
flex-wrap: wrap;
border-radius: var(--ts-radius);
}
}
`,
})
export class SettingsPage {
protected readonly facade = inject(ProjectFacade);
protected readonly categories = CATEGORIES;
protected readonly colors = SETTING_COLORS;
protected readonly icons = TYPE_ICONS;
protected readonly fieldTypes = FIELD_TYPES;
/** What the API has; the draft is compared against it. */
private readonly saved = computed(
() => this.facade.project()?.settings ?? null,
);
protected readonly draft = signal<ProjectSettings | null>(null);
/** The key, typed to confirm deleting the project. */
protected readonly confirmKey = signal('');
protected readonly dirty = computed(
() =>
!!this.draft() &&
JSON.stringify(this.draft()) !== JSON.stringify(this.saved()),
);
protected readonly activeStatuses = computed(
() => this.draft()?.statuses.filter((s) => !s.archived) ?? [],
);
/** The same rules the API enforces, shown before saving. */
protected readonly problems = computed(() => {
const d = this.draft();
if (!d) return [];
const problems: string[] = [];
const lists = [d.statuses, d.issueTypes, d.areas, d.customFields];
if (lists.some((list) => list.some((item) => !item.name.trim())))
problems.push('Hay nombres vacíos');
if (
lists.some((list) => {
const ids = list.map((item) => item.id);
return ids.some((id, i) => ids.indexOf(id) !== i);
})
)
problems.push('Hay dos valores con el mismo nombre');
const active = d.statuses.filter((s) => !s.archived);
if (!active.some((s) => s.category === StatusCategory.TODO))
problems.push(
'Falta un estado activo «Pendiente» donde entren los tickets',
);
if (!active.some((s) => s.category === StatusCategory.DONE))
problems.push('Falta un estado activo «Hecho»');
if (!d.issueTypes.some((t) => !t.archived))
problems.push('Hace falta al menos un tipo de ticket activo');
for (const field of d.customFields)
if (
field.type === CustomFieldType.SELECT &&
!field.options.some((o) => o.trim())
)
problems.push(`El campo «${field.name}» necesita alguna opción`);
return problems;
});
constructor() {
// Follow the saved settings while there is nothing pending (after saving,
// the project comes back equal to the draft, so it is clean again).
effect(() => {
const saved = this.saved();
if (saved && !untracked(this.dirty))
this.draft.set(structuredClone(saved));
});
}
protected readonly toneOf = tone;
protected readonly categoryLabel = (c: StatusCategory) => CATEGORY[c].label;
protected readonly categoryHint = (c: StatusCategory) => CATEGORY[c].hint;
protected readonly iconLabel = (icon: string) => ICON_LABEL[icon] ?? icon;
protected readonly colorLabel = (c: (typeof SETTING_COLORS)[number]) =>
COLOR_LABEL[c];
/** Values the API does not have yet: they can still be removed or have their id follow the name. */
protected isNew(section: Section, id: string): boolean {
return !this.saved()?.[section].some((item) => item.id === id);
}
protected allows(from: string, to: string): boolean {
return !!this.draft()
?.transitions.find((t) => t.from === from)
?.to.includes(to);
}
/** '' (or anything below 1) clears the limit. */
protected wipFrom(value: string): number | null {
const limit = Math.round(Number(value));
return Number.isFinite(limit) && limit >= 1 ? Math.min(limit, 999) : null;
}
/** Index of the type whose template is open. */
protected readonly openTemplate = signal<number | null>(null);
protected hasTemplate(type: IssueTypeOption): boolean {
return !!(
type.template?.description?.trim() ||
type.template?.checklist.some((s) => s.trim())
);
}
/** Edits the template in the draft; empty lines go when saved. */
protected setTemplate(
index: number,
changes: { description?: string; checklist?: string[] },
): void {
this.patch((d) => {
const type = d.issueTypes[index];
const current = type.template ?? { description: null, checklist: [] };
type.template = {
description:
changes.description !== undefined
? changes.description || null
: current.description,
checklist: (changes.checklist ?? current.checklist).slice(0, 20),
};
});
}
protected edit(section: Section, index: number, changes: object): void {
this.patch((d) => Object.assign(d[section][index], changes));
}
protected setName(section: Section, index: number, name: string): void {
this.patch((d) => {
const item = d[section][index];
item.name = name;
if (this.isNew(section, item.id)) {
const id = this.uniqueId(d[section], idFrom(name), index);
if (section === 'statuses') this.renameStatus(d, item.id, id);
item.id = id;
}
});
}
protected setStatusName(index: number, name: string): void {
this.setName('statuses', index, name);
}
protected toggleTransition(from: string, to: string, on: boolean): void {
this.patch((d) => {
let row = d.transitions.find((t) => t.from === from);
if (!row) {
row = { from, to: [] };
d.transitions.push(row);
}
row.to = on
? [...new Set([...row.to, to])]
: row.to.filter((target) => target !== to);
});
}
protected reorder(event: CdkDragDrop<unknown>): void {
this.patch((d) =>
moveItemInArray(d.statuses, event.previousIndex, event.currentIndex),
);
}
protected addStatus(): void {
this.patch((d) => {
const id = this.uniqueId(d.statuses, 'NUEVO_ESTADO');
// Before the done/cancelled statuses, so it lands mid-board.
const at = d.statuses.findIndex(
(s) =>
s.category === StatusCategory.DONE ||
s.category === StatusCategory.CANCELLED,
);
d.statuses.splice(at === -1 ? d.statuses.length : at, 0, {
id,
name: 'Nuevo estado',
category: StatusCategory.IN_PROGRESS,
color: 'teal',
requiresReason: false,
archived: false,
});
d.transitions.push({ from: id, to: [] });
});
}
protected addType(): void {
this.patch((d) =>
d.issueTypes.push({
id: this.uniqueId(d.issueTypes, 'NUEVO_TIPO'),
name: 'Nuevo tipo',
icon: 'flag',
color: 'teal',
archived: false,
}),
);
}
protected addArea(): void {
this.patch((d) =>
d.areas.push({
id: this.uniqueId(d.areas, 'NUEVA_AREA'),
name: 'Nueva área',
archived: false,
}),
);
}
protected addField(): void {
this.patch((d) =>
d.customFields.push({
id: this.uniqueId(d.customFields, 'NUEVO_CAMPO'),
name: 'Nuevo campo',
type: CustomFieldType.TEXT,
options: [],
archived: false,
}),
);
}
protected setFieldType(index: number, type: CustomFieldType): void {
this.patch((d) => {
const field = d.customFields[index];
field.type = type;
if (type !== CustomFieldType.SELECT) field.options = [];
});
}
/** One per line; blank lines and repeats go when saved. */
protected setOptions(index: number, text: string): void {
this.patch((d) => {
d.customFields[index].options = text.split('\n').slice(0, 50);
});
}
/** Only for values never saved; saved ones are archived instead. */
protected remove(section: Section, index: number): void {
this.patch((d) => {
const [item] = d[section].splice(index, 1);
if (section === 'statuses') {
d.transitions = d.transitions
.filter((t) => t.from !== item.id)
.map((t) => ({ ...t, to: t.to.filter((to) => to !== item.id) }));
}
});
}
protected discard(): void {
const saved = this.saved();
if (saved) this.draft.set(structuredClone(saved));
}
protected save(): void {
const draft = this.draft();
if (!draft || !this.dirty() || this.problems().length) return;
// Options as the API keeps them, so the draft is clean once saved.
const cleaned: ProjectSettings = {
...draft,
customFields: draft.customFields.map((f) => ({
...f,
options: [...new Set(f.options.map((o) => o.trim()).filter(Boolean))],
})),
};
this.draft.set(cleaned);
this.facade.saveSettings({
...cleaned,
// Only rows with targets; unknown ids would be rejected anyway.
transitions: cleaned.transitions.filter((t) => t.to.length),
});
}
private patch(change: (draft: ProjectSettings) => void): void {
this.draft.update((d) => {
if (!d) return d;
const next = structuredClone(d);
change(next);
return next;
});
}
private uniqueId(list: { id: string }[], base: string, except = -1): string {
const taken = new Set(
list.filter((_, i) => i !== except).map((item) => item.id),
);
let id = base;
for (let n = 2; taken.has(id); n++) id = `${base.slice(0, 27)}_${n}`;
return id;
}
private renameStatus(d: ProjectSettings, from: string, to: string): void {
for (const row of d.transitions) {
if (row.from === from) row.from = to;
row.to = row.to.map((target) => (target === from ? to : target));
}
}
}