feat: formatted text, a list view, ticket details, public proposals and votes

Formatted text
- Descriptions, comments, replies and release notes render Markdown,
  sanitised with DOMPurify (tested against scripts, handlers and
  javascript: links). A pasted image is uploaded and written as
  ![name](attachment:<id>); the web fetches it with the reader's session,
  so it works on private projects. Every text box has a preview. The
  attachment upload now answers its attachmentId.

List view
- /p/:key/list: every ticket as rows, sortable by any column, filtered by
  text, open/closed, type, priority and assignee; status, priority and
  assignee change in place; bulk edit (the backlog's bar, now shared).

Ticket details
- Reactions on comments (GitHub's eight), for members and viewers.
- Duplicate a ticket: what it says, not where it stands.
- blockedBy: open tickets it waits for (BLOCKS / DEPENDS_ON), worked out
  when reading with one query per board or page; shown on cards, list
  rows and the ticket.

Public proposals
- A public project can take bug reports and ideas from anyone
  (acceptsProposals): POST /api/explore/projects/{project}/proposals and
  the form at /p/:key/proponer. They become tickets labelled «propuesta»,
  opened by TaskStream; a honeypot field and 5 per address every 15
  minutes keep spam out. No e-mail is asked: it would be public.

Votes
- Anyone signed in votes on a public project's tickets, members on a
  private one (voteIssue, PUT/DELETE /api/issues/{issue}/vote): votes and
  voted on each ticket, buttons on the ticket and the roadmap, a column
  in the list. The showcase carries votes and the open proposals.

MCP: vote_issue, duplicate_issue, react_to_comment; listings show
blockers and votes. Docs, Word and PDF updated; chat notifications
(Discord, Slack, Telegram) noted for later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 21:36:11 +02:00
parent 298766ad1a
commit f2001aca88
116 changed files with 17997 additions and 650 deletions

View File

@@ -8,3 +8,6 @@ export * from './lib/facades/explore.facade';
export * from './lib/facades/inbox.facade';
export * from './lib/facades/epics.facade';
export * from './lib/facades/backlog.facade';
export * from './lib/facades/list.facade';
export * from './lib/facades/propose.facade';
export type { ListCriteria } from './lib/events/list.events';

View File

@@ -6,6 +6,7 @@ export const epicsPageEvents = eventGroup({
source: 'Epics Page',
events: {
opened: type<{ projectId: string }>(),
voteRequested: type<{ issueId: string; on: boolean }>(),
},
});
@@ -14,5 +15,7 @@ export const epicsApiEvents = eventGroup({
events: {
loaded: type<Epic[]>(),
loadFailed: type<string>(),
voted: type<void>(),
voteFailed: type<string>(),
},
});

View File

@@ -69,6 +69,10 @@ export const issuePageEvents = eventGroup({
attachmentId: string;
}>(),
commentEditRequested: type<{ commentId: string; body: string }>(),
reactRequested: type<{ commentId: string; emoji: string; on: boolean }>(),
voteRequested: type<{ issueId: string; on: boolean }>(),
/** An image pasted into a text was uploaded (it joins the ticket's files). */
imagePasted: type<{ issueId: string }>(),
commentDeleteRequested: type<{ commentId: string }>(),
},
});

View File

@@ -0,0 +1,38 @@
import { type } from '@ngrx/signals';
import { eventGroup } from '@ngrx/signals/events';
import {
BulkChange,
BulkResult,
IssueListFilter,
IssuePage,
IssuePriority,
} from '@task-stream/web/tracker/domain';
/** What the list shows, beyond the project. */
export type ListCriteria = Omit<IssueListFilter, 'projectId' | 'limit'>;
export const listPageEvents = eventGroup({
source: 'List Page',
events: {
opened: type<{ projectId: string }>(),
filtered: type<ListCriteria>(),
statusChangeRequested: type<{ issueId: string; status: string }>(),
priorityChangeRequested: type<{
issueId: string;
priority: IssuePriority;
}>(),
assignRequested: type<{ issueId: string; assigneeId: string | null }>(),
bulkRequested: type<{ issueIds: string[]; change: BulkChange }>(),
},
});
export const listApiEvents = eventGroup({
source: 'List API',
events: {
loaded: type<IssuePage>(),
loadFailed: type<string>(),
changed: type<void>(),
changeFailed: type<string>(),
bulkDone: type<BulkResult>(),
},
});

View File

@@ -48,6 +48,10 @@ export const projectPageEvents = eventGroup({
analyticsRequested: type<{ projectId: string; days: number }>(),
burnupRequested: type<{ releaseId: string }>(),
visibilityChangeRequested: type<{ projectId: string; isPublic: boolean }>(),
proposalsChangeRequested: type<{
projectId: string;
acceptsProposals: boolean;
}>(),
deleteRequested: type<{ projectId: string; confirmKey: string }>(),
},
});

View File

@@ -19,6 +19,11 @@ export class EpicsFacade {
open(projectId: string): void {
this.dispatch.opened({ projectId });
}
/** Votes for an epic (`on`) or takes the vote back. */
vote(issueId: string, on: boolean): void {
this.dispatch.voteRequested({ issueId, on });
}
}
/** Store + facade of the epics view, for its route component. */

View File

@@ -4,10 +4,11 @@ import {
Attachment,
AttachmentsGateway,
IssueLink,
IssuesGateway,
IssueLinkType,
UpdateIssueInput,
} from '@task-stream/web/tracker/domain';
import { Observable } from 'rxjs';
import { map, Observable } from 'rxjs';
import { issuePageEvents } from '../events/issue.events';
import { IssueStore } from '../stores/issue.store';
@@ -20,6 +21,7 @@ export class IssueFacade {
private readonly store = inject(IssueStore);
private readonly dispatch = injectDispatch(issuePageEvents);
private readonly files = inject(AttachmentsGateway);
private readonly issues = inject(IssuesGateway);
readonly issue = this.store.issue;
readonly comments = this.store.comments;
@@ -178,6 +180,43 @@ export class IssueFacade {
return this.files.download(issueId, attachment);
}
/** A file's bytes by id alone (an image inside a description or comment). */
fileById(attachmentId: string): Observable<Blob> {
return this.fileOf({ id: attachmentId } as Attachment);
}
/**
* Uploads an image pasted into a text and answers its id, to write
* `![name](attachment:<id>)`. It also shows among the ticket's files.
*/
uploadImage(file: File): Observable<string> {
const issueId = this.store.issue()?.id ?? '';
return this.files.upload(issueId, file).pipe(
map((uploaded) => {
this.dispatch.imagePasted({ issueId });
return uploaded.attachmentId;
}),
);
}
/** Votes for the open ticket (`on`) or takes the vote back. */
vote(on: boolean): void {
this.withIssue((issueId) => this.dispatch.voteRequested({ issueId, on }));
}
/** Adds (`on`) or takes back the signed-in person's reaction. */
react(commentId: string, emoji: string, on: boolean): void {
this.dispatch.reactRequested({ commentId, emoji, on });
}
/** A copy of what the open ticket says; answers its key. */
duplicate(): Observable<string | null> {
const issueId = this.store.issue()?.id ?? '';
return this.issues
.duplicate(issueId)
.pipe(map((result) => result.key ?? null));
}
editComment(commentId: string, body: string): void {
this.dispatch.commentEditRequested({ commentId, body });
}

View File

@@ -0,0 +1,51 @@
import { inject, Injectable, Provider } from '@angular/core';
import { injectDispatch } from '@ngrx/signals/events';
import { BulkChange, IssuePriority } from '@task-stream/web/tracker/domain';
import { ListCriteria, listPageEvents } from '../events/list.events';
import { LIST_LIMIT, ListStore } from '../stores/list.store';
/** The list view of a project, for presenters. */
@Injectable()
export class ListFacade {
private readonly store = inject(ListStore);
private readonly dispatch = injectDispatch(listPageEvents);
/** Most recently updated first (the first LIST_LIMIT). */
readonly issues = this.store.issues;
readonly total = this.store.total;
readonly criteria = this.store.criteria;
readonly limit = LIST_LIMIT;
/** False until the first load: show skeletons, not empty states. */
readonly loaded = this.store.loaded;
readonly error = this.store.error;
open(projectId: string): void {
this.dispatch.opened({ projectId });
}
filter(criteria: ListCriteria): void {
this.dispatch.filtered(criteria);
}
changeStatus(issueId: string, status: string): void {
this.dispatch.statusChangeRequested({ issueId, status });
}
changePriority(issueId: string, priority: IssuePriority): void {
this.dispatch.priorityChangeRequested({ issueId, priority });
}
assign(issueId: string, assigneeId: string | null): void {
this.dispatch.assignRequested({ issueId, assigneeId });
}
/** The same change on several tickets (each may refuse on its own). */
bulkUpdate(issueIds: string[], change: BulkChange): void {
if (issueIds.length) this.dispatch.bulkRequested({ issueIds, change });
}
}
/** Store + facade of the list view, for its route component. */
export function provideListFacade(): Provider[] {
return [ListStore, ListFacade];
}

View File

@@ -161,6 +161,13 @@ export class ProjectFacade {
this.dispatch.visibilityChangeRequested({ projectId, isPublic });
}
/** Take bug reports and ideas from anyone (while public). Owners and admins. */
setAcceptsProposals(acceptsProposals: boolean): void {
const projectId = this.projectId();
if (projectId)
this.dispatch.proposalsChangeRequested({ projectId, acceptsProposals });
}
/**
* Owner only, typing the key to confirm. Tickets, comments and releases go
* too; on success it navigates home.

View File

@@ -0,0 +1,20 @@
import { inject, Injectable } from '@angular/core';
import {
ProposalInput,
ProposalResult,
ProposalsGateway,
} from '@task-stream/web/tracker/domain';
import { Observable } from 'rxjs';
/** The public form of a project: anyone reports a bug or proposes an idea. */
@Injectable({ providedIn: 'root' })
export class ProposeFacade {
private readonly proposals = inject(ProposalsGateway);
submit(
projectKey: string,
proposal: ProposalInput,
): Observable<ProposalResult> {
return this.proposals.submit(projectKey, proposal);
}
}

View File

@@ -12,9 +12,9 @@ import {
IssuesGateway,
TrackerRealtimeGateway,
} from '@task-stream/web/tracker/domain';
import { debounceTime, startWith, switchMap } from 'rxjs';
import { debounceTime, merge, mergeMap, startWith, switchMap, tap } from 'rxjs';
import { epicsApiEvents, epicsPageEvents } from '../events/epics.events';
import { describeError } from '../notifications';
import { describeError, Notifications } from '../notifications';
interface EpicsState {
epics: Epic[];
@@ -42,11 +42,16 @@ export const EpicsStore = signalStore(
events = inject(Events),
issues = inject(IssuesGateway),
realtime = inject(TrackerRealtimeGateway),
notifications = inject(Notifications),
) => ({
// Any ticket of the project may move an epic's progress: reload, calmly.
load$: events.on(epicsPageEvents.opened).pipe(
switchMap(({ payload }) =>
realtime.issueChanges(payload.projectId).pipe(
merge(
realtime.issueChanges(payload.projectId),
// One's own vote, without waiting for the live update.
events.on(epicsApiEvents.voted),
).pipe(
debounceTime(500),
startWith(null),
switchMap(() =>
@@ -61,6 +66,19 @@ export const EpicsStore = signalStore(
),
),
),
vote$: events.on(epicsPageEvents.voteRequested).pipe(
mergeMap(({ payload }) =>
issues.vote(payload.issueId, payload.on).pipe(
mapResponse({
next: () => epicsApiEvents.voted(),
error: (error) => epicsApiEvents.voteFailed(describeError(error)),
}),
),
),
),
voteFeedback$: events
.on(epicsApiEvents.voteFailed)
.pipe(tap(({ payload }) => notifications.error(payload))),
}),
),
);

View File

@@ -244,7 +244,11 @@ export const IssueStore = signalStore(
* ticket, its comments and its subtasks are asked for twice.
*/
catchUp$: events
.on(issueApiEvents.commandSucceeded, issueApiEvents.checklistSaved)
.on(
issueApiEvents.commandSucceeded,
issueApiEvents.checklistSaved,
issuePageEvents.imagePasted,
)
.pipe(
map(() => store.issue()),
filter((issue): issue is Issue => !!issue),
@@ -391,6 +395,30 @@ export const IssueStore = signalStore(
),
),
),
events.on(issuePageEvents.voteRequested).pipe(
mergeMap(({ payload }) =>
issues.vote(payload.issueId, payload.on).pipe(
// The count is the feedback.
mapResponse({
next: () => issueApiEvents.checklistSaved(),
error: (error) =>
issueApiEvents.commandFailed(describeError(error)),
}),
),
),
),
events.on(issuePageEvents.reactRequested).pipe(
mergeMap(({ payload }) =>
comments.react(payload.commentId, payload.emoji, payload.on).pipe(
// A reaction is not worth a toast either.
mapResponse({
next: () => issueApiEvents.checklistSaved(),
error: (error) =>
issueApiEvents.commandFailed(describeError(error)),
}),
),
),
),
events.on(issuePageEvents.checklistUpdateRequested).pipe(
mergeMap(({ payload }) =>
issues

View File

@@ -0,0 +1,183 @@
import { inject } from '@angular/core';
import { mapResponse } from '@ngrx/operators';
import { signalStore, withState } from '@ngrx/signals';
import {
Events,
on,
withEventHandlers,
withReducer,
} from '@ngrx/signals/events';
import {
IssuesGateway,
IssueSummary,
TrackerRealtimeGateway,
} from '@task-stream/web/tracker/domain';
import {
combineLatest,
concatMap,
debounceTime,
map,
merge,
mergeMap,
startWith,
switchMap,
tap,
} from 'rxjs';
import {
ListCriteria,
listApiEvents,
listPageEvents,
} from '../events/list.events';
import { describeError, Notifications } from '../notifications';
/** The list asks for this many at most; past that, the filters narrow it. */
export const LIST_LIMIT = 200;
interface ListState {
projectId: string | null;
criteria: ListCriteria;
issues: IssueSummary[];
total: number;
loaded: boolean;
error: string | null;
}
/** Every ticket of a project that fits the filters, as rows. Live. */
export const ListStore = signalStore(
withState<ListState>({
projectId: null,
criteria: {},
issues: [],
total: 0,
loaded: false,
error: null,
}),
withReducer(
on(listPageEvents.opened, ({ payload }) => ({
projectId: payload.projectId,
loaded: false,
error: null,
})),
on(listPageEvents.filtered, ({ payload }) => ({ criteria: payload })),
on(listApiEvents.loaded, ({ payload }) => ({
issues: payload.items,
total: payload.total,
loaded: true,
error: null,
})),
on(listApiEvents.loadFailed, ({ payload }) => ({
loaded: true,
error: payload,
})),
),
withEventHandlers(
(
store,
events = inject(Events),
issues = inject(IssuesGateway),
realtime = inject(TrackerRealtimeGateway),
notifications = inject(Notifications),
) => {
const command = (request: ReturnType<IssuesGateway['assign']>) =>
request.pipe(
mapResponse({
next: () => listApiEvents.changed(),
error: (error) => listApiEvents.changeFailed(describeError(error)),
}),
);
return {
/**
* Reloads on opening, on each filter and on anyone's change (calmly);
* also after this page's own changes, not to wait for the live one.
*/
load$: events.on(listPageEvents.opened).pipe(
switchMap(({ payload }) =>
combineLatest([
events.on(listPageEvents.filtered).pipe(
map(({ payload: criteria }) => criteria),
startWith(store.criteria()),
debounceTime(250),
),
merge(
realtime.issueChanges(payload.projectId),
events.on(
listApiEvents.changed,
listApiEvents.changeFailed,
listApiEvents.bulkDone,
),
).pipe(debounceTime(400), startWith(null)),
]).pipe(
switchMap(([criteria]) =>
issues
.list({
...criteria,
projectId: payload.projectId,
limit: LIST_LIMIT,
})
.pipe(
mapResponse({
next: (page) => listApiEvents.loaded(page),
error: (error) =>
listApiEvents.loadFailed(describeError(error)),
}),
),
),
),
),
),
status$: events.on(listPageEvents.statusChangeRequested).pipe(
mergeMap(({ payload }) =>
command(
issues.changeStatus({
issueId: payload.issueId,
status: payload.status,
}),
),
),
),
priority$: events.on(listPageEvents.priorityChangeRequested).pipe(
mergeMap(({ payload }) =>
command(
issues.update({
issueId: payload.issueId,
priority: payload.priority,
}),
),
),
),
assign$: events
.on(listPageEvents.assignRequested)
.pipe(
mergeMap(({ payload }) =>
command(issues.assign(payload.issueId, payload.assigneeId)),
),
),
bulk$: events.on(listPageEvents.bulkRequested).pipe(
concatMap(({ payload }) =>
issues.bulkUpdate(payload.issueIds, payload.change).pipe(
mapResponse({
next: (result) => listApiEvents.bulkDone(result),
error: (error) =>
listApiEvents.changeFailed(describeError(error)),
}),
),
),
),
bulkFeedback$: events.on(listApiEvents.bulkDone).pipe(
tap(({ payload }) => {
const refused = payload.results.filter((r) => !r.ok);
if (!refused.length)
notifications.success(`${payload.updated} tickets actualizados`);
else
notifications.error(
`${payload.updated} actualizados; ${refused.length} no: ${refused[0].error}`,
);
}),
),
feedback$: events
.on(listApiEvents.changeFailed)
.pipe(tap(({ payload }) => notifications.error(payload))),
};
},
),
);

View File

@@ -419,6 +419,20 @@ export const ProjectStore = signalStore(
),
),
),
events
.on(projectPageEvents.proposalsChangeRequested)
.pipe(
mergeMap(({ payload }) =>
runCommand(
projects.update(payload),
payload.acceptsProposals
? 'Formulario público abierto: cualquiera puede proponer'
: 'Formulario público cerrado',
projectApiEvents.commandSucceeded,
projectApiEvents.commandFailed,
),
),
),
events
.on(projectPageEvents.releaseCreateRequested)
.pipe(

View File

@@ -58,3 +58,6 @@ export enum NotificationKind {
ADDED_TO_PROJECT = 'ADDED_TO_PROJECT',
REMINDER = 'REMINDER',
}
/** The reactions a comment takes, in the order they are offered (GitHub's). */
export const REACTIONS = ['👍', '👎', '😄', '🎉', '😕', '❤️', '🚀', '👀'];

View File

@@ -17,6 +17,24 @@ export interface UpdateProjectInput {
name?: string;
description?: string | null;
isPublic?: boolean;
acceptsProposals?: boolean;
}
/** A bug report or an idea from anyone, through a public project's form. */
export interface ProposalInput {
kind: 'BUG' | 'IDEA';
title: string;
description: string;
/** How they sign it (optional; no e-mail: it would be public). */
author: string;
/** Left empty by people; bots fill it in. */
website: string;
}
export interface ProposalResult {
/** The ticket it became (null when it was dropped as spam). */
key: string | null;
path: string | null;
}
export interface CreateIssueInput {
@@ -68,6 +86,19 @@ export interface CreateReleaseInput {
targetDate?: string | null;
}
/** The list view of a project: every ticket that fits, any status. */
export interface IssueListFilter {
projectId: string;
/** Matches key, title or description. */
search?: string;
categories?: StatusCategory[];
types?: string[];
priorities?: IssuePriority[];
assigneeId?: string;
unassigned?: boolean;
limit: number;
}
/** "My work": tickets across all my projects. */
export interface MyIssuesFilter {
/** true: assigned to me. false: any ticket of my projects. */

View File

@@ -26,6 +26,8 @@ export interface Project {
description: string | null;
/** Anyone can read it, also without signing in. */
isPublic: boolean;
/** Takes bug reports and ideas from anyone (while public). */
acceptsProposals: boolean;
owner: UserRef;
members: ProjectMember[];
settings: ProjectSettings;
@@ -112,6 +114,11 @@ export interface IssueSummary {
labels: string[];
/** The epic or ticket this one breaks down. */
parent: IssueParent | null;
/** Open tickets it waits for: the ones that block it or it depends on. */
blockedBy: IssueParent[];
/** How many want it done, and whether I am one of them. */
votes: number;
voted: boolean;
/** Place in the backlog and in its board column (ascending, as text). */
rank: string;
/** Estimate; null when nobody estimated it. */
@@ -275,6 +282,8 @@ export interface Comment {
replyTo: string | null;
/** Deleted, but kept (without its text) while it has replies. */
deleted: boolean;
/** 👍… and who chose each (only the ones somebody chose). */
reactions: { emoji: string; users: UserRef[] }[];
createdAt: string;
editedAt: string | null;
}

View File

@@ -38,6 +38,9 @@ import {
CreateReleaseInput,
LinkIssuesInput,
MemberInput,
IssueListFilter,
ProposalInput,
ProposalResult,
MyIssuesFilter,
UpdateIssueInput,
UpdateProjectInput,
@@ -88,9 +91,15 @@ export abstract class IssuesGateway {
abstract board(filter: BoardFilter): Observable<BoardColumn[]>;
abstract issue(idOrKey: string): Observable<Issue>;
abstract search(projectId: string, text: string): Observable<IssueSummary[]>;
/** A project's tickets for the list view (most recently updated first). */
abstract list(filter: IssueListFilter): Observable<IssuePage>;
/** Tickets across all my projects (most recently updated first). */
abstract mine(filter: MyIssuesFilter): Observable<IssuePage>;
abstract create(input: CreateIssueInput): Observable<CommandResult>;
/** Votes for it (`on`) or takes the vote back. */
abstract vote(issueId: string, on: boolean): Observable<CommandResult>;
/** A copy of what the ticket says; the result carries its key. */
abstract duplicate(issueId: string): Observable<CommandResult>;
abstract update(input: UpdateIssueInput): Observable<CommandResult>;
abstract changeStatus(input: ChangeStatusInput): Observable<CommandResult>;
abstract assign(
@@ -236,16 +245,33 @@ export abstract class CommentsGateway {
replyTo?: string | null,
): Observable<CommandResult>;
abstract edit(commentId: string, body: string): Observable<CommandResult>;
/** Adds (`on`) or takes back one's reaction. */
abstract react(
commentId: string,
emoji: string,
on: boolean,
): Observable<CommandResult>;
abstract remove(commentId: string): Observable<CommandResult>;
}
/** A ticket's files. Uploads and downloads go through the REST API. */
/** The ticket's acknowledgement and the new file's id. */
export type AttachmentUploaded = CommandResult & { attachmentId: string };
/** The public form: no session needed. */
export abstract class ProposalsGateway {
abstract submit(
projectKey: string,
proposal: ProposalInput,
): Observable<ProposalResult>;
}
export abstract class AttachmentsGateway {
abstract upload(
issueId: string,
file: File,
commentId?: string | null,
): Observable<CommandResult>;
): Observable<AttachmentUploaded>;
/** The file's bytes, to show (images) or save. */
abstract download(issueId: string, attachment: Attachment): Observable<Blob>;
abstract remove(

View File

@@ -21,6 +21,7 @@ import {
DeleteCommentDocument,
EditCommentDocument,
IssueCommentsDocument,
ReactToCommentDocument,
PublishReleaseDocument,
ReleaseBurnupDocument,
ReleaseNotesDraftDocument,
@@ -52,6 +53,16 @@ export class GraphqlCommentsGateway extends CommentsGateway {
.pipe(map((d) => toCommandResult(d.addComment)));
}
react(
commentId: string,
emoji: string,
on: boolean,
): Observable<CommandResult> {
return this.gql
.mutate(ReactToCommentDocument, { commentId, emoji, on })
.pipe(map((d) => toCommandResult(d.reactToComment)));
}
edit(commentId: string, body: string): Observable<CommandResult> {
return this.gql
.mutate(EditCommentDocument, { commentId, body })

View File

@@ -11,6 +11,7 @@ import {
Issue,
IssuePage,
IssuesGateway,
IssueListFilter,
IssueSummary,
LinkIssuesInput,
MyIssuesFilter,
@@ -25,10 +26,12 @@ import {
BoardDocument,
ChangeIssueStatusDocument,
CreateIssueDocument,
DuplicateIssueDocument,
DueIssuesDocument,
EpicsDocument,
IssueChildrenDocument,
IssueDocument,
IssueListDocument,
LinkIssuesDocument,
MyIssuesDocument,
RankIssueDocument,
@@ -41,6 +44,7 @@ import {
SetIssueReleaseDocument,
UnlinkIssuesDocument,
UnwatchIssueDocument,
VoteIssueDocument,
WatchIssueDocument,
UpdateChecklistItemDocument,
UpdateIssueDocument,
@@ -102,6 +106,24 @@ export class GraphqlIssuesGateway extends IssuesGateway {
);
}
list(filter: IssueListFilter): Observable<IssuePage> {
const { limit, ...criteria } = filter;
return this.gql
.query(IssueListDocument, {
filter: {
...criteria,
search: criteria.search?.trim() || undefined,
} as never,
limit,
})
.pipe(
map((d) => ({
items: d.issues.items.map(toIssueSummary),
total: d.issues.total,
})),
);
}
search(projectId: string, text: string): Observable<IssueSummary[]> {
return this.gql
.query(SearchIssuesDocument, { filter: { projectId, search: text } })
@@ -114,6 +136,12 @@ export class GraphqlIssuesGateway extends IssuesGateway {
.pipe(map((d) => toCommandResult(d.createIssue)));
}
duplicate(issueId: string): Observable<CommandResult> {
return this.gql
.mutate(DuplicateIssueDocument, { issueId })
.pipe(map((d) => toCommandResult(d.duplicateIssue)));
}
update(input: UpdateIssueInput): Observable<CommandResult> {
return this.gql
.mutate(UpdateIssueDocument, { input: input as never })
@@ -147,6 +175,12 @@ export class GraphqlIssuesGateway extends IssuesGateway {
.pipe(map((d) => toCommandResult(d.unlinkIssues)));
}
vote(issueId: string, on: boolean): Observable<CommandResult> {
return this.gql
.mutate(VoteIssueDocument, { issueId, on })
.pipe(map((d) => toCommandResult(d.voteIssue)));
}
watch(issueId: string, watching: boolean): Observable<CommandResult> {
return watching
? this.gql

View File

@@ -7,6 +7,7 @@ import {
import {
Attachment,
AttachmentsGateway,
AttachmentUploaded,
CommandResult,
} from '@task-stream/web/tracker/domain';
import { from, Observable, switchMap } from 'rxjs';
@@ -25,12 +26,14 @@ export class HttpAttachmentsGateway extends AttachmentsGateway {
issueId: string,
file: File,
commentId?: string | null,
): Observable<CommandResult> {
): Observable<AttachmentUploaded> {
const body = new FormData();
body.append('file', file, file.name);
if (commentId) body.append('commentId', commentId);
return this.authorized((headers) =>
this.http.post<CommandResult>(this.url(issueId), body, { headers }),
this.http.post<AttachmentUploaded>(this.url(issueId), body, {
headers,
}),
);
}

View File

@@ -0,0 +1,30 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { API_CONFIG } from '@task-stream/web/shared/infrastructure';
import {
ProposalInput,
ProposalResult,
ProposalsGateway,
} from '@task-stream/web/tracker/domain';
import { Observable } from 'rxjs';
/** The public form posts over REST, without a session (`/api/explore/...`). */
@Injectable()
export class HttpProposalsGateway extends ProposalsGateway {
private readonly http = inject(HttpClient);
private readonly api = inject(API_CONFIG);
submit(
projectKey: string,
proposal: ProposalInput,
): Observable<ProposalResult> {
return this.http.post<ProposalResult>(
`${this.api.restUrl}/explore/projects/${encodeURIComponent(projectKey)}/proposals`,
{
...proposal,
description: proposal.description.trim() || undefined,
author: proposal.author.trim() || undefined,
},
);
}
}

View File

@@ -9,6 +9,7 @@ fragment ProjectFields on Project {
name
description
isPublic
acceptsProposals
updatedAt
version
owner {
@@ -83,6 +84,13 @@ fragment IssueSummaryFields on Issue {
key
title
}
blockedBy {
id
key
title
}
votes
voted
rank
storyPoints
startDate
@@ -143,6 +151,12 @@ fragment CommentFields on Comment {
body
replyTo
deleted
reactions {
emoji
users {
...UserRefFields
}
}
createdAt
editedAt
author {

File diff suppressed because one or more lines are too long

View File

@@ -249,3 +249,30 @@ query DueIssues($filter: IssueFilterInput!) {
}
}
}
query IssueList($filter: IssueFilterInput!, $limit: Int!) {
issues(filter: $filter, limit: $limit) {
items {
...IssueSummaryFields
}
total
}
}
mutation ReactToComment($commentId: ID!, $emoji: String!, $on: Boolean!) {
reactToComment(commentId: $commentId, emoji: $emoji, on: $on) {
...CommandResultFields
}
}
mutation DuplicateIssue($issueId: ID!) {
duplicateIssue(issueId: $issueId) {
...CommandResultFields
}
}
mutation VoteIssue($issueId: ID!, $on: Boolean!) {
voteIssue(issueId: $issueId, on: $on) {
...CommandResultFields
}
}

View File

@@ -5,6 +5,7 @@ import {
import {
ActivityGateway,
AttachmentsGateway,
ProposalsGateway,
CommentsGateway,
IssuesGateway,
NotificationsGateway,
@@ -28,6 +29,7 @@ import {
import { GraphqlIssuesGateway } from './adapters/graphql-issues.gateway';
import { GraphqlNotificationsGateway } from './adapters/graphql-notifications.gateway';
import { HttpAttachmentsGateway } from './adapters/http-attachments.gateway';
import { HttpProposalsGateway } from './adapters/http-proposals.gateway';
import { GraphqlProjectsGateway } from './adapters/graphql-projects.gateway';
import { GraphqlRealtimeGateway } from './adapters/graphql-realtime.gateway';
import { GraphqlSavedFiltersGateway } from './adapters/graphql-saved-filters.gateway';
@@ -46,6 +48,7 @@ export function provideTrackerInfrastructure(): EnvironmentProviders {
{ provide: ReleasesGateway, useClass: GraphqlReleasesGateway },
{ provide: ActivityGateway, useClass: GraphqlActivityGateway },
{ provide: AttachmentsGateway, useClass: HttpAttachmentsGateway },
{ provide: ProposalsGateway, useClass: HttpProposalsGateway },
{ provide: UsersGateway, useClass: GraphqlUsersGateway },
{ provide: NotificationsGateway, useClass: GraphqlNotificationsGateway },
{ provide: TrackerRealtimeGateway, useClass: GraphqlRealtimeGateway },

View File

@@ -6,6 +6,13 @@
"projectType": "library",
"tags": ["scope:web-tracker", "type:presenters"],
"targets": {
"test": {
"executor": "@nx/vitest:test",
"outputs": ["{options.reportsDirectory}"],
"options": {
"reportsDirectory": "coverage/libs/web/tracker/presenters"
}
},
"lint": {
"executor": "@nx/eslint:lint"
}

View File

@@ -10,15 +10,11 @@ import {
} from '@angular/core';
import { RouterLink } from '@angular/router';
import {
PiActionButtonComponent,
PiEmptyStateComponent,
PiIconButtonComponent,
PiIconComponent,
PiNoteComponent,
PiSelectFieldComponent,
PiSkeletonComponent,
PiTextFieldComponent,
type PiSelectFieldOption,
} from '@pi/ui';
import {
BacklogFacade,
@@ -27,31 +23,26 @@ import {
} from '@task-stream/web/tracker/application';
import {
BulkChange,
IssuePriority,
IssueSummary,
sumPoints,
} from '@task-stream/web/tracker/domain';
import { initials, options, PRIORITY, statusLook, typeLook } from '../ui/copy';
/** "Nobody" / "no sprint" in the bulk selects. */
const NOBODY = '__none__';
import { BulkBarComponent } from '../ui/bulk-bar';
import { initials, PRIORITY, statusLook, typeLook } from '../ui/copy';
/** /p/:key/backlog — what is still to start, in the order the team takes it. */
@Component({
selector: 'ts-backlog-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
BulkBarComponent,
RouterLink,
CdkDrag,
CdkDropList,
PiActionButtonComponent,
PiEmptyStateComponent,
PiIconButtonComponent,
PiIconComponent,
PiNoteComponent,
PiSelectFieldComponent,
PiSkeletonComponent,
PiTextFieldComponent,
],
providers: [provideBacklogFacade()],
template: `
@@ -85,60 +76,12 @@ const NOBODY = '__none__';
<pi-skeleton shape="text" [lines]="8" />
} @else if (facade.issues().length) {
@if (project.canContribute()) {
<div class="ts-bulk" role="toolbar" aria-label="Edición en bloque">
<label class="ts-bulk__all">
<input
type="checkbox"
[checked]="allSelected()"
[indeterminate]="selected().size > 0 && !allSelected()"
(change)="selectAll($any($event.target).checked)"
/>
{{
selected().size
? selected().size + ' seleccionados'
: 'Seleccionar'
}}
</label>
@if (selected().size) {
<pi-select-field [options]="bulkFields" [(value)]="bulkField" />
@switch (bulkField()) {
@case ('status') {
<pi-select-field
[options]="statusOptions()"
[(value)]="bulkValue"
/>
}
@case ('assignee') {
<pi-select-field
[options]="assigneeOptions()"
[(value)]="bulkValue"
/>
}
@case ('sprint') {
<pi-select-field
[options]="sprintOptions()"
[(value)]="bulkValue"
/>
}
@case ('priority') {
<pi-select-field
[options]="priorityOptions"
[(value)]="bulkValue"
/>
}
@case ('label') {
<pi-text-field placeholder="etiqueta" [(value)]="bulkLabel" />
}
}
<pi-action-button
size="small"
color="primary"
text="Aplicar"
[disabled]="!canApply()"
(execute)="applyBulk()"
/>
}
</div>
<ts-bulk-bar
[count]="selected().size"
[allSelected]="allSelected()"
(selectAll)="selectAll($event)"
(apply)="applyBulk($event)"
/>
}
<ol
class="ts-backlog ts-panel"
@@ -261,23 +204,6 @@ const NOBODY = '__none__';
.ts-backlog__row.is-selected {
background: color-mix(in srgb, var(--ts-brand) 8%, var(--ts-surface));
}
.ts-bulk {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
margin-bottom: 0.75rem;
pi-select-field,
pi-text-field {
width: 13rem;
}
}
.ts-bulk__all {
display: inline-flex;
gap: 0.375rem;
align-items: center;
font-size: 0.875rem;
}
.ts-backlog__trash {
margin: 1rem 0 0;
font-size: 0.875rem;
@@ -342,46 +268,6 @@ export class BacklogPage {
this.facade.issues().length > 0 &&
this.facade.issues().every((i) => this.selected().has(i.id)),
);
protected readonly bulkFields: PiSelectFieldOption<string>[] = [
{ value: 'status', label: 'Mover a…' },
{ value: 'assignee', label: 'Asignar a…' },
{ value: 'sprint', label: 'Sprint…' },
{ value: 'priority', label: 'Prioridad…' },
{ value: 'label', label: 'Añadir etiqueta…' },
];
protected readonly bulkField = signal<string | null>('status');
protected readonly bulkValue = signal<string | null>(null);
protected readonly bulkLabel = signal('');
protected readonly statusOptions = computed<PiSelectFieldOption<string>[]>(
() =>
this.project
.workflow()
.settings.statuses.filter((s) => !s.archived)
.map((s) => ({ value: s.id, label: s.name })),
);
protected readonly assigneeOptions = computed<PiSelectFieldOption<string>[]>(
() => [
{ value: NOBODY, label: 'Nadie (sin asignar)' },
...this.project
.members()
.map((m) => ({ value: m.user.id, label: m.user.name })),
],
);
protected readonly sprintOptions = computed<PiSelectFieldOption<string>[]>(
() => [
{ value: NOBODY, label: 'Backlog (sin sprint)' },
...this.project
.openSprints()
.map((s) => ({ value: s.id, label: s.name })),
],
);
protected readonly priorityOptions = options(PRIORITY);
protected readonly canApply = computed(() =>
this.bulkField() === 'label'
? !!this.bulkLabel().trim()
: !!this.bulkValue(),
);
protected toggle(issueId: string, on: boolean): void {
this.selected.update((set) => {
const next = new Set(set);
@@ -395,29 +281,9 @@ export class BacklogPage {
this.selected.set(new Set(on ? this.facade.issues().map((i) => i.id) : []));
}
protected applyBulk(): void {
const value = this.bulkValue();
const change: BulkChange = {};
switch (this.bulkField()) {
case 'status':
if (value) change.status = value;
break;
case 'assignee':
change.assigneeId = value === NOBODY ? null : value;
break;
case 'sprint':
change.sprintId = value === NOBODY ? null : value;
break;
case 'priority':
if (value) change.priority = value as IssuePriority;
break;
case 'label':
change.addLabels = [this.bulkLabel().trim().toLowerCase()];
break;
}
protected applyBulk(change: BulkChange): void {
this.facade.bulkUpdate([...this.selected()], change);
this.selected.set(new Set());
this.bulkLabel.set('');
}
protected readonly points = computed(() => sumPoints(this.facade.issues()));
protected readonly unestimated = computed(

View File

@@ -445,18 +445,6 @@ a.ts-key {
margin: 0.5rem 0;
}
.ts-mention {
padding: 0 0.2em;
border-radius: 0.25em;
background: color-mix(in oklab, var(--ts-brand) 14%, transparent);
color: inherit;
font-weight: 600;
}
.ts-mention.is-me {
background: color-mix(in oklab, var(--ts-brand) 30%, transparent);
}
.ts-mentions {
display: flex;
flex-wrap: wrap;
@@ -573,3 +561,107 @@ a.ts-key {
gap: 0.75rem;
align-items: center;
}
// Waiting for other tickets: shown next to the key, with links to them.
.ts-blocked {
display: inline-flex;
flex-wrap: wrap;
gap: 0.375rem;
align-items: center;
padding: 0.125rem 0.5rem;
border-radius: 999px;
background: color-mix(in srgb, var(--ts-c-red, #d33) 12%, transparent);
color: var(--ts-c-red, var(--ts-ink));
font-size: 0.8125rem;
font-weight: 600;
.ts-key {
color: inherit;
}
}
// 👍 2 · 🎉 1 · (+)
.ts-reactions {
display: flex;
flex-wrap: wrap;
gap: 0.375rem;
align-items: center;
margin-top: 0.5rem;
}
.ts-reaction {
display: inline-flex;
gap: 0.25rem;
align-items: center;
// @pi/ui styles every <button> too specifically to override otherwise.
min-width: 0 !important;
height: auto !important;
padding: 0.125rem 0.5rem !important;
border: 1px solid var(--ts-line) !important;
border-radius: 999px !important;
background: var(--ts-surface);
color: inherit;
font: inherit;
font-size: 0.875rem;
cursor: pointer;
.ts-mono {
font-size: 0.75rem;
}
&.is-mine {
border-color: var(--ts-brand) !important;
background: color-mix(in srgb, var(--ts-brand) 12%, var(--ts-surface));
}
&:disabled {
cursor: default;
}
}
.ts-reaction-picker {
position: relative;
summary {
display: inline-grid;
place-items: center;
width: 1.75rem;
height: 1.625rem;
border: 1px dashed var(--ts-line-strong, var(--ts-line));
border-radius: 999px;
color: var(--ts-muted);
cursor: pointer;
list-style: none;
&::-webkit-details-marker {
display: none;
}
}
}
.ts-reaction-picker__menu {
position: absolute;
z-index: 5;
bottom: calc(100% + 0.375rem);
left: 0;
display: flex;
gap: 0.125rem;
padding: 0.25rem;
border: 1px solid var(--ts-line);
border-radius: 0.75rem;
background: var(--ts-surface);
box-shadow: 0 8px 24px rgb(0 0 0 / 14%);
button {
width: 2rem;
min-width: 0 !important;
height: 2rem;
padding: 0 !important;
border: 0 !important;
border-radius: 0.5rem !important;
background: none;
font-size: 1.125rem;
cursor: pointer;
&:hover {
background: color-mix(in srgb, var(--ts-brand) 12%, transparent);
}
}
}
.ts-votes {
padding: 0.25rem 0.625rem;
border: 1px solid var(--ts-line);
border-radius: 999px;
color: var(--ts-muted);
font-size: 0.8125rem;
}

View File

@@ -12,7 +12,7 @@ import {
viewChild,
} from '@angular/core';
import { form, FormField, required } from '@angular/forms/signals';
import { RouterLink } from '@angular/router';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import {
PiActionButtonComponent,
PiCheckboxComponent,
@@ -47,9 +47,9 @@ import {
isTyping,
matches,
mentionQuery,
mentionSegments,
POINT_SCALE,
ReleaseStatus,
REACTIONS,
} from '@task-stream/web/tracker/domain';
import {
clock,
@@ -63,6 +63,13 @@ import {
typeLook,
} from '../ui/copy';
import { AttachmentItem } from '../ui/attachments';
import {
AttachmentLoader,
ImageUploader,
MarkdownComponent,
MarkdownHintComponent,
PasteImagesDirective,
} from '../ui/markdown';
const NONE = '';
/** Same ceiling as the API's ATTACHMENTS_MAX_MB default. */
@@ -72,6 +79,9 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
selector: 'ts-issue-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
MarkdownComponent,
MarkdownHintComponent,
PasteImagesDirective,
NgTemplateOutlet,
RouterLink,
FormField,
@@ -133,10 +143,46 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
<span class="ts-parent__title">{{ parent.title }}</span>
</a>
}
@if (issue.blockedBy.length) {
<span
class="ts-blocked"
role="status"
[title]="blockedTitle(issue.blockedBy)"
>
<pi-icon icon="lock" size="x-small" aria-hidden="true" />
Bloqueado por
@for (blocker of issue.blockedBy; track blocker.id) {
<a class="ts-key" [routerLink]="['..', blocker.key]">{{
blocker.key
}}</a>
}
</span>
}
</div>
<div class="ts-issue__title-row">
<h1>{{ issue.title }}</h1>
<div class="ts-issue__actions">
@if (facade.me()) {
<pi-icon-button
icon="arrow-up"
color="grey"
appearance="outline"
[text]="
(issue.voted ? 'Votado · ' : 'Votar · ') + issue.votes
"
[attr.aria-pressed]="issue.voted"
[attr.title]="
issue.voted
? 'Quitar mi voto'
: 'Votar: dice al equipo que lo quieres'
"
(execute)="facade.vote(!issue.voted)"
/>
} @else if (issue.votes) {
<span class="ts-votes ts-mono" title="Votos">
▲ {{ issue.votes }}
</span>
}
@if (project.myRole()) {
<pi-icon-button
[icon]="facade.watching() ? 'eye-off' : 'eye'"
@@ -165,6 +211,14 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
title="Editar (tecla E)"
(execute)="openEdit()"
/>
<pi-icon-button
icon="copy"
color="grey"
appearance="outline"
text="Duplicar"
title="Crear otro ticket con lo mismo (sin estado, persona ni comentarios)"
(execute)="duplicate()"
/>
}
</div>
</div>
@@ -190,7 +244,11 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
<article class="ts-block">
<h2 class="ts-section">Descripción</h2>
@if (issue.description) {
<p class="ts-prewrap">{{ issue.description }}</p>
<ts-markdown
[text]="issue.description"
[me]="facade.me()"
[loader]="loadImage"
/>
} @else {
<p class="ts-muted">Sin descripción.</p>
}
@@ -539,7 +597,9 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
}}{{ comment.editedAt ? ' · editado' : '' }}</span
>
<span class="ts-spacer"></span>
@if (!comment.deleted && comment.author.id === facade.me()) {
@if (
!comment.deleted && comment.author.id === facade.me()
) {
<pi-icon-button
icon="edit"
color="grey"
@@ -564,19 +624,60 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
@if (comment.deleted) {
<p class="ts-muted ts-comment__gone">Comentario borrado</p>
} @else {
<p class="ts-prewrap">
@for (part of segments(comment.body); track $index) {
@if ('mention' in part) {
<span
class="ts-mention"
[class.is-me]="part.userId === facade.me()"
>@{{ part.mention }}</span
<ts-markdown
[text]="comment.body"
[me]="facade.me()"
[loader]="loadImage"
/>
}
@if (
!comment.deleted &&
(comment.reactions.length || project.myRole())
) {
<div class="ts-reactions">
@for (
reaction of comment.reactions;
track reaction.emoji
) {
<button
type="button"
class="ts-reaction"
[class.is-mine]="reacted(reaction)"
[attr.aria-pressed]="reacted(reaction)"
[title]="reactionTitle(reaction)"
[disabled]="!project.myRole()"
(click)="
facade.react(
comment.id,
reaction.emoji,
!reacted(reaction)
)
"
>
} @else {
{{ part.text }}
{{ reaction.emoji }}
<span class="ts-mono">{{
reaction.users.length
}}</span>
</button>
}
}
</p>
@if (project.myRole()) {
<details class="ts-reaction-picker">
<summary title="Reaccionar" aria-label="Reaccionar">
<pi-icon icon="add" size="x-small" />
</summary>
<div class="ts-reaction-picker__menu">
@for (emoji of reactions; track emoji) {
<button
type="button"
(click)="pickReaction(comment, emoji, $event)"
>
{{ emoji }}
</button>
}
</div>
</details>
}
</div>
}
@if (!comment.deleted && filesOf(comment).length) {
<div class="ts-attachments">
@@ -593,12 +694,18 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
</ng-template>
@for (thread of threads(); track thread.comment.id) {
<ng-container
*ngTemplateOutlet="commentView; context: { $implicit: thread.comment }"
*ngTemplateOutlet="
commentView;
context: { $implicit: thread.comment }
"
/>
<div class="ts-replies">
@for (reply of thread.replies; track reply.id) {
<ng-container
*ngTemplateOutlet="commentView; context: { $implicit: reply }"
*ngTemplateOutlet="
commentView;
context: { $implicit: reply }
"
/>
}
@if (replyingTo() === thread.comment.id) {
@@ -614,6 +721,13 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
'… Escribe @ para mencionar a alguien.'
"
[(value)]="replyBody"
[tsPasteImages]="pasteImage"
/>
<ts-markdown-hint
[text]="replyBody()"
[me]="facade.me()"
[loader]="loadImage"
[images]="true"
/>
@if (replyMentionOptions().length) {
<div
@@ -621,15 +735,20 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
role="group"
aria-label="Mencionar a"
>
@for (member of replyMentionOptions(); track member.id) {
@for (
member of replyMentionOptions();
track member.id
) {
<button
type="button"
class="ts-mentions__option"
(click)="mentionInReply(member)"
>
<span class="ts-comment__avatar" aria-hidden="true">{{
initialsOf(member.name)
}}</span>
<span
class="ts-comment__avatar"
aria-hidden="true"
>{{ initialsOf(member.name) }}</span
>
{{ member.name }}
</button>
}
@@ -651,7 +770,9 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
</button>
</div>
</form>
} @else if (project.canContribute() && !thread.comment.deleted) {
} @else if (
project.canContribute() && !thread.comment.deleted
) {
<button
type="button"
class="ts-plain-link ts-reply__open"
@@ -675,6 +796,13 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
<pi-textarea
placeholder="Deja una decisión, una explicación, un paso para reproducir… Escribe @ para mencionar a alguien."
[(value)]="commentBody"
[tsPasteImages]="pasteImage"
/>
<ts-markdown-hint
[text]="commentBody()"
[me]="facade.me()"
[loader]="loadImage"
[images]="true"
/>
@if (mentionOptions().length) {
<div
@@ -881,9 +1009,18 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
<pi-text-field [formField]="edit.title">
<pi-label [isRequired]="true">Título</pi-label>
</pi-text-field>
<pi-textarea [formField]="edit.description">
<pi-textarea
[formField]="edit.description"
[tsPasteImages]="pasteImage"
>
<pi-label>Descripción</pi-label>
</pi-textarea>
<ts-markdown-hint
[text]="editModel().description"
[me]="facade.me()"
[loader]="loadImage"
[images]="true"
/>
<pi-text-field [formField]="edit.labels" placeholder="safari, checkout">
<pi-label>Etiquetas (separadas por comas)</pi-label>
</pi-text-field>
@@ -909,7 +1046,16 @@ const MAX_FILE_BYTES = 25 * 1024 * 1024;
(submit)="$event.preventDefault(); saveComment()"
novalidate
>
<pi-textarea [formField]="commentEdit.body" />
<pi-textarea
[formField]="commentEdit.body"
[tsPasteImages]="pasteImage"
/>
<ts-markdown-hint
[text]="commentEditModel().body"
[me]="facade.me()"
[loader]="loadImage"
[images]="true"
/>
<pi-action-button
size="w100"
color="primary"
@@ -929,6 +1075,8 @@ export class IssuePage {
protected readonly project = inject(ProjectFacade);
private readonly drawer = inject(DrawerService);
private readonly toast = inject(ToastService);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly reasonForm =
viewChild.required<TemplateRef<unknown>>('reasonForm');
private readonly editForm =
@@ -1046,7 +1194,48 @@ export class IssuePage {
() => this.facade.comments().filter((c) => !c.deleted).length,
);
protected readonly commentFiles = signal<File[]>([]);
protected readonly segments = mentionSegments;
protected readonly reactions = REACTIONS;
protected reacted(reaction: { users: { id: string }[] }): boolean {
return reaction.users.some((u) => u.id === this.facade.me());
}
protected reactionTitle(reaction: {
emoji: string;
users: { name: string }[];
}): string {
return `${reaction.users.map((u) => u.name).join(', ')} · ${reaction.emoji}`;
}
/** From the picker: adds it, or takes it back if it was already there. */
protected pickReaction(comment: Comment, emoji: string, event: Event): void {
const mine = comment.reactions.find((r) => r.emoji === emoji);
this.facade.react(comment.id, emoji, !(mine && this.reacted(mine)));
(event.target as HTMLElement).closest('details')?.removeAttribute('open');
}
protected blockedTitle(blockers: { key: string; title: string }[]): string {
return blockers.map((b) => `${b.key}: ${b.title}`).join('\n');
}
protected duplicate(): void {
this.facade.duplicate().subscribe({
next: (key) => {
this.toast.success(
key ? `Creado ${key}, copia de este` : 'Copia creada',
);
if (key)
void this.router.navigate(['..', key], { relativeTo: this.route });
},
error: () => this.toast.error('No se pudo duplicar'),
});
}
/** Images inside descriptions and comments: fetched, and uploaded on paste. */
protected readonly loadImage: AttachmentLoader = (id) =>
this.facade.fileById(id);
protected readonly pasteImage: ImageUploader = (file) =>
this.facade.uploadImage(file);
/** Members matching what is typed after an `@` at the end of the comment. */
protected readonly mentionOptions = computed(() =>
this.membersMatching(this.commentBody()),
@@ -1111,7 +1300,7 @@ export class IssuePage {
private readonly reasonModel = signal({ text: '' });
protected readonly reason = form(this.reasonModel, (p) => required(p.text));
private readonly editModel = signal({
protected readonly editModel = signal({
title: '',
description: '',
labels: '',
@@ -1120,7 +1309,7 @@ export class IssuePage {
protected readonly edit = form(this.editModel, (p) => required(p.title));
private editingComment: string | null = null;
private readonly commentEditModel = signal({ body: '' });
protected readonly commentEditModel = signal({ body: '' });
protected readonly commentEdit = form(this.commentEditModel, (p) =>
required(p.body),
);

View File

@@ -0,0 +1,678 @@
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
signal,
untracked,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import {
PiEmptyStateComponent,
PiIconComponent,
PiNoteComponent,
PiSelectFieldComponent,
PiSkeletonComponent,
PiTextFieldComponent,
type PiSelectFieldOption,
} from '@pi/ui';
import {
ListCriteria,
ListFacade,
ProjectFacade,
provideListFacade,
} from '@task-stream/web/tracker/application';
import {
BulkChange,
IssuePriority,
IssueSummary,
StatusCategory,
} from '@task-stream/web/tracker/domain';
import { BulkBarComponent } from '../ui/bulk-bar';
import { VoteComponent } from '../ui/vote';
import {
options,
PRIORITY,
PRIORITY_LEVEL,
statusLook,
timeAgo,
typeLook,
} from '../ui/copy';
const ALL = '';
const NOBODY = '__nobody__';
const OPEN: StatusCategory[] = [
StatusCategory.TODO,
StatusCategory.IN_PROGRESS,
StatusCategory.QA,
];
const CLOSED: StatusCategory[] = [
StatusCategory.DONE,
StatusCategory.CANCELLED,
];
type SortKey =
| 'key'
| 'title'
| 'type'
| 'status'
| 'priority'
| 'assignee'
| 'sprint'
| 'points'
| 'votes'
| 'due'
| 'updated';
/** Ticket keys in their number's order (WEB-9 before WEB-10). */
const numberOf = (key: string) => Number(key.split('-').pop());
/**
* /p/:key/list — every ticket of the project as rows: sort by any column,
* filter, change status, priority or assignee in place, edit in bulk.
*/
@Component({
selector: 'ts-list-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
BulkBarComponent,
VoteComponent,
RouterLink,
PiEmptyStateComponent,
PiIconComponent,
PiNoteComponent,
PiSelectFieldComponent,
PiSkeletonComponent,
PiTextFieldComponent,
],
providers: [provideListFacade()],
template: `
<div class="ts-list__filters">
<pi-text-field
placeholder="Buscar por clave, título o descripción…"
[(value)]="search"
/>
<pi-select-field [options]="scopeOptions" [(value)]="scope" />
<pi-select-field [options]="typeOptions()" [(value)]="type" />
<pi-select-field [options]="priorityFilterOptions" [(value)]="priority" />
<pi-select-field
[options]="assigneeFilterOptions()"
[(value)]="assignee"
/>
@if (facade.loaded()) {
<span class="ts-muted ts-mono ts-list__count">
{{ facade.total() }} tickets{{
facade.total() > facade.issues().length
? ' · se muestran ' +
facade.issues().length +
', afina los filtros'
: ''
}}
</span>
}
</div>
@if (facade.error(); as error) {
<pi-note
gap="xs"
status="error"
appearance="fill"
type="status"
title="No se pudo cargar la lista"
[text]="error"
/>
} @else if (!facade.loaded()) {
<pi-skeleton shape="text" [lines]="10" />
} @else if (rows().length) {
@if (project.canContribute()) {
<ts-bulk-bar
[count]="selected().size"
[allSelected]="allSelected()"
(selectAll)="selectAll($event)"
(apply)="applyBulk($event)"
/>
}
<div class="ts-list ts-panel">
<table>
<thead>
<tr>
@if (project.canContribute()) {
<th class="ts-list__pick" aria-label="Seleccionar"></th>
}
@for (column of columns; track column.key) {
<th
[class]="'ts-list__' + column.key"
[attr.aria-sort]="ariaSort(column.key)"
>
<button type="button" (click)="sortBy(column.key)">
{{ column.label }}
@if (sort().key === column.key) {
<span aria-hidden="true">{{
sort().asc ? '↑' : '↓'
}}</span>
}
</button>
</th>
}
</tr>
</thead>
<tbody>
@for (issue of rows(); track issue.id) {
<tr [class.is-selected]="selected().has(issue.id)">
@if (project.canContribute()) {
<td class="ts-list__pick">
<input
type="checkbox"
[attr.aria-label]="'Seleccionar ' + issue.key"
[checked]="selected().has(issue.id)"
(change)="toggle(issue.id, $any($event.target).checked)"
/>
</td>
}
<td class="ts-list__key">
<a
class="ts-key"
[routerLink]="['..', 'issues', issue.key]"
>{{ issue.key }}</a
>
</td>
<td class="ts-list__title">
<a [routerLink]="['..', 'issues', issue.key]">{{
issue.title
}}</a>
@if (issue.blockedBy.length) {
<span
class="ts-list__blocked"
[title]="'Bloqueado por ' + blockersOf(issue)"
>
<pi-icon icon="lock" size="x-small" /> Bloqueado
</span>
}
@if (issue.parent; as parent) {
<span class="ts-muted ts-mono" [title]="parent.title">
↑ {{ parent.key }}</span
>
}
</td>
<td class="ts-list__type">
<span
class="ts-list__type-label"
[style.--tone]="typeTone(issue)"
>
<pi-icon [icon]="typeIcon(issue)" size="x-small" />
{{ typeLabel(issue) }}
</span>
</td>
<td class="ts-list__status">
@if (project.canContribute()) {
<select
class="ts-cell-select"
[style.--tone]="statusTone(issue.status)"
[attr.aria-label]="'Estado de ' + issue.key"
(change)="changeStatus(issue, $any($event.target))"
>
@for (status of statusChoices(issue); track status.id) {
<option
[value]="status.id"
[selected]="status.id === issue.status"
>
{{ status.name }}
</option>
}
</select>
} @else {
<span
class="ts-pill"
[style.--tone]="statusTone(issue.status)"
>{{ statusLabel(issue.status) }}</span
>
}
</td>
<td class="ts-list__priority">
@if (project.canContribute()) {
<select
class="ts-cell-select"
[attr.aria-label]="'Prioridad de ' + issue.key"
(change)="
changePriority(issue, $any($event.target).value)
"
>
@for (option of priorityOptions; track option.value) {
<option
[value]="option.value"
[selected]="option.value === issue.priority"
>
{{ option.label }}
</option>
}
</select>
} @else {
{{ priorityLabel(issue) }}
}
</td>
<td class="ts-list__assignee">
@if (project.canContribute()) {
<select
class="ts-cell-select"
[attr.aria-label]="'Persona asignada a ' + issue.key"
(change)="assign(issue, $any($event.target).value)"
>
<option [value]="NOBODY" [selected]="!issue.assignee">
Sin asignar
</option>
@for (member of project.members(); track member.user.id) {
<option
[value]="member.user.id"
[selected]="member.user.id === issue.assignee?.id"
>
{{ member.user.name }}
</option>
}
</select>
} @else {
{{ issue.assignee?.name ?? '—' }}
}
</td>
<td class="ts-list__sprint ts-muted">
{{ issue.sprint?.name ?? '—' }}
</td>
<td class="ts-list__points ts-mono">
{{ issue.storyPoints ?? '—' }}
</td>
<td class="ts-list__votes">
<ts-vote [votes]="issue.votes" [voted]="issue.voted" />
</td>
<td
class="ts-list__due ts-mono"
[class.is-late]="isLate(issue)"
>
{{ issue.dueDate ? shortDate(issue.dueDate) : '—' }}
</td>
<td class="ts-list__updated ts-muted">
{{ ago(issue.updatedAt) }}
</td>
</tr>
}
</tbody>
</table>
</div>
} @else {
<pi-empty-state
icon="task"
title="Ningún ticket con estos filtros"
description="Prueba con «Todos» en vez de «Abiertos», o quita algún filtro."
/>
}
`,
styles: `
.ts-list__filters {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 0.75rem;
align-items: center;
margin-bottom: 1rem;
pi-text-field {
flex: 2 1 16rem;
}
pi-select-field {
flex: 1 1 13.5rem;
max-width: 15rem;
}
}
.ts-list__count {
font-size: 0.8125rem;
}
.ts-list {
overflow-x: auto;
padding: 0;
}
table {
width: 100%;
min-width: 60rem;
border-collapse: collapse;
font-size: 0.875rem;
}
th {
position: sticky;
top: 0;
padding: 0;
background: var(--ts-surface);
text-align: left;
button {
width: 100%;
padding: 0.625rem 0.625rem;
border: 0;
background: none;
color: var(--ts-muted);
font: inherit;
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.04em;
text-align: left;
text-transform: uppercase;
cursor: pointer;
&:hover {
color: var(--ts-ink);
}
}
}
td {
padding: 0.4375rem 0.625rem;
border-top: 1px solid var(--ts-line);
vertical-align: middle;
}
tr.is-selected td {
background: color-mix(in srgb, var(--ts-brand) 8%, var(--ts-surface));
}
.ts-list__pick {
width: 2rem;
padding-left: 0.875rem;
}
.ts-list__key {
white-space: nowrap;
}
.ts-list__title {
min-width: 16rem;
a {
color: inherit;
text-decoration: none;
&:hover {
color: var(--ts-brand);
}
}
.ts-mono {
margin-left: 0.375rem;
font-size: 0.75rem;
}
}
.ts-list__blocked {
display: inline-flex;
gap: 0.25rem;
align-items: center;
margin-left: 0.5rem;
padding: 0 0.375rem;
border-radius: 999px;
background: color-mix(in srgb, var(--ts-c-red, #d33) 12%, transparent);
color: var(--ts-c-red, var(--ts-ink));
font-size: 0.75rem;
font-weight: 600;
}
.ts-list__type-label {
display: inline-flex;
gap: 0.375rem;
align-items: center;
color: var(--tone);
white-space: nowrap;
}
.ts-list__points,
.ts-list__due,
.ts-list__updated {
white-space: nowrap;
}
.ts-list__due.is-late {
color: var(--ts-c-red, var(--ts-ink));
font-weight: 600;
}
.ts-cell-select {
max-width: 11rem;
padding: 0.25rem 0.375rem;
border: 1px solid transparent;
border-radius: 0.375rem;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
&:hover,
&:focus-visible {
border-color: var(--ts-line-strong, var(--ts-line));
}
&[style] {
border-left: 3px solid var(--tone);
}
}
`,
})
export class ListPage {
protected readonly facade = inject(ListFacade);
protected readonly project = inject(ProjectFacade);
protected readonly NOBODY = NOBODY;
protected readonly ago = (iso: string) => timeAgo(iso);
protected readonly columns: { key: SortKey; label: string }[] = [
{ key: 'key', label: 'Clave' },
{ key: 'title', label: 'Título' },
{ key: 'type', label: 'Tipo' },
{ key: 'status', label: 'Estado' },
{ key: 'priority', label: 'Prioridad' },
{ key: 'assignee', label: 'Asignado' },
{ key: 'sprint', label: 'Sprint' },
{ key: 'points', label: 'Pts' },
{ key: 'votes', label: 'Votos' },
{ key: 'due', label: 'Vence' },
{ key: 'updated', label: 'Actualizado' },
];
/* Filters (sent to the API) */
protected readonly search = signal('');
protected readonly scope = signal<string | null>('open');
protected readonly type = signal<string | null>(ALL);
protected readonly priority = signal<string | null>(ALL);
protected readonly assignee = signal<string | null>(ALL);
protected readonly scopeOptions: PiSelectFieldOption<string>[] = [
{ value: 'open', label: 'Abiertos' },
{ value: 'closed', label: 'Terminados o cancelados' },
{ value: 'all', label: 'Todos' },
];
protected readonly typeOptions = computed<PiSelectFieldOption<string>[]>(
() => [
{ value: ALL, label: 'Todos los tipos' },
...this.project
.workflow()
.settings.issueTypes.filter((t) => !t.archived)
.map((t) => ({ value: t.id, label: t.name })),
],
);
protected readonly priorityOptions = options(PRIORITY);
protected readonly priorityFilterOptions: PiSelectFieldOption<string>[] = [
{ value: ALL, label: 'Todas las prioridades' },
...this.priorityOptions,
];
protected readonly assigneeFilterOptions = computed<
PiSelectFieldOption<string>[]
>(() => [
{ value: ALL, label: 'Todas las personas' },
{ value: NOBODY, label: 'Sin asignar' },
...this.project
.members()
.map((m) => ({ value: m.user.id, label: m.user.name })),
]);
private readonly criteria = computed<ListCriteria>(() => {
const scope = this.scope();
const assignee = this.assignee();
return {
search: this.search() || undefined,
categories:
scope === 'open' ? OPEN : scope === 'closed' ? CLOSED : undefined,
types: this.type() ? [this.type() as string] : undefined,
priorities: this.priority()
? [this.priority() as IssuePriority]
: undefined,
unassigned: assignee === NOBODY || undefined,
assigneeId: assignee && assignee !== NOBODY ? assignee : undefined,
};
});
/* Sorting (here, on what was loaded) */
protected readonly sort = signal<{ key: SortKey; asc: boolean }>({
key: 'updated',
asc: false,
});
protected readonly rows = computed(() => {
const { key, asc } = this.sort();
const order = this.statusOrder();
const value = (i: IssueSummary): string | number => {
switch (key) {
case 'key':
return numberOf(i.key);
case 'title':
return i.title.toLocaleLowerCase();
case 'type':
return this.typeLabel(i);
case 'status':
return order.get(i.status) ?? 99;
case 'priority':
return PRIORITY_LEVEL[i.priority];
case 'assignee':
return i.assignee?.name.toLocaleLowerCase() ?? '￿';
case 'sprint':
return i.sprint?.name.toLocaleLowerCase() ?? '￿';
case 'points':
return i.storyPoints ?? -1;
case 'votes':
return i.votes;
case 'due':
return i.dueDate ?? '￿';
case 'updated':
return i.updatedAt;
}
};
return [...this.facade.issues()].sort((a, b) => {
const x = value(a);
const y = value(b);
const diff =
typeof x === 'number' && typeof y === 'number'
? x - y
: String(x).localeCompare(String(y));
return asc ? diff : -diff;
});
});
/** Statuses in board order. */
private readonly statusOrder = computed(
() =>
new Map(
this.project
.workflow()
.settings.statuses.map((s, index) => [s.id, index] as const),
),
);
/* Selection */
protected readonly selected = signal(new Set<string>());
protected readonly allSelected = computed(
() =>
this.rows().length > 0 &&
this.rows().every((i) => this.selected().has(i.id)),
);
constructor() {
effect(() => {
const projectId = this.project.project()?.id;
if (projectId) untracked(() => this.facade.open(projectId));
});
effect(() => {
const criteria = this.criteria();
untracked(() => this.facade.filter(criteria));
});
}
protected sortBy(key: SortKey): void {
this.sort.update((current) =>
current.key === key
? { key, asc: !current.asc }
: // Dates and numbers read best from the top; words from A.
{
key,
asc: !['updated', 'priority', 'points', 'votes'].includes(key),
},
);
}
protected ariaSort(key: SortKey): string | null {
const sort = this.sort();
if (sort.key !== key) return null;
return sort.asc ? 'ascending' : 'descending';
}
protected toggle(issueId: string, on: boolean): void {
this.selected.update((set) => {
const next = new Set(set);
if (on) next.add(issueId);
else next.delete(issueId);
return next;
});
}
protected selectAll(on: boolean): void {
this.selected.set(new Set(on ? this.rows().map((i) => i.id) : []));
}
protected applyBulk(change: BulkChange): void {
this.facade.bulkUpdate([...this.selected()], change);
this.selected.set(new Set());
}
/**
* Its status and where the workflow lets it go. Statuses that need a
* reason are left to the ticket page, where there is room to write it.
*/
protected statusChoices(issue: IssueSummary) {
const workflow = this.project.workflow();
const ids = [
issue.status,
...workflow
.allowedFrom(issue.status)
.filter((id) => !workflow.requiresReason(id)),
];
return ids.map((id) => ({ id, name: this.statusLabel(id) }));
}
protected changeStatus(issue: IssueSummary, select: HTMLSelectElement): void {
if (select.value !== issue.status)
this.facade.changeStatus(issue.id, select.value);
}
protected changePriority(issue: IssueSummary, priority: string): void {
if (priority !== issue.priority)
this.facade.changePriority(issue.id, priority as IssuePriority);
}
protected assign(issue: IssueSummary, value: string): void {
const assigneeId = value === NOBODY ? null : value;
if (assigneeId !== (issue.assignee?.id ?? null))
this.facade.assign(issue.id, assigneeId);
}
protected blockersOf(issue: IssueSummary): string {
return issue.blockedBy.map((b) => b.key).join(', ');
}
protected isLate(issue: IssueSummary): boolean {
return (
!!issue.dueDate &&
OPEN.includes(issue.statusCategory) &&
issue.dueDate.slice(0, 10) < new Date().toISOString().slice(0, 10)
);
}
protected shortDate(date: string): string {
return new Date(`${date.slice(0, 10)}T00:00:00`).toLocaleDateString(
'es-ES',
{ day: 'numeric', month: 'short' },
);
}
protected typeIcon = (issue: IssueSummary) =>
typeLook(this.project.workflow(), issue.type).icon;
protected typeTone = (issue: IssueSummary) =>
typeLook(this.project.workflow(), issue.type).tone;
protected typeLabel = (issue: IssueSummary) =>
typeLook(this.project.workflow(), issue.type).label;
protected statusTone = (status: string) =>
statusLook(this.project.workflow(), status).tone;
protected statusLabel = (status: string) =>
statusLook(this.project.workflow(), status).label;
protected priorityLabel = (issue: IssueSummary) =>
PRIORITY[issue.priority].label;
}

View File

@@ -61,6 +61,11 @@ import { projectTone, PUBLIC_TONE, ROLE } from '../ui/copy';
{{ project.description }}
</p>
}
@if (project.isPublic && project.acceptsProposals) {
<a class="ts-project-header__propose" routerLink="proponer">
¿Has visto un error o tienes una idea? Cuéntanoslo →
</a>
}
</div>
<div class="ts-project-header__team">
<ts-avatars [names]="memberNames()" [max]="6" />
@@ -85,6 +90,7 @@ import { projectTone, PUBLIC_TONE, ROLE } from '../ui/copy';
}
<nav class="ts-tabs" aria-label="Secciones del proyecto">
<a routerLink="board" routerLinkActive="is-active">Tablero</a>
<a routerLink="list" routerLinkActive="is-active">Lista</a>
<a routerLink="backlog" routerLinkActive="is-active">Backlog</a>
<a routerLink="sprints" routerLinkActive="is-active">Sprints</a>
<a routerLink="calendar" routerLinkActive="is-active">Calendario</a>
@@ -195,6 +201,16 @@ import { projectTone, PUBLIC_TONE, ROLE } from '../ui/copy';
margin: 0.5rem 0 0;
color: var(--ts-muted);
}
.ts-project-header__propose {
display: inline-block;
margin-top: 0.625rem;
color: var(--ts-brand);
font-weight: 600;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.ts-project-header__team {
display: flex;
align-items: center;

View File

@@ -0,0 +1,259 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import {
PiActionButtonComponent,
PiLabelDirective,
PiNoteComponent,
PiTextareaComponent,
PiTextFieldComponent,
} from '@pi/ui';
import {
ProjectFacade,
ProposeFacade,
} from '@task-stream/web/tracker/application';
import { ProposalResult } from '@task-stream/web/tracker/domain';
import { MarkdownHintComponent } from '../ui/markdown';
/**
* /p/:key/proponer — anyone, without an account, reports a bug or proposes
* an idea for a public project that takes them. It becomes a ticket
* labelled «propuesta» that the team looks at and others can vote for.
*/
@Component({
selector: 'ts-propose-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
RouterLink,
MarkdownHintComponent,
PiActionButtonComponent,
PiLabelDirective,
PiNoteComponent,
PiTextareaComponent,
PiTextFieldComponent,
],
template: `
@if (project.project(); as p) {
<section class="ts-propose ts-panel">
@if (!p.isPublic || !p.acceptsProposals) {
<pi-note
gap="xs"
status="info"
appearance="fill"
type="status"
title="Este proyecto no recoge propuestas ahora mismo"
text="Quien lo lleva puede abrir el formulario en su configuración."
/>
} @else if (sent(); as result) {
<div class="ts-propose__done" role="status">
<h2>¡Gracias!</h2>
<p>
Ha llegado al equipo de {{ p.name }}.
@if (result.key) {
Puedes seguirla, y otras personas votarla, en
<a
class="ts-plain-link"
[routerLink]="['..', 'issues', result.key]"
>{{ result.key }}</a
>.
}
</p>
<button type="button" class="ts-plain-link" (click)="reset()">
Enviar otra
</button>
</div>
} @else {
<header>
<h2>Cuéntanoslo</h2>
<p class="ts-muted">
No hace falta cuenta. Llegará al equipo como un ticket con la
etiqueta «propuesta», visible para todo el mundo (no escribas
datos personales).
</p>
</header>
<form
class="ts-propose__form"
(submit)="$event.preventDefault(); submit(p.key)"
novalidate
>
<fieldset class="ts-propose__kind">
<legend>¿Qué es?</legend>
<label>
<input
type="radio"
name="kind"
value="BUG"
[checked]="kind() === 'BUG'"
(change)="kind.set('BUG')"
/>
Algo no funciona
</label>
<label>
<input
type="radio"
name="kind"
value="IDEA"
[checked]="kind() === 'IDEA'"
(change)="kind.set('IDEA')"
/>
Tengo una idea
</label>
</fieldset>
<pi-text-field
[placeholder]="
kind() === 'BUG'
? 'Ej.: El pago falla con tarjetas de prepago'
: 'Ej.: Poder exportar a PDF'
"
[(value)]="title"
>
<pi-label [isRequired]="true">Título</pi-label>
</pi-text-field>
<pi-textarea
[placeholder]="
kind() === 'BUG'
? 'Qué hiciste, qué esperabas y qué pasó. El navegador o el móvil ayudan.'
: 'Qué te gustaría y para qué te serviría.'
"
[(value)]="description"
>
<pi-label>Detalles</pi-label>
</pi-textarea>
<ts-markdown-hint [text]="description()" />
<pi-text-field placeholder="Opcional" [(value)]="author">
<pi-label>Tu nombre o alias</pi-label>
</pi-text-field>
<!-- A field people never see: only bots fill it in. -->
<input
class="ts-propose__trap"
type="text"
name="website"
tabindex="-1"
autocomplete="off"
aria-hidden="true"
[value]="website()"
(input)="website.set($any($event.target).value)"
/>
@if (error(); as message) {
<p class="ts-propose__error" role="alert">{{ message }}</p>
}
<div>
<pi-action-button
color="primary"
text="Enviar"
[disabled]="!canSend() || sending()"
(execute)="submit(p.key)"
/>
</div>
</form>
}
</section>
}
`,
styles: `
.ts-propose {
display: grid;
gap: 1rem;
max-width: 44rem;
padding: 1.5rem;
h2 {
margin: 0 0 0.25rem;
}
header p {
margin: 0;
}
}
.ts-propose__form {
display: grid;
gap: 1.5rem;
}
.ts-propose__kind {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 1.25rem;
margin: 0;
padding: 0;
border: 0;
legend {
margin-bottom: 0.375rem;
font-size: 0.875rem;
font-weight: 600;
}
label {
display: inline-flex;
gap: 0.375rem;
align-items: center;
}
}
.ts-propose__trap {
position: absolute;
left: -10000px;
width: 1px;
height: 1px;
opacity: 0;
}
.ts-propose__error {
margin: 0;
color: var(--ts-c-red, var(--ts-ink));
}
.ts-propose__done p {
margin: 0 0 0.75rem;
}
`,
})
export class ProposePage {
protected readonly project = inject(ProjectFacade);
private readonly propose = inject(ProposeFacade);
protected readonly kind = signal<'BUG' | 'IDEA'>('BUG');
protected readonly title = signal('');
protected readonly description = signal('');
protected readonly author = signal('');
protected readonly website = signal('');
protected readonly sending = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly sent = signal<ProposalResult | null>(null);
protected readonly canSend = computed(() => {
const title = this.title().trim().length;
return title >= 3 && title <= 150;
});
protected submit(projectKey: string): void {
if (!this.canSend() || this.sending()) return;
this.sending.set(true);
this.error.set(null);
this.propose
.submit(projectKey, {
kind: this.kind(),
title: this.title().trim(),
description: this.description(),
author: this.author(),
website: this.website(),
})
.subscribe({
next: (result) => {
this.sending.set(false);
this.sent.set(result);
},
error: (error: { status?: number }) => {
this.sending.set(false);
this.error.set(
error.status === 429
? 'Has enviado varias seguidas: espera unos minutos y vuelve a intentarlo.'
: 'No se ha podido enviar. Inténtalo de nuevo en un momento.',
);
},
});
}
protected reset(): void {
this.sent.set(null);
this.title.set('');
this.description.set('');
}
}

View File

@@ -9,6 +9,7 @@ import {
} from '@angular/core';
import { form, FormField, maxLength, required } from '@angular/forms/signals';
import { RouterLink } from '@angular/router';
import { MarkdownComponent } from '../ui/markdown';
import {
PiActionButtonComponent,
PiEmptyStateComponent,
@@ -26,6 +27,7 @@ import { RELEASE_STATUS, releaseWhen } from '../ui/copy';
selector: 'ts-releases-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
MarkdownComponent,
RouterLink,
FormField,
PiActionButtonComponent,
@@ -88,7 +90,10 @@ import { RELEASE_STATUS, releaseWhen } from '../ui/copy';
@if (release.notes) {
<details class="ts-release__notes">
<summary>Notas de la versión</summary>
<pre class="ts-release__notes-text">{{ release.notes }}</pre>
<ts-markdown
class="ts-release__notes-text"
[text]="release.notes"
/>
</details>
}
<div class="ts-release__actions">
@@ -209,8 +214,8 @@ import { RELEASE_STATUS, releaseWhen } from '../ui/copy';
}
}
.ts-release__notes-text {
display: block;
margin: 0.5rem 0 0;
white-space: pre-wrap;
font: inherit;
font-size: 0.875rem;
}

View File

@@ -1,3 +1,5 @@
import { AuthFacade } from '@task-stream/web/identity/application';
import { VoteComponent } from '../ui/vote';
import {
ChangeDetectionStrategy,
Component,
@@ -42,7 +44,7 @@ const shortDay = (day: string) =>
@Component({
selector: 'ts-roadmap-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [RouterLink, PiNoteComponent, PiSkeletonComponent],
imports: [RouterLink, PiNoteComponent, PiSkeletonComponent, VoteComponent],
providers: [provideEpicsFacade()],
template: `
<div class="ts-section-header">
@@ -121,14 +123,21 @@ const shortDay = (day: string) =>
@for (row of epicRows(); track row.epic.issue.id) {
<div class="ts-roadmap__row" role="row">
<a
class="ts-roadmap__label"
<div
class="ts-roadmap__label ts-roadmap__label--epic"
role="rowheader"
[routerLink]="['..', 'issues', row.epic.issue.key]"
>
<span class="ts-key">{{ row.epic.issue.key }}</span>
{{ row.epic.issue.title }}
</a>
<a [routerLink]="['..', 'issues', row.epic.issue.key]">
<span class="ts-key">{{ row.epic.issue.key }}</span>
{{ row.epic.issue.title }}
</a>
<ts-vote
[votes]="row.epic.issue.votes"
[voted]="row.epic.issue.voted"
[canVote]="canVote()"
(voteChange)="epics.vote(row.epic.issue.id, $event)"
/>
</div>
<div class="ts-roadmap__track" role="cell">
<a
class="ts-roadmap__bar"
@@ -163,6 +172,12 @@ const shortDay = (day: string) =>
>
{{ epic.issue.title }}
<span class="ts-muted ts-mono">{{ epic.progress.percent }}%</span>
<ts-vote
[votes]="epic.issue.votes"
[voted]="epic.issue.voted"
[canVote]="canVote()"
(voteChange)="epics.vote(epic.issue.id, $event)"
/>
</li>
}
</ul>
@@ -176,7 +191,7 @@ const shortDay = (day: string) =>
`,
styles: `
.ts-roadmap {
--label: 14rem;
--label: 18rem;
position: relative;
display: grid;
padding: 0.5rem 0.75rem 0.75rem;
@@ -201,6 +216,23 @@ const shortDay = (day: string) =>
text-overflow: ellipsis;
white-space: nowrap;
}
.ts-roadmap__label--epic {
display: flex;
gap: 0.5rem;
align-items: center;
a {
flex: 1;
min-width: 0;
overflow: hidden;
color: inherit;
text-decoration: none;
text-overflow: ellipsis;
white-space: nowrap;
&:hover {
color: var(--ts-brand);
}
}
}
a.ts-roadmap__label:hover {
color: var(--ts-brand);
}
@@ -299,6 +331,13 @@ const shortDay = (day: string) =>
export class RoadmapPage {
protected readonly epics = inject(EpicsFacade);
private readonly project = inject(ProjectFacade);
private readonly auth = inject(AuthFacade);
/** Signed in, on a public project or as a member. */
protected readonly canVote = computed(
() =>
this.auth.isAuthenticated() &&
(!!this.project.project()?.isPublic || !!this.project.myRole()),
);
private readonly dated = computed(() =>
this.epics.epics().filter((e) => e.issue.startDate || e.issue.dueDate),

View File

@@ -1,3 +1,4 @@
import { RouterLink } from '@angular/router';
import {
CdkDrag,
CdkDragDrop,
@@ -56,6 +57,7 @@ function idFrom(name: string): string {
selector: 'ts-settings-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
RouterLink,
GitIntegrationComponent,
WebhooksComponent,
TransferComponent,
@@ -119,6 +121,44 @@ function idFrom(name: string): string {
<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) {

View File

@@ -32,6 +32,18 @@ export const trackerRoutes: Routes = [
loadComponent: () =>
import('./pages/board.page').then((m) => m.BoardPage),
},
{
path: 'proponer',
title: 'Proponer · TaskStream',
loadComponent: () =>
import('./pages/propose.page').then((m) => m.ProposePage),
},
{
path: 'list',
title: 'Lista · TaskStream',
loadComponent: () =>
import('./pages/list.page').then((m) => m.ListPage),
},
{
path: 'issues/:issueKey',
title: 'Ticket · TaskStream',

View File

@@ -0,0 +1,166 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
input,
output,
signal,
} from '@angular/core';
import {
PiActionButtonComponent,
PiSelectFieldComponent,
PiTextFieldComponent,
type PiSelectFieldOption,
} from '@pi/ui';
import { ProjectFacade } from '@task-stream/web/tracker/application';
import { BulkChange, IssuePriority } from '@task-stream/web/tracker/domain';
import { options, PRIORITY } from './copy';
/** "Nobody" / "no sprint" in the selects. */
const NOBODY = '__none__';
/**
* Edit in bulk: select all, then one change (status, assignee, sprint,
* priority or an extra label) for every selected ticket. Shared by the
* backlog and the list.
*/
@Component({
selector: 'ts-bulk-bar',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
PiActionButtonComponent,
PiSelectFieldComponent,
PiTextFieldComponent,
],
template: `
<div class="ts-bulk" role="toolbar" aria-label="Edición en bloque">
<label class="ts-bulk__all">
<input
type="checkbox"
[checked]="allSelected()"
[indeterminate]="count() > 0 && !allSelected()"
(change)="selectAll.emit($any($event.target).checked)"
/>
{{ count() ? count() + ' seleccionados' : 'Seleccionar todos' }}
</label>
@if (count()) {
<pi-select-field [options]="fields" [(value)]="field" />
@switch (field()) {
@case ('status') {
<pi-select-field [options]="statusOptions()" [(value)]="value" />
}
@case ('assignee') {
<pi-select-field [options]="assigneeOptions()" [(value)]="value" />
}
@case ('sprint') {
<pi-select-field [options]="sprintOptions()" [(value)]="value" />
}
@case ('priority') {
<pi-select-field [options]="priorityOptions" [(value)]="value" />
}
@case ('label') {
<pi-text-field placeholder="etiqueta" [(value)]="label" />
}
}
<pi-action-button
size="small"
color="primary"
text="Aplicar"
[disabled]="!canApply()"
(execute)="emit()"
/>
}
</div>
`,
styles: `
.ts-bulk {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
margin-bottom: 0.75rem;
pi-select-field,
pi-text-field {
width: 13rem;
}
}
.ts-bulk__all {
display: inline-flex;
gap: 0.375rem;
align-items: center;
font-size: 0.875rem;
}
`,
})
export class BulkBarComponent {
/** How many tickets are selected. */
readonly count = input.required<number>();
readonly allSelected = input.required<boolean>();
readonly selectAll = output<boolean>();
/** The change to make on every selected ticket. */
readonly apply = output<BulkChange>();
private readonly project = inject(ProjectFacade);
protected readonly fields: PiSelectFieldOption<string>[] = [
{ value: 'status', label: 'Mover a…' },
{ value: 'assignee', label: 'Asignar a…' },
{ value: 'sprint', label: 'Sprint…' },
{ value: 'priority', label: 'Prioridad…' },
{ value: 'label', label: 'Añadir etiqueta…' },
];
protected readonly field = signal<string | null>('status');
protected readonly value = signal<string | null>(null);
protected readonly label = signal('');
protected readonly statusOptions = computed<PiSelectFieldOption<string>[]>(
() =>
this.project
.workflow()
.settings.statuses.filter((s) => !s.archived)
.map((s) => ({ value: s.id, label: s.name })),
);
protected readonly assigneeOptions = computed<PiSelectFieldOption<string>[]>(
() => [
{ value: NOBODY, label: 'Nadie (sin asignar)' },
...this.project
.members()
.map((m) => ({ value: m.user.id, label: m.user.name })),
],
);
protected readonly sprintOptions = computed<PiSelectFieldOption<string>[]>(
() => [
{ value: NOBODY, label: 'Backlog (sin sprint)' },
...this.project
.openSprints()
.map((s) => ({ value: s.id, label: s.name })),
],
);
protected readonly priorityOptions = options(PRIORITY);
protected readonly canApply = computed(() =>
this.field() === 'label' ? !!this.label().trim() : !!this.value(),
);
protected emit(): void {
const value = this.value();
const change: BulkChange = {};
switch (this.field()) {
case 'status':
if (value) change.status = value;
break;
case 'assignee':
change.assigneeId = value === NOBODY ? null : value;
break;
case 'sprint':
change.sprintId = value === NOBODY ? null : value;
break;
case 'priority':
if (value) change.priority = value as IssuePriority;
break;
case 'label':
change.addLabels = [this.label().trim().toLowerCase()];
break;
}
this.apply.emit(change);
this.label.set('');
}
}

View File

@@ -31,6 +31,17 @@ import { initials, PRIORITY, PRIORITY_LEVEL, typeLook } from './copy';
<pi-icon [icon]="type().icon" size="small" />
</span>
<span class="ts-card__key">{{ issue().key }}</span>
@if (issue().blockedBy.length) {
<span
class="ts-card__blocked"
[attr.title]="
'Bloqueado por ' + issue().blockedBy.map(blockerKey).join(', ')
"
>
<pi-icon icon="lock" size="x-small" />
Bloqueado
</span>
}
@if (issue().area; as area) {
<span class="ts-card__area">{{ areaLabel(area) }}</span>
}
@@ -180,6 +191,17 @@ import { initials, PRIORITY, PRIORITY_LEVEL, typeLook } from './copy';
font-weight: 600;
color: var(--ts-ink-soft);
}
.ts-card__blocked {
display: inline-flex;
gap: 0.25rem;
align-items: center;
padding: 0 0.375rem;
border-radius: 999px;
background: color-mix(in srgb, var(--ts-c-red, #d33) 12%, transparent);
color: var(--ts-c-red, var(--ts-ink));
font-size: 0.6875rem;
font-weight: 600;
}
.ts-card__area {
margin-left: auto;
font-family: var(--ts-font-mono);
@@ -259,6 +281,8 @@ import { initials, PRIORITY, PRIORITY_LEVEL, typeLook } from './copy';
`,
})
export class IssueCardComponent {
protected readonly blockerKey = (blocker: { key: string }) => blocker.key;
/** Late, due today or in the next two days. */
protected readonly due = computed(() =>
dueState(this.issue().dueDate, this.issue().statusCategory),

View File

@@ -0,0 +1,49 @@
import { renderMarkdown } from './markdown';
describe('renderMarkdown', () => {
it('formats Markdown, keeping single line breaks', () => {
const html = renderMarkdown(
'**Hecho** y _probado_\nen `main`\n\n- uno\n- dos',
);
expect(html).toContain('<strong>Hecho</strong>');
expect(html).toContain('<em>probado</em><br>');
expect(html).toContain('<code>main</code>');
expect(html).toContain('<li>uno</li>');
});
it('highlights mentions, the reader own apart', () => {
const html = renderMarkdown('@[Ana López](101) y @[Bob](102)', '101');
expect(html).toContain(
'<span class="ts-mention is-me" data-user="101">@Ana López</span>',
);
expect(html).toContain(
'<span class="ts-mention" data-user="102">@Bob</span>',
);
});
it('lets nothing run, whatever someone writes', () => {
const html = renderMarkdown(
'<script>alert(1)</script><img src=x onerror="alert(2)"> <div class="ts-btn" onclick="x()">hola</div>',
);
expect(html).not.toMatch(/<script|onerror|onclick|ts-btn|<div/);
// A Markdown link to javascript: is no link at all.
const link = renderMarkdown('[clic](javascript:alert(3))');
expect(link).not.toContain('href');
});
it('opens links apart and leaves pasted images to be fetched', () => {
const html = renderMarkdown(
'[docs](https://example.org) ![captura](attachment:3f2c-1)',
);
expect(html).toContain('href="https://example.org"');
expect(html).toContain('target="_blank"');
expect(html).toContain('rel="noopener noreferrer"');
expect(html).toMatch(/<img alt="captura" data-attachment="3f2c-1">/);
});
it('shows task lists as ticked boxes nobody can click', () => {
const html = renderMarkdown('- [x] Reproducido\n- [ ] Arreglado');
expect(html).toContain('<input checked="" disabled="" type="checkbox">');
expect(html).toContain('<input disabled="" type="checkbox">');
});
});

View File

@@ -0,0 +1,410 @@
import {
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
Directive,
effect,
ElementRef,
HostListener,
inject,
input,
signal,
untracked,
ViewEncapsulation,
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { mentionSegments } from '@task-stream/web/tracker/domain';
import DOMPurify from 'dompurify';
import { marked } from 'marked';
import { Observable } from 'rxjs';
/** Images pasted into a text are stored as attachments: `![name](attachment:<id>)`. */
const ATTACHMENT = /^attachment:([\w-]{1,64})$/;
const ALLOWED_TAGS = [
'p',
'br',
'strong',
'em',
'del',
'code',
'pre',
'blockquote',
'hr',
'h1',
'h2',
'h3',
'h4',
'ul',
'ol',
'li',
'a',
'img',
'span',
'table',
'thead',
'tbody',
'tr',
'th',
'td',
'input',
];
let hooked = false;
/** Links open apart; only mentions keep a class; attachment images wait to be fetched. */
function installHooks(): void {
if (hooked) return;
hooked = true;
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'A') {
node.setAttribute('target', '_blank');
node.setAttribute('rel', 'noopener noreferrer');
}
if (node.tagName === 'IMG') {
const id = ATTACHMENT.exec(node.getAttribute('src') ?? '')?.[1];
if (id) {
node.removeAttribute('src');
node.setAttribute('data-attachment', id);
}
}
if (node.tagName === 'INPUT') {
// Task lists: `- [x] done` renders as a ticked, read-only box.
if (node.getAttribute('type') !== 'checkbox') node.remove();
else node.setAttribute('disabled', '');
}
const cls = node.getAttribute('class');
if (cls && !/^ts-mention( is-me)?$/.test(cls))
node.removeAttribute('class');
});
}
const escapeHtml = (text: string) =>
text.replace(
/[&<>"']/g,
(c) =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[
c
] ?? c,
);
/**
* A description, comment or release note as safe HTML: Markdown (GitHub's
* flavour, single line breaks kept), `@[Name](id)` mentions highlighted
* (`me` marks one's own), and nothing that could run: whatever someone wrote
* goes through DOMPurify with a short list of tags.
*/
export function renderMarkdown(text: string, me: string | null = null): string {
installHooks();
const withMentions = mentionSegments(text)
.map((part) =>
'mention' in part
? `<span class="ts-mention${part.userId === me ? ' is-me' : ''}" data-user="${escapeHtml(part.userId)}">@${escapeHtml(part.mention)}</span>`
: part.text,
)
.join('');
const html = marked.parse(withMentions, {
gfm: true,
breaks: true,
async: false,
});
return DOMPurify.sanitize(html, {
ALLOWED_TAGS,
ALLOWED_ATTR: [
'href',
'title',
'alt',
'src',
'class',
'data-user',
'type',
'checked',
'disabled',
],
// DOMPurify's own rule plus `attachment:`: links and images to http(s),
// mail or a pasted file; plain values (`type="checkbox"`) still pass.
ALLOWED_URI_REGEXP:
/^(?:(?:https?|mailto|attachment):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
});
}
/** Fetches an attachment's bytes (with the session), by id. */
export type AttachmentLoader = (attachmentId: string) => Observable<Blob>;
/**
* Formatted text: Markdown rendered safely. Pasted images (`attachment:`)
* are fetched with `loader`, since a private project's files need the
* session and an `<img>` cannot send it.
*/
@Component({
selector: 'ts-markdown',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
template: '<div class="ts-md" [innerHTML]="html()"></div>',
styles: `
.ts-md {
display: block;
min-width: 0;
overflow-wrap: anywhere;
line-height: 1.55;
> :first-child {
margin-top: 0;
}
> :last-child {
margin-bottom: 0;
}
p,
ul,
ol,
pre,
blockquote,
table {
margin: 0 0 0.625rem;
}
h1,
h2,
h3,
h4 {
margin: 1rem 0 0.5rem;
line-height: 1.25;
}
h1 {
font-size: 1.375rem;
}
h2 {
font-size: 1.1875rem;
}
h3,
h4 {
font-size: 1rem;
}
ul,
ol {
padding-left: 1.375rem;
}
li:has(> input[type='checkbox']) {
list-style: none;
margin-left: -1.375rem;
}
a {
color: var(--ts-brand);
}
code {
padding: 0.0625rem 0.3125rem;
border-radius: 0.3125rem;
background: color-mix(in srgb, var(--ts-ink) 8%, transparent);
font-family: var(--ts-mono, ui-monospace, monospace);
font-size: 0.875em;
}
pre {
padding: 0.75rem 0.875rem;
overflow-x: auto;
border-radius: 0.5rem;
background: color-mix(in srgb, var(--ts-ink) 7%, transparent);
code {
padding: 0;
background: none;
}
}
blockquote {
padding: 0 0 0 0.875rem;
border-left: 3px solid var(--ts-line-strong, var(--ts-line));
color: var(--ts-muted);
font-size: inherit;
quotes: none;
&::before,
&::after {
content: none;
}
}
img {
display: block;
max-width: 100%;
max-height: 28rem;
border-radius: 0.5rem;
border: 1px solid var(--ts-line);
}
img[data-attachment]:not([src]) {
width: 12rem;
height: 6rem;
background: color-mix(in srgb, var(--ts-ink) 6%, transparent);
}
table {
border-collapse: collapse;
display: block;
overflow-x: auto;
}
th,
td {
padding: 0.375rem 0.625rem;
border: 1px solid var(--ts-line);
text-align: left;
}
hr {
border: 0;
border-top: 1px solid var(--ts-line);
}
.ts-mention {
padding: 0 0.2em;
border-radius: 0.25em;
background: color-mix(in oklab, var(--ts-brand) 14%, transparent);
color: inherit;
font-weight: 600;
}
.ts-mention.is-me {
background: color-mix(in oklab, var(--ts-brand) 30%, transparent);
}
}
`,
})
export class MarkdownComponent {
readonly text = input<string | null | undefined>('');
/** Signed-in user's id, to mark mentions of oneself. */
readonly me = input<string | null>(null);
readonly loader = input<AttachmentLoader | null>(null);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly sanitizer = inject(DomSanitizer);
/** Object URLs of the images already fetched, by attachment id. */
private readonly urls = new Map<string, string>();
// Sanitised above with DOMPurify; Angular's own pass would drop the mentions' data.
protected readonly html = computed(() =>
this.sanitizer.bypassSecurityTrustHtml(
renderMarkdown(this.text() ?? '', this.me()),
),
);
constructor() {
effect(() => {
this.html();
const loader = this.loader();
// After the new HTML is in place.
untracked(() => queueMicrotask(() => this.loadImages(loader)));
});
inject(DestroyRef).onDestroy(() => {
for (const url of this.urls.values()) URL.revokeObjectURL(url);
});
}
private loadImages(loader: AttachmentLoader | null): void {
if (!loader) return;
const images = this.host.nativeElement.querySelectorAll<HTMLImageElement>(
'img[data-attachment]',
);
for (const img of Array.from(images)) {
const id = img.dataset['attachment'] ?? '';
const known = this.urls.get(id);
if (known) {
img.src = known;
continue;
}
loader(id).subscribe({
next: (blob) => {
const url = URL.createObjectURL(blob);
this.urls.set(id, url);
img.src = url;
},
error: () => img.setAttribute('alt', `${img.alt} (no disponible)`),
});
}
}
}
/**
* Under a text box: that it takes Markdown, and a preview of what will show.
*/
@Component({
selector: 'ts-markdown-hint',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MarkdownComponent],
template: `
<div class="ts-md-hint">
<span class="ts-muted"
>Admite Markdown: **negrita**, _cursiva_, <code>código</code>, listas y
enlaces{{ images() ? '; pega capturas con Ctrl+V' : '' }}.</span
>
<button
type="button"
class="ts-plain-link"
[disabled]="!text()?.trim()"
(click)="open.set(!open())"
>
{{ open() ? 'Ocultar vista previa' : 'Vista previa' }}
</button>
</div>
@if (open() && text()?.trim()) {
<ts-markdown
class="ts-md-preview"
[text]="text()"
[me]="me()"
[loader]="loader()"
/>
}
`,
styles: `
:host {
display: grid;
gap: 0.5rem;
}
.ts-md-hint {
display: flex;
flex-wrap: wrap;
gap: 0.25rem 0.75rem;
align-items: baseline;
font-size: 0.75rem;
}
.ts-md-preview {
padding: 0.75rem 0.875rem;
border: 1px dashed var(--ts-line-strong, var(--ts-line));
border-radius: 0.625rem;
}
`,
})
export class MarkdownHintComponent {
readonly text = input<string | null | undefined>('');
readonly me = input<string | null>(null);
readonly loader = input<AttachmentLoader | null>(null);
/** Whether pasting images is on for the box above. */
readonly images = input(false);
protected readonly open = signal(false);
}
/** Uploads a pasted image and answers its attachment id. */
export type ImageUploader = (file: File) => Observable<string>;
/**
* On a textarea (or a component wrapping one): pasting an image uploads it
* and writes `![name](attachment:<id>)` where the caret was. The text is
* changed through an `input` event, so whatever binds the field sees it.
*/
@Directive({ selector: '[tsPasteImages]' })
export class PasteImagesDirective {
readonly tsPasteImages = input<ImageUploader | null>(null);
private readonly destroyRef = inject(DestroyRef);
@HostListener('paste', ['$event'])
onPaste(event: ClipboardEvent): void {
const upload = this.tsPasteImages();
const files = Array.from(event.clipboardData?.files ?? []).filter((f) =>
f.type.startsWith('image/'),
);
const area = event.target as HTMLTextAreaElement | null;
if (!upload || !files.length || area?.tagName !== 'TEXTAREA') return;
event.preventDefault();
let caret = area.selectionStart ?? area.value.length;
for (const file of files) {
const name = (file.name || 'captura').replace(/[[\]()\n]/g, ' ');
const sub = upload(file).subscribe((id) => {
const snippet = `\n![${name}](attachment:${id})\n`;
area.value =
area.value.slice(0, caret) + snippet + area.value.slice(caret);
caret += snippet.length;
area.dispatchEvent(new Event('input', { bubbles: true }));
});
this.destroyRef.onDestroy(() => sub.unsubscribe());
}
}
}

View File

@@ -0,0 +1,78 @@
import {
ChangeDetectionStrategy,
Component,
input,
output,
} from '@angular/core';
/**
* ▲ 3: how many want a ticket. A button for whoever can vote (the
* signed-in, on a public project), the count alone for the rest.
*/
@Component({
selector: 'ts-vote',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (canVote()) {
<button
type="button"
class="ts-vote"
[class.is-mine]="voted()"
[attr.aria-pressed]="voted()"
[attr.aria-label]="
(voted() ? 'Quitar mi voto · ' : 'Votar · ') + votes()
"
[title]="voted() ? 'Quitar mi voto' : 'Votar'"
(click)="voteChange.emit(!voted())"
>
▲ <span>{{ votes() }}</span>
</button>
} @else {
<span class="ts-vote is-static" title="Votos">▲ {{ votes() }}</span>
}
`,
styles: `
:host {
display: inline-flex;
}
/* @pi/ui styles every <button> (min-width, padding, radius, border) too
specifically to override without !important. */
.ts-vote {
display: inline-flex;
gap: 0.25rem;
align-items: center;
min-width: 0 !important;
height: auto !important;
padding: 0.0625rem 0.5rem !important;
border: 1px solid var(--ts-line) !important;
border-radius: 999px !important;
line-height: 1.5;
background: var(--ts-surface);
color: var(--ts-muted);
font: inherit;
font-family: var(--ts-font-mono, ui-monospace, monospace);
font-size: 0.75rem;
white-space: nowrap;
cursor: pointer;
&:hover:not(.is-static) {
border-color: var(--ts-brand);
color: var(--ts-ink);
}
&.is-mine {
border-color: var(--ts-brand) !important;
background: color-mix(in srgb, var(--ts-brand) 12%, var(--ts-surface));
color: var(--ts-brand);
}
&.is-static {
cursor: default;
}
}
`,
})
export class VoteComponent {
readonly votes = input.required<number>();
readonly voted = input(false);
readonly canVote = input(false);
/** The new state: true to vote, false to take it back. */
readonly voteChange = output<boolean>();
}

View File

@@ -0,0 +1,5 @@
import '@angular/compiler';
import '@analogjs/vitest-angular/setup-snapshots';
import { setupTestBed } from '@analogjs/vitest-angular/setup-testbed';
setupTestBed();

View File

@@ -22,6 +22,9 @@
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}

View File

@@ -0,0 +1,29 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../../dist/out-tsc",
"types": [
"vitest/globals",
"vitest/importMeta",
"vite/client",
"node",
"vitest"
]
},
"include": [
"vite.config.ts",
"vite.config.mts",
"vitest.config.ts",
"vitest.config.mts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.test.tsx",
"src/**/*.spec.tsx",
"src/**/*.test.js",
"src/**/*.spec.js",
"src/**/*.test.jsx",
"src/**/*.spec.jsx",
"src/**/*.d.ts"
],
"files": ["src/test-setup.ts"]
}

View File

@@ -0,0 +1,29 @@
/// <reference types='vitest' />
import { defineConfig } from 'vite';
import angular from '@analogjs/vite-plugin-angular';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
export default defineConfig(() => ({
root: import.meta.dirname,
cacheDir: '../../../../node_modules/.vite/libs/web/tracker/presenters',
plugins: [angular(), nxViteTsPaths(), nxCopyAssetsPlugin(['*.md'])],
// Uncomment this if you are using workers.
// worker: {
// plugins: () => [ nxViteTsPaths() ],
// },
test: {
name: 'web-tracker-presenters',
watch: false,
passWithNoTests: true,
globals: true,
environment: 'jsdom',
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
setupFiles: ['src/test-setup.ts'],
reporters: ['default'],
coverage: {
reportsDirectory: '../../../../coverage/libs/web/tracker/presenters',
provider: 'v8' as const,
},
},
}));