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

@@ -7,6 +7,7 @@ export * from './lib/comments.service';
export * from './lib/releases.service';
export * from './lib/changes.service';
export * from './lib/workflows.service';
export * from './lib/blockers.service';
export * from './lib/notifications.service';
export * from './lib/notifications';
export * from './lib/saved-filters.service';

View File

@@ -0,0 +1,78 @@
import {
IssueLinkType,
IssueReadModel,
StatusCategory,
} from '@task-stream/api/tracker/domain';
import { BlockersService } from './blockers.service';
import { FindIssuesRepository } from './ports/find-issues.repository';
const issue = (
id: string,
statusCategory = StatusCategory.TODO,
links: IssueReadModel['links'] = [],
) =>
({
id,
key: `WEB-${id}`,
title: `Ticket ${id}`,
statusCategory,
trashedAt: null,
links,
}) as unknown as IssueReadModel;
describe('BlockersService', () => {
const store = new Map(
[
issue('2'),
issue('3', StatusCategory.DONE),
issue('4', StatusCategory.IN_PROGRESS),
issue('5'),
].map((i) => [i.id, i]),
);
const queries: string[][] = [];
const service = new BlockersService({
findByIds: async (ids: string[]) => {
queries.push(ids);
return ids.map((id) => store.get(id)).filter(Boolean);
},
} as unknown as FindIssuesRepository);
const link = (
type: IssueLinkType,
direction: 'INWARD' | 'OUTWARD',
id: string,
) => ({ type, direction, issueId: id, issueKey: `WEB-${id}` });
beforeEach(() => (queries.length = 0));
it('is waiting on what blocks it and what it depends on, while open', async () => {
const one = issue('1', StatusCategory.TODO, [
link(IssueLinkType.BLOCKS, 'INWARD', '2'), // 2 blocks 1
link(IssueLinkType.DEPENDS_ON, 'OUTWARD', '3'), // 1 depends on 3 (done)
link(IssueLinkType.DEPENDS_ON, 'OUTWARD', '4'), // 1 depends on 4
link(IssueLinkType.BLOCKS, 'OUTWARD', '5'), // 1 blocks 5: not a blocker
link(IssueLinkType.RELATES_TO, 'OUTWARD', '2'),
]);
expect((await service.blockedBy(one)).map((b) => b.key)).toEqual([
'WEB-2',
'WEB-4',
]);
});
it('asks once for the tickets of one moment (a board)', async () => {
const card = (id: string, blocker: string) =>
issue(id, StatusCategory.TODO, [
link(IssueLinkType.DEPENDS_ON, 'OUTWARD', blocker),
]);
const results = await Promise.all([
service.blockedBy(card('10', '2')),
service.blockedBy(card('11', '4')),
service.blockedBy(issue('12')),
]);
expect(results.map((r) => r.map((b) => b.key))).toEqual([
['WEB-2'],
['WEB-4'],
[],
]);
expect(queries).toEqual([['2', '4']]);
});
});

View File

@@ -0,0 +1,86 @@
import { Injectable } from '@nestjs/common';
import {
IssueLinkType,
IssueReadModel,
StatusCategory,
} from '@task-stream/api/tracker/domain';
import { FindIssuesRepository } from './ports/find-issues.repository';
/** A ticket another one waits for. */
export interface Blocker {
id: string;
key: string;
title: string;
}
const FINISHED = new Set<StatusCategory>([
StatusCategory.DONE,
StatusCategory.CANCELLED,
]);
/**
* What a ticket waits for: the tickets that block it and the ones it
* depends on, while they are open. Links keep no status, so it is worked
* out when reading; the lookups of one moment (a board, a page of a list)
* go to the read model as one query, not one per ticket.
*/
@Injectable()
export class BlockersService {
private batch: {
ids: Set<string>;
result: Promise<Map<string, IssueReadModel>>;
} | null = null;
constructor(private readonly findIssues: FindIssuesRepository) {}
async blockedBy(issue: IssueReadModel): Promise<Blocker[]> {
const ids = blockerIdsOf(issue);
if (!ids.length) return [];
const found = await this.load(ids);
return ids
.map((id) => found.get(id))
.filter(
(blocker): blocker is IssueReadModel =>
!!blocker &&
!blocker.trashedAt &&
!FINISHED.has(blocker.statusCategory),
)
.map(({ id, key, title }) => ({ id, key, title }));
}
private load(ids: string[]): Promise<Map<string, IssueReadModel>> {
if (!this.batch) {
const pending = new Set<string>();
const result = new Promise<Map<string, IssueReadModel>>(
(resolve, reject) =>
setImmediate(() => {
this.batch = null;
this.findIssues
.findByIds([...pending])
.then((issues) => resolve(new Map(issues.map((i) => [i.id, i]))))
.catch(reject);
}),
);
this.batch = { ids: pending, result };
}
for (const id of ids) this.batch.ids.add(id);
return this.batch.result;
}
}
/** "X blocks this" and "this depends on X": X is what it waits for. */
export function blockerIdsOf(issue: IssueReadModel): string[] {
return [
...new Set(
(issue.links ?? [])
.filter(
(link) =>
(link.type === IssueLinkType.BLOCKS &&
link.direction === 'INWARD') ||
(link.type === IssueLinkType.DEPENDS_ON &&
link.direction === 'OUTWARD'),
)
.map((link) => link.issueId),
),
];
}

View File

@@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { BusinessRuleError } from '@task-stream/api/shared/domain';
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
import { AttachFileCommand } from './attach-file.command';
import { CommandResult, ack } from './command-result';
import { AttachFileCommand, AttachmentResult } from './attach-file.command';
import { ack } from './command-result';
import { WriteAccess } from './write-access';
/**
@@ -19,7 +19,7 @@ export class AttachFileCommandHandler
private readonly storage: AttachmentStorage,
) {}
async execute(command: AttachFileCommand): Promise<CommandResult> {
async execute(command: AttachFileCommand): Promise<AttachmentResult> {
const { issue } = await this.access.issueForContributor(
command.issueId,
command.actorId,
@@ -52,6 +52,7 @@ export class AttachFileCommandHandler
await this.storage.remove(key);
throw error;
}
return ack(issue);
// The id lets a client point at the file, e.g. an image inside a comment.
return { ...ack(issue), attachmentId: id };
}
}

View File

@@ -7,7 +7,12 @@ export interface IncomingFile {
content: Buffer;
}
export class AttachFileCommand extends Command<CommandResult> {
/** The ticket's acknowledgement, and the id of the file now on it. */
export interface AttachmentResult extends CommandResult {
attachmentId: string;
}
export class AttachFileCommand extends Command<AttachmentResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,

View File

@@ -1,3 +1,7 @@
import { DuplicateIssueCommandHandler } from './duplicate-issue.command-handler';
import { ReactToCommentCommandHandler } from './react-to-comment.command-handler';
import { VoteIssueCommandHandler } from './vote-issue.command-handler';
import { SubmitProposalCommandHandler } from './submit-proposal.command-handler';
import { CreateProjectCommandHandler } from './create-project.command-handler';
import { UpdateProjectCommandHandler } from './update-project.command-handler';
import { UpdateProjectSettingsCommandHandler } from './update-project-settings.command-handler';
@@ -42,6 +46,10 @@ import {
} from './change-checklist.command-handler';
export const COMMAND_HANDLERS = [
SubmitProposalCommandHandler,
VoteIssueCommandHandler,
ReactToCommentCommandHandler,
DuplicateIssueCommandHandler,
CreateProjectCommandHandler,
UpdateProjectCommandHandler,
UpdateProjectSettingsCommandHandler,

View File

@@ -16,6 +16,7 @@ import {
Issue,
IssueStatus,
Project,
IssuePriority,
IssueType,
ProjectRole,
TRACKER_FACTORIES,
@@ -74,6 +75,11 @@ import { ReleaseNamesRepository } from '../ports/release-names.repository';
import { UserDirectory } from '../ports/user-directory';
import { AttachmentStorage } from '../ports/attachment-storage';
import { AddCommentCommand } from './add-comment.command';
import { DuplicateIssueCommand } from './duplicate-issue.command';
import { ReactToCommentCommand } from './react-to-comment.command';
import { UpdateProjectCommand } from './update-project.command';
import { SubmitProposalCommand } from './submit-proposal.command';
import { VoteIssueCommand } from './vote-issue.command';
import { AddProjectMemberCommand } from './add-project-member.command';
import { AssignIssueCommand } from './assign-issue.command';
import { AttachFileCommand } from './attach-file.command';
@@ -97,6 +103,10 @@ import { FindProjectsRepository } from '../ports/find-projects.repository';
async function setup() {
const store = new InMemoryEventStore();
const projectViews = new Map<
string,
{ id: string; key: string; isPublic: boolean; acceptsProposals: boolean }
>();
// The project's Git repositories, as Mongo would keep them.
const gitRepositories = new Map<string, GitRepositoryConfig[]>();
const git: GitIntegrationsRepository = {
@@ -129,7 +139,13 @@ async function setup() {
ReadAccess,
{
provide: FindProjectsRepository,
useValue: { findRole: async () => null, findById: async () => null },
// Read-model lookups: projects are added by the tests that need them.
useValue: {
findRole: async () => null,
findById: async (id: string) => projectViews.get(id) ?? null,
findByKey: async (key: string) =>
[...projectViews.values()].find((p) => p.key === key) ?? null,
},
},
{ provide: GitIntegrationsRepository, useValue: git },
AggregateRehydrator,
@@ -177,6 +193,7 @@ async function setup() {
sprints,
keys,
git,
projectViews,
run,
rehydrator: moduleRef.get(AggregateRehydrator),
};
@@ -832,6 +849,133 @@ describe('tracker commands (event sourced)', () => {
expect(rebuilt.deleted).toBe(true);
});
it('duplicates what a ticket says, not where it stands', async () => {
const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const original = await run(
new CreateIssueCommand(
'dev',
projectId,
IssueType.BUG,
'Pago roto',
{
description: 'Falla en Safari',
priority: IssuePriority.HIGH,
labels: ['pagos'],
storyPoints: 3,
},
'qa',
),
);
await run(new AddChecklistItemCommand('dev', original.id, 'Reproducir'));
const copy = await run(new DuplicateIssueCommand('qa', original.id));
expect(copy.key).not.toBe(original.key);
const issue = await rehydrator.rehydrate(copy.id, Issue);
expect(issue).toMatchObject({
title: 'Pago roto (copia)',
description: 'Falla en Safari',
priority: IssuePriority.HIGH,
labels: ['pagos'],
storyPoints: 3,
assigneeId: null,
reporterId: 'qa',
});
expect(issue.checklist.map((s) => [s.text, s.done])).toEqual([
['Reproducir', false],
]);
await expect(
run(new DuplicateIssueCommand('pm', original.id)),
).rejects.toThrow(ForbiddenError);
});
it('takes reactions from members, once each, viewers included', async () => {
const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('dev', projectId, IssueType.TASK, 'Spike', {}),
);
const comment = await run(new AddCommentCommand('dev', issue.id, 'Redis'));
await run(new ReactToCommentCommand('qa', comment.id, '👍', true));
await run(new ReactToCommentCommand('pm', comment.id, '👍', true));
await run(new ReactToCommentCommand('pm', comment.id, '👍', true));
await run(new ReactToCommentCommand('dev', comment.id, '🎉', true));
await run(new ReactToCommentCommand('dev', comment.id, '🎉', false));
expect((await rehydrator.rehydrate(comment.id, Comment)).reactions).toEqual(
{ '👍': ['qa', 'pm'] },
);
await expect(
run(new ReactToCommentCommand('qa', comment.id, '💩', true)),
).rejects.toThrow(ValidationError);
await expect(
run(new ReactToCommentCommand('stranger', comment.id, '👍', true)),
).rejects.toThrow(ForbiddenError);
});
it('takes votes from members, and from anyone once it is public', async () => {
const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand(
'dev',
projectId,
IssueType.FEATURE,
'Modo oscuro',
{},
),
);
await run(new VoteIssueCommand('pm', issue.id, true));
await run(new VoteIssueCommand('pm', issue.id, true));
await expect(
run(new VoteIssueCommand('stranger', issue.id, true)),
).rejects.toThrow(ForbiddenError);
await run(new UpdateProjectCommand('owner', projectId, { isPublic: true }));
await run(new VoteIssueCommand('stranger', issue.id, true));
await run(new VoteIssueCommand('pm', issue.id, false));
expect((await rehydrator.rehydrate(issue.id, Issue)).voterIds).toEqual([
'stranger',
]);
});
it('turns a proposal into a ticket, only where the project takes them', async () => {
const { run, rehydrator, projectViews } = await setup();
const projectId = await projectWithTeam(run);
const view = {
id: projectId,
key: 'TS',
isPublic: true,
acceptsProposals: false,
};
projectViews.set(projectId, view);
const propose = () =>
run(
new SubmitProposalCommand(
'ts',
'BUG',
'No carga en Firefox',
'Pantalla en blanco',
'Lucía',
),
);
await expect(propose()).rejects.toThrow(ForbiddenError);
view.acceptsProposals = true;
const result = await propose();
const issue = await rehydrator.rehydrate(result.id, Issue);
expect(issue).toMatchObject({
title: 'No carga en Firefox',
type: IssueType.BUG,
labels: ['propuesta'],
reporterId: 'system',
});
expect(issue.description).toContain('Pantalla en blanco');
expect(issue.description).toContain('por Lucía');
view.isPublic = false;
await expect(propose()).rejects.toThrow(NotFoundError);
});
it('answers comments one level deep, on the same ticket', async () => {
const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run);

View File

@@ -1,6 +1,10 @@
import { randomUUID } from 'node:crypto';
import { CommandHandler, EventPublisher, ICommandHandler } from '@nestjs/cqrs';
import { IssueFactory, assertCanNest } from '@task-stream/api/tracker/domain';
import {
IssueFactory,
SYSTEM_ACTOR_ID,
assertCanNest,
} from '@task-stream/api/tracker/domain';
import { IssueNumbersRepository } from '../ports/issue-numbers.repository';
import { CommandResult, ack } from './command-result';
import { CreateIssueCommand } from './create-issue.command';
@@ -21,7 +25,10 @@ export class CreateIssueCommandHandler
async execute(command: CreateIssueCommand): Promise<CommandResult> {
const project = await this.access.project(command.projectId);
project.assertCanContribute(command.actorId);
// TaskStream itself (proposals from the public form) is no member; only
// internal commands act as it, never a request from outside.
if (command.actorId !== SYSTEM_ACTOR_ID)
project.assertCanContribute(command.actorId);
// Before taking a number: an invalid type or area must not burn one.
const workflow = project.workflow;
workflow.assertActiveType(command.type);

View File

@@ -0,0 +1,61 @@
import { CommandBus, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { AddChecklistItemCommand } from './change-checklist.command';
import { CommandResult } from './command-result';
import { CreateIssueCommand } from './create-issue.command';
import { DuplicateIssueCommand } from './duplicate-issue.command';
import { WriteAccess } from './write-access';
/**
* Copies what a ticket says (type, title, description, area, priority,
* labels, Figma, estimate, dates, parent and checklist steps, unticked),
* not where it stands: the copy starts in the first status, unassigned,
* out of sprints and releases, without comments or files. Created through
* the usual command, so the same rules and events apply.
*/
@CommandHandler(DuplicateIssueCommand)
export class DuplicateIssueCommandHandler
implements ICommandHandler<DuplicateIssueCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly commandBus: CommandBus,
) {}
async execute(command: DuplicateIssueCommand): Promise<CommandResult> {
const { issue } = await this.access.issueForContributor(
command.issueId,
command.actorId,
);
const copy: CommandResult = await this.commandBus.execute(
new CreateIssueCommand(
command.actorId,
issue.projectId,
issue.type,
`${issue.title} (copia)`.slice(0, 255),
{
description: issue.description,
area: issue.area,
priority: issue.priority,
labels: issue.labels,
figmaUrl: issue.figmaUrl,
storyPoints: issue.storyPoints,
startDate: issue.startDate,
dueDate: issue.dueDate,
},
null,
null,
issue.parentId,
null,
// The original's text is the content, not the type's template.
false,
),
);
let result = copy;
for (const step of issue.checklist) {
result = await this.commandBus.execute(
new AddChecklistItemCommand(command.actorId, copy.id, step.text),
);
}
return { ...result, key: copy.key };
}
}

View File

@@ -0,0 +1,12 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
/** A new ticket like this one, to start from: the copy's key in the result. */
export class DuplicateIssueCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,
) {
super();
}
}

View File

@@ -6,6 +6,11 @@ export * from './assign-issue.command';
export * from './change-issue-status.command';
export * from './change-project-member-role.command';
export * from './create-issue.command';
export * from './duplicate-issue.command';
export * from './react-to-comment.command';
export * from './vote-issue.command';
export * from './submit-proposal.command';
export { PROPOSAL_LABEL } from './submit-proposal.command-handler';
export * from './create-project.command';
export * from './create-release.command';
export * from './delete-comment.command';

View File

@@ -0,0 +1,25 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { ForbiddenError } from '@task-stream/api/shared/domain';
import { CommandResult, ack } from './command-result';
import { ReactToCommentCommand } from './react-to-comment.command';
import { WriteAccess } from './write-access';
/** Reacting is for members, viewers included: reading is enough to agree. */
@CommandHandler(ReactToCommentCommand)
export class ReactToCommentCommandHandler
implements ICommandHandler<ReactToCommentCommand>
{
constructor(private readonly access: WriteAccess) {}
async execute(command: ReactToCommentCommand): Promise<CommandResult> {
const comment = await this.access.comment(command.commentId);
const project = await this.access.project(comment.projectId);
if (!project.isMember(command.actorId))
throw new ForbiddenError(
`You are not a member of project ${project.key}`,
);
comment.react(command.actorId, command.emoji, command.on);
await comment.commitAndWait();
return ack(comment);
}
}

View File

@@ -0,0 +1,14 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
/** Adds (`on`) or takes back one's reaction (👍…) on a comment. */
export class ReactToCommentCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly commentId: string,
public readonly emoji: string,
public readonly on: boolean,
) {
super();
}
}

View File

@@ -0,0 +1,82 @@
import { CommandBus, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import {
ForbiddenError,
NotFoundError,
assertThat,
} from '@task-stream/api/shared/domain';
import {
IssuePriority,
SYSTEM_ACTOR_ID,
} from '@task-stream/api/tracker/domain';
import { FindProjectsRepository } from '../ports/find-projects.repository';
import { CommandResult } from './command-result';
import { CreateIssueCommand } from './create-issue.command';
import { ProposalKind, SubmitProposalCommand } from './submit-proposal.command';
import { WriteAccess } from './write-access';
/** The label every proposal carries, for the team to find and sort them. */
export const PROPOSAL_LABEL = 'propuesta';
/** Preferred ticket type of each kind, when the project has it active. */
const TYPE_OF: Record<ProposalKind, string> = { BUG: 'BUG', IDEA: 'FEATURE' };
/**
* Only a public project that takes proposals accepts one. It is opened by
* TaskStream (nobody signed in), in the first status, as a Bug or a Feature
* (or the first active type if the project has neither), and signed with
* the name they gave, if any.
*/
@CommandHandler(SubmitProposalCommand)
export class SubmitProposalCommandHandler
implements ICommandHandler<SubmitProposalCommand>
{
constructor(
private readonly findProjects: FindProjectsRepository,
private readonly access: WriteAccess,
private readonly commandBus: CommandBus,
) {}
async execute(command: SubmitProposalCommand): Promise<CommandResult> {
const found =
(await this.findProjects.findById(command.project)) ??
(await this.findProjects.findByKey(command.project.toUpperCase()));
if (!found?.isPublic) throw new NotFoundError('Project', command.project);
if (!found.acceptsProposals)
throw new ForbiddenError(`${found.key} does not take proposals`);
const title = command.title.trim();
assertThat(
title.length >= 3 && title.length <= 150,
'A proposal needs a title of 3 to 150 characters',
);
const text = command.description.trim();
assertThat(text.length <= 5000, 'A proposal is 5000 characters at most');
const project = await this.access.project(found.id);
const active = project.settings.issueTypes.filter((t) => !t.archived);
const type =
active.find((t) => t.id === TYPE_OF[command.kind])?.id ?? active[0]?.id;
const author = command.author?.trim().slice(0, 80);
const signature = `_Propuesta enviada desde el formulario público${author ? ` por ${author}` : ''}._`;
return this.commandBus.execute(
new CreateIssueCommand(
SYSTEM_ACTOR_ID,
project.id,
type,
title,
{
description: text ? `${text}\n\n${signature}` : signature,
labels: [PROPOSAL_LABEL],
priority: IssuePriority.MEDIUM,
},
null,
null,
null,
null,
// What they wrote is the content, not the type's template.
false,
),
);
}
}

View File

@@ -0,0 +1,22 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
export type ProposalKind = 'BUG' | 'IDEA';
/**
* A bug report or an idea from anyone, through a public project's form:
* it becomes a ticket labelled `propuesta`, for the team to look at.
*/
export class SubmitProposalCommand extends Command<CommandResult> {
constructor(
/** Project id or key. */
public readonly project: string,
public readonly kind: ProposalKind,
public readonly title: string,
public readonly description: string,
/** How they sign it, if they want to: shown in the ticket. */
public readonly author: string | null,
) {
super();
}
}

View File

@@ -9,6 +9,7 @@ export class UpdateProjectCommand extends Command<CommandResult> {
name?: string;
description?: string | null;
isPublic?: boolean;
acceptsProposals?: boolean;
},
) {
super();

View File

@@ -0,0 +1,33 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import {
BusinessRuleError,
ForbiddenError,
} from '@task-stream/api/shared/domain';
import { CommandResult, ack } from './command-result';
import { VoteIssueCommand } from './vote-issue.command';
import { WriteAccess } from './write-access';
/**
* Anyone signed in votes on a public project's tickets (that is the point:
* the people it is for say what they want); on a private one, its members.
*/
@CommandHandler(VoteIssueCommand)
export class VoteIssueCommandHandler
implements ICommandHandler<VoteIssueCommand>
{
constructor(private readonly access: WriteAccess) {}
async execute(command: VoteIssueCommand): Promise<CommandResult> {
const issue = await this.access.issue(command.issueId);
const project = await this.access.project(issue.projectId);
if (!project.isPublic && !project.isMember(command.actorId))
throw new ForbiddenError(
`You are not a member of project ${project.key}`,
);
if (issue.trashedAt)
throw new BusinessRuleError(`${issue.key} is in the trash`);
issue.vote(command.actorId, command.on);
await issue.commitAndWait();
return ack(issue);
}
}

View File

@@ -0,0 +1,13 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
/** The actor votes for a ticket (`on`) or takes the vote back. */
export class VoteIssueCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,
public readonly on: boolean,
) {
super();
}
}

View File

@@ -5,6 +5,7 @@ import { AddCommentCommand } from './commands/add-comment.command';
import { CommandResult } from './commands/command-result';
import { DeleteCommentCommand } from './commands/delete-comment.command';
import { EditCommentCommand } from './commands/edit-comment.command';
import { ReactToCommentCommand } from './commands/react-to-comment.command';
import { Page } from './ports/find-issues.repository';
import { GetCommentsQuery } from './queries/get-comments.query';
@@ -36,6 +37,18 @@ export class CommentsService {
);
}
/** Adds (`on`) or takes back one's reaction (👍…). */
react(
actorId: string,
commentId: string,
emoji: string,
on: boolean,
): Promise<CommandResult> {
return this.commandBus.execute(
new ReactToCommentCommand(actorId, commentId, emoji, on),
);
}
delete(actorId: string, commentId: string): Promise<CommandResult> {
return this.commandBus.execute(
new DeleteCommentCommand(actorId, commentId),

View File

@@ -29,6 +29,7 @@ export class CommentAddedEventHandler
body: comment.body,
replyTo: comment.replyTo ?? null,
deleted: false,
reactions: [],
createdAt: comment.createdAt,
editedAt: null,
version: versionOf(event),

View File

@@ -0,0 +1,34 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import {
CommentReactedEvent,
REACTIONS,
} from '@task-stream/api/tracker/domain';
import { UpsertMaterializedCommentRepository } from '../ports/upsert-materialized-comment.repository';
import { UserDirectory } from '../ports/user-directory';
import { ReadModelNotifier, versionOf } from './read-model-notifier';
@EventsHandler(CommentReactedEvent)
export class CommentReactedEventHandler
implements IEventHandler<CommentReactedEvent>
{
constructor(
private readonly upsertMaterializedCommentRepository: UpsertMaterializedCommentRepository,
private readonly users: UserDirectory,
private readonly notifier: ReadModelNotifier,
) {}
async handle(event: CommentReactedEvent) {
const refs = await this.users.refs(Object.values(event.reactions).flat());
await this.upsertMaterializedCommentRepository.upsert({
id: event.aggregateId,
reactions: REACTIONS.filter(
(emoji) => event.reactions[emoji]?.length,
).map((emoji) => ({
emoji,
users: event.reactions[emoji].map((id) => refs.of(id)),
})),
version: versionOf(event),
});
await this.notifier.comment(event.aggregateId, event.issueId, event);
}
}

View File

@@ -2,6 +2,8 @@ import { ActivityEventHandler } from './activity.event-handler';
import { CommentAddedEventHandler } from './comment-added.event-handler';
import { CommentDeletedEventHandler } from './comment-deleted.event-handler';
import { CommentEditedEventHandler } from './comment-edited.event-handler';
import { CommentReactedEventHandler } from './comment-reacted.event-handler';
import { IssueVotedEventHandler } from './issue-voted.event-handler';
import { IssueAssignedEventHandler } from './issue-assigned.event-handler';
import { IssueCreatedEventHandler } from './issue-created.event-handler';
import { IssueLinkedEventHandler } from './issue-linked.event-handler';
@@ -46,6 +48,8 @@ export const EVENT_HANDLERS = [
CommentAddedEventHandler,
CommentDeletedEventHandler,
CommentEditedEventHandler,
CommentReactedEventHandler,
IssueVotedEventHandler,
IssueAssignedEventHandler,
IssueCreatedEventHandler,
IssueLinkedEventHandler,

View File

@@ -0,0 +1,23 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { IssueVotedEvent } from '@task-stream/api/tracker/domain';
import { UpsertMaterializedIssueRepository } from '../ports/upsert-materialized-issue.repository';
import { ReadModelNotifier, versionOf } from './read-model-notifier';
@EventsHandler(IssueVotedEvent)
export class IssueVotedEventHandler implements IEventHandler<IssueVotedEvent> {
constructor(
private readonly upsertMaterializedIssueRepository: UpsertMaterializedIssueRepository,
private readonly notifier: ReadModelNotifier,
) {}
async handle(event: IssueVotedEvent) {
// A vote is not a change to the ticket: `updatedAt` stays.
await this.upsertMaterializedIssueRepository.upsert({
id: event.aggregateId,
votes: event.voterIds.length,
voterIds: event.voterIds,
version: versionOf(event),
});
await this.notifier.issue(event.aggregateId, event);
}
}

View File

@@ -26,6 +26,7 @@ export class ProjectCreatedEventHandler
name: project.name,
description: project.description,
isPublic: project.isPublic ?? false,
acceptsProposals: project.acceptsProposals ?? false,
owner: users.of(project.ownerId),
members: project.members.map((m) => ({
user: users.of(m.userId),

View File

@@ -8,8 +8,11 @@ import {
IssueReadModel,
} from '@task-stream/api/tracker/domain';
import { AssignIssueCommand } from './commands/assign-issue.command';
import { DuplicateIssueCommand } from './commands/duplicate-issue.command';
import { VoteIssueCommand } from './commands/vote-issue.command';
import {
AttachFileCommand,
AttachmentResult,
IncomingFile,
} from './commands/attach-file.command';
import { DetachFileCommand } from './commands/detach-file.command';
@@ -169,7 +172,7 @@ export class IssuesService {
issueId: string,
file: IncomingFile,
commentId: string | null = null,
): Promise<CommandResult> {
): Promise<AttachmentResult> {
return this.commandBus.execute(
new AttachFileCommand(actorId, issueId, file, commentId),
);
@@ -258,6 +261,16 @@ export class IssuesService {
return this.commandBus.execute(new RestoreIssueCommand(actorId, issueId));
}
/** Votes for the ticket (`on`) or takes the vote back. */
vote(actorId: string, issueId: string, on: boolean): Promise<CommandResult> {
return this.commandBus.execute(new VoteIssueCommand(actorId, issueId, on));
}
/** A new ticket like this one (what it says, not where it stands). */
duplicate(actorId: string, issueId: string): Promise<CommandResult> {
return this.commandBus.execute(new DuplicateIssueCommand(actorId, issueId));
}
trashed(
viewerId: string | null,
projectId: string,

View File

@@ -1,3 +1,7 @@
import {
ProposalKind,
SubmitProposalCommand,
} from './commands/submit-proposal.command';
import { GetShowcaseQuery, Showcase } from './queries/get-showcase.query';
import { Injectable } from '@nestjs/common';
import { CommandBus, QueryBus } from '@nestjs/cqrs';
@@ -34,6 +38,19 @@ export class ProjectsService {
) {}
/** A public project's roadmap, releases, sprint and good first tickets (no token). */
/** A bug report or an idea from anyone, for a public project that takes them. */
propose(
project: string,
kind: ProposalKind,
title: string,
description: string,
author: string | null,
): Promise<CommandResult> {
return this.commandBus.execute(
new SubmitProposalCommand(project, kind, title, description, author),
);
}
showcase(project: string): Promise<Showcase> {
return this.queryBus.execute(new GetShowcaseQuery(project));
}
@@ -61,7 +78,12 @@ export class ProjectsService {
update(
actorId: string,
projectId: string,
changes: { name?: string; description?: string | null; isPublic?: boolean },
changes: {
name?: string;
description?: string | null;
isPublic?: boolean;
acceptsProposals?: boolean;
},
): Promise<CommandResult> {
return this.commandBus.execute(
new UpdateProjectCommand(actorId, projectId, changes),

View File

@@ -6,6 +6,8 @@ import { FindProjectsRepository } from '../ports/find-projects.repository';
import { FindReleasesRepository } from '../ports/find-releases.repository';
import { FindSprintsRepository } from '../ports/find-sprints.repository';
import { PROPOSAL_LABEL } from '../commands/submit-proposal.command-handler';
/** Tickets with this label are offered to newcomers on public pages. */
export const GOOD_FIRST_LABEL = 'good-first-issue';
@@ -35,6 +37,8 @@ export interface Showcase {
dueDate: string | null;
percent: number;
done: boolean;
/** How many want it. */
votes: number;
path: string;
}[];
releases: {
@@ -46,6 +50,20 @@ export interface Showcase {
notes: string | null;
}[];
goodFirst: { key: string; title: string; type: string; path: string }[];
/** Bug reports and ideas from the public: whether it takes them, where, and the open ones. */
proposals: {
open: boolean;
/** The form in the web app, while it takes them. */
path: string | null;
/** Open proposals, most voted first. */
top: {
key: string;
title: string;
type: string;
votes: number;
path: string;
}[];
};
}
export class GetShowcaseQuery extends Query<Showcase> {
@@ -55,6 +73,11 @@ export class GetShowcaseQuery extends Query<Showcase> {
}
const FINISHED = [StatusCategory.DONE, StatusCategory.CANCELLED];
const OPEN = [
StatusCategory.TODO,
StatusCategory.IN_PROGRESS,
StatusCategory.QA,
];
@QueryHandler(GetShowcaseQuery)
export class GetShowcaseQueryHandler
@@ -74,7 +97,7 @@ export class GetShowcaseQueryHandler
(await this.findProjects.findByKey(query.project.toUpperCase()));
if (!project?.isPublic) throw new NotFoundError('Project', query.project);
const path = (key: string) => `/p/${project.key}/issues/${key}`;
const [epics, releases, sprint, goodFirst] = await Promise.all([
const [epics, releases, sprint, goodFirst, proposals] = await Promise.all([
this.findIssues.epics(project.id),
this.findReleases.findByProject(project.id),
this.findSprints.findActive(project.id),
@@ -85,6 +108,13 @@ export class GetShowcaseQueryHandler
limit: 20,
offset: 0,
}),
this.findIssues.search({
projectId: project.id,
labels: [PROPOSAL_LABEL],
categories: OPEN,
limit: 100,
offset: 0,
}),
]);
const visible = releases
.filter((r) => r.status !== ReleaseStatus.ARCHIVED)
@@ -120,6 +150,7 @@ export class GetShowcaseQueryHandler
dueDate: issue.dueDate,
percent: p.percent,
done: FINISHED.includes(issue.statusCategory),
votes: issue.votes,
path: path(issue.key),
})),
releases: visible.map((r, i) => ({
@@ -136,6 +167,20 @@ export class GetShowcaseQueryHandler
type: i.type,
path: path(i.key),
})),
proposals: {
open: project.acceptsProposals,
path: project.acceptsProposals ? `/p/${project.key}/proponer` : null,
top: [...proposals.items]
.sort((a, b) => b.votes - a.votes)
.slice(0, 10)
.map((i) => ({
key: i.key,
title: i.title,
type: i.type,
votes: i.votes,
path: path(i.key),
})),
},
};
}
}

View File

@@ -55,6 +55,7 @@ import {
StartSprintCommand,
} from '../commands/sprint.commands';
import { FindSprintsRepository } from '../ports/find-sprints.repository';
import { FindProjectsRepository } from '../ports/find-projects.repository';
import { SprintCarryOverSaga } from './sprint-carry-over.saga';
import { FindIssuesRepository } from '../ports/find-issues.repository';
import { IssueNumbersRepository } from '../ports/issue-numbers.repository';
@@ -87,6 +88,8 @@ async function setup() {
IssueTree,
AggregateRehydrator,
{ provide: EventStore, useValue: store },
// Proposals look projects up in the read model; no saga sends one.
{ provide: FindProjectsRepository, useValue: {} },
{ provide: AttachmentStorage, useValue: files },
{ provide: UserDirectory, useValue: users },
{ provide: ProjectKeysRepository, useClass: InMemoryProjectKeys },

View File

@@ -17,6 +17,7 @@ import { ReadAccess } from './queries/read-access';
import { ReleasesService } from './releases.service';
import { SAGAS } from './sagas/sagas';
import { WorkflowsService } from './workflows.service';
import { BlockersService } from './blockers.service';
import { NotificationsService } from './notifications.service';
import { Notifier } from './notifications/notifier';
import { NotificationsEventHandler } from './notifications/notifications.event-handler';
@@ -60,6 +61,7 @@ const SERVICES = [
ReleasesService,
ChangesService,
WorkflowsService,
BlockersService,
NotificationsService,
SavedFiltersService,
SprintsService,

View File

@@ -7,6 +7,10 @@ import {
import { CommentAddedEvent } from '../events/comment-added.event';
import { CommentDeletedEvent } from '../events/comment-deleted.event';
import { CommentEditedEvent } from '../events/comment-edited.event';
import { CommentReactedEvent } from '../events/comment-reacted.event';
/** The reactions a comment takes, in the order they are shown (GitHub's). */
export const REACTIONS = ['👍', '👎', '😄', '🎉', '😕', '❤️', '🚀', '👀'];
/** Data of a comment (what CommentAddedEvent carries). */
export interface CommentProps {
@@ -35,6 +39,8 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
public authorId!: string;
public body!: string;
public replyTo: string | null = null;
/** Who chose each emoji (only the ones somebody chose). */
public reactions: Record<string, string[]> = {};
public deleted = false;
public createdAt!: string;
public editedAt: string | null = null;
@@ -62,6 +68,31 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
);
}
/** Adds (`on`) or takes back the actor's reaction; repeating it changes nothing. */
react(actorId: string, emoji: string, on: boolean): void {
this.assertAlive();
assertThat(
REACTIONS.includes(emoji),
`Reactions are one of ${REACTIONS.join(' ')}`,
);
const users = this.reactions[emoji] ?? [];
if (on === users.includes(actorId)) return;
const next = {
...this.reactions,
[emoji]: on ? [...users, actorId] : users.filter((u) => u !== actorId),
};
if (!next[emoji].length) delete next[emoji];
this.apply(
new CommentReactedEvent(
actorId,
this.id,
this.projectId,
this.issueId,
next,
),
);
}
/** @param canModerate whether the actor manages the project (may delete others' comments). */
delete(actorId: string, canModerate: boolean): void {
this.assertAlive();
@@ -86,6 +117,10 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
this.editedAt = event.occurredAt;
}
onCommentReactedEvent(event: CommentReactedEvent): void {
this.reactions = event.reactions;
}
onCommentDeletedEvent(): void {
this.deleted = true;
}

View File

@@ -0,0 +1,17 @@
import { AutowiredEvent } from '@task-stream/api/shared/domain';
import { TrackerEvent } from './tracker.event';
/** Someone added or took back a reaction (👍…) on a comment. */
@AutowiredEvent
export class CommentReactedEvent extends TrackerEvent {
constructor(
actorId: string,
commentId: string,
projectId: string,
readonly issueId: string,
/** Every reaction after the change: who chose each emoji. */
readonly reactions: Record<string, string[]>,
) {
super(actorId, commentId, projectId);
}
}

View File

@@ -14,6 +14,7 @@ export * from './issue-unlinked.event';
export * from './issue-release-changed.event';
export * from './comment-added.event';
export * from './comment-edited.event';
export * from './comment-reacted.event';
export * from './comment-deleted.event';
export * from './release-created.event';
export * from './release-updated.event';
@@ -25,6 +26,7 @@ export * from './release-deleted.event';
export * from './issue-attachment-added.event';
export * from './issue-attachment-removed.event';
export * from './issue-watched.event';
export * from './issue-voted.event';
export * from './issue-unwatched.event';
export * from './issue-parent-changed.event';
export * from './issue-checklist-item-added.event';

View File

@@ -0,0 +1,16 @@
import { AutowiredEvent } from '@task-stream/api/shared/domain';
import { TrackerEvent } from './tracker.event';
/** Someone voted for a ticket, or took the vote back. */
@AutowiredEvent
export class IssueVotedEvent extends TrackerEvent {
constructor(
actorId: string,
issueId: string,
projectId: string,
/** Everyone who wants it, after the change. */
readonly voterIds: string[],
) {
super(actorId, issueId, projectId);
}
}

View File

@@ -2,14 +2,17 @@ import { AutowiredEvent } from '@task-stream/api/shared/domain';
import type { ProjectProps } from '../project/project';
import { TrackerEvent } from './tracker.event';
/** Name, description or visibility changed. */
/** Name, description, visibility or whether it takes public proposals changed. */
@AutowiredEvent
export class ProjectUpdatedEvent extends TrackerEvent {
constructor(
actorId: string,
projectId: string,
readonly changes: Partial<
Pick<ProjectProps, 'name' | 'description' | 'isPublic'>
Pick<
ProjectProps,
'name' | 'description' | 'isPublic' | 'acceptsProposals'
>
>,
) {
super(actorId, projectId, projectId);

View File

@@ -25,6 +25,7 @@ import { IssueUnlinkedEvent } from '../events/issue-unlinked.event';
import { IssueUpdatedEvent } from '../events/issue-updated.event';
import { IssueUnwatchedEvent } from '../events/issue-unwatched.event';
import { IssueWatchedEvent } from '../events/issue-watched.event';
import { IssueVotedEvent } from '../events/issue-voted.event';
import { ProjectWorkflow } from '../project/project-settings';
import {
IssueAttachment,
@@ -116,6 +117,8 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
public attachments: IssueAttachment[] = [];
/** People who asked to be told about this ticket. */
public watchers: string[] = [];
/** People who want it done (a public roadmap's way to prioritise). */
public voterIds: string[] = [];
/** The epic or ticket this one breaks down. */
public parentId: string | null = null;
public checklist: ChecklistItem[] = [];
@@ -337,6 +340,21 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
);
}
/** The actor votes for it (`on`) or takes the vote back. Idempotent. */
vote(actorId: string, on: boolean): void {
if (on === this.voterIds.includes(actorId)) return;
this.apply(
new IssueVotedEvent(
actorId,
this.id,
this.projectId,
on
? [...this.voterIds, actorId]
: this.voterIds.filter((id) => id !== actorId),
),
);
}
/** `userId` starts following the ticket. Idempotent. */
watch(actorId: string, userId: string): void {
if (this.watchers.includes(userId)) return;
@@ -553,6 +571,10 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
this.updatedAt = event.occurredAt;
}
onIssueVotedEvent(event: IssueVotedEvent): void {
this.voterIds = event.voterIds;
}
onIssueWatchedEvent(event: IssueWatchedEvent): void {
this.watchers = [...this.watchers, event.userId];
}

View File

@@ -32,6 +32,11 @@ export interface ProjectProps {
description: string | null;
/** Anyone (even without signing in) can read it. Absent in old projects: private. */
isPublic?: boolean;
/**
* Takes bug reports and ideas from anyone, through a public form (only
* while it is public). Absent in old projects: no.
*/
acceptsProposals?: boolean;
ownerId: string;
members: ProjectMember[];
/** Absent in projects created before settings existed: defaults apply. */
@@ -49,6 +54,7 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
public name!: string;
public description: string | null = null;
public isPublic = false;
public acceptsProposals = false;
public ownerId!: string;
public members: ProjectMember[] = [];
public settings: ProjectSettings = defaultProjectSettings();
@@ -104,13 +110,19 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
updateDetails(
actorId: string,
changes: { name?: string; description?: string | null; isPublic?: boolean },
changes: {
name?: string;
description?: string | null;
isPublic?: boolean;
acceptsProposals?: boolean;
},
): void {
this.assertCanManage(actorId);
const patch: {
name?: string;
description?: string | null;
isPublic?: boolean;
acceptsProposals?: boolean;
} = {};
if (changes.name !== undefined) {
const name = changes.name.trim();
@@ -123,6 +135,11 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
}
if (changes.isPublic !== undefined && changes.isPublic !== this.isPublic)
patch.isPublic = changes.isPublic;
if (
changes.acceptsProposals !== undefined &&
changes.acceptsProposals !== this.acceptsProposals
)
patch.acceptsProposals = changes.acceptsProposals;
if (Object.keys(patch).length === 0) return;
this.apply(new ProjectUpdatedEvent(actorId, this.id, patch));
}
@@ -213,6 +230,7 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
this.name = project.name;
this.description = project.description;
this.isPublic = project.isPublic ?? false;
this.acceptsProposals = project.acceptsProposals ?? false;
this.ownerId = project.ownerId;
this.members = project.members.map((m) => ({ ...m }));
this.settings = structuredClone(

View File

@@ -1,5 +1,11 @@
import { UserRefReadModel } from './user-ref.read-model';
/** One emoji on a comment and who chose it. */
export class CommentReactionReadModel {
emoji!: string;
users!: UserRefReadModel[];
}
export class CommentReadModel {
id!: string;
issueId!: string;
@@ -13,6 +19,8 @@ export class CommentReadModel {
* conversation under it still makes sense. Gone with its last reply.
*/
deleted!: boolean;
/** In the order they are offered; only the ones somebody chose. */
reactions!: CommentReactionReadModel[];
createdAt!: string;
editedAt!: string | null;
version!: number;

View File

@@ -81,6 +81,10 @@ export class IssueReadModel {
attachments!: AttachmentReadModel[];
/** People following the ticket. */
watchers!: UserRefReadModel[];
/** How many want it done. */
votes!: number;
/** Who voted: to tell someone whether they did; never shown as a list. */
voterIds!: string[];
parent!: IssueParentReadModel | null;
/** Place in the backlog (and in each board column): ascending. */
rank!: string;

View File

@@ -14,6 +14,8 @@ export class ProjectReadModel {
description!: string | null;
/** Readable by anyone, also without signing in. */
isPublic!: boolean;
/** Takes bug reports and ideas from anyone (only while public). */
acceptsProposals!: boolean;
owner!: UserRefReadModel;
members!: ProjectMemberReadModel[];
/** Statuses, transitions, ticket types and areas. */

View File

@@ -50,6 +50,7 @@ const commentFromDoc = (doc: CommentDoc): CommentReadModel => ({
...fromDoc(doc),
replyTo: doc.replyTo ?? null,
deleted: doc.deleted ?? false,
reactions: doc.reactions ?? [],
});
const escapeRegex = (text: string) =>
@@ -63,6 +64,7 @@ function toProject(doc: ProjectDoc): ProjectReadModel {
return {
...fromDoc(rest),
isPublic: rest.isPublic ?? false,
acceptsProposals: rest.acceptsProposals ?? false,
settings: rest.settings ?? defaultProjectSettings(),
};
}

View File

@@ -293,6 +293,8 @@ export function issueFromDoc(doc: IssueDoc): IssueReadModel {
// Tickets projected before attachments existed have none.
attachments: rest.attachments ?? [],
watchers: rest.watchers ?? [],
votes: rest.votes ?? 0,
voterIds: rest.voterIds ?? [],
parent: rest.parent?.id ? rest.parent : null,
rank: rest.rank ?? implicitRank(rest.number),
startDate: rest.startDate ?? null,

View File

@@ -31,6 +31,18 @@ export class CommentResolver {
return this.comments.edit(me.id, commentId, body);
}
@Mutation(() => CommandResultGql, {
description: 'React (👍 👎 😄 🎉 😕 ❤️ 🚀 👀) or take it back (on: false)',
})
reactToComment(
@CurrentUser() me: User,
@Args('commentId', { type: () => ID }) commentId: string,
@Args('emoji') emoji: string,
@Args('on') on: boolean,
) {
return this.comments.react(me.id, commentId, emoji, on);
}
@Mutation(() => CommandResultGql, { description: 'Author or project admin' })
deleteComment(
@CurrentUser() me: User,

View File

@@ -74,6 +74,14 @@ export class UpdateProjectInput {
@IsOptional()
@IsBoolean()
isPublic?: boolean;
@Field({
nullable: true,
description:
'Take bug reports and ideas from anyone through the public form (while public)',
})
@IsOptional()
@IsBoolean()
acceptsProposals?: boolean;
}
@InputType()

View File

@@ -14,6 +14,7 @@ import {
OptionalAuth,
} from '@task-stream/api/identity/presenters';
import {
BlockersService,
CommentsService,
IssuesService,
WorkflowsService,
@@ -44,6 +45,7 @@ import {
EpicGql,
IssueGql,
IssuePageGql,
IssueParentGql,
} from './types';
@Resolver(() => IssueGql)
@@ -52,6 +54,7 @@ export class IssueResolver {
private readonly issuesService: IssuesService,
private readonly commentsService: CommentsService,
private readonly workflows: WorkflowsService,
private readonly blockers: BlockersService,
) {}
@OptionalAuth()
@@ -154,6 +157,22 @@ export class IssueResolver {
return this.workflows.allowedTransitions(issue);
}
@ResolveField(() => [IssueParentGql], {
description:
'Open tickets it waits for: the ones that block it and the ones it depends on',
})
blockedBy(@Parent() issue: IssueReadModel) {
return this.blockers.blockedBy(issue);
}
@ResolveField(() => Boolean, { description: 'Whether I voted for it' })
voted(
@CurrentUser() me: User | undefined,
@Parent() issue: IssueReadModel,
): boolean {
return !!me && issue.voterIds.includes(me.id);
}
@ResolveField(() => [IssueGql], { description: 'Linked tickets I can see' })
linkedIssues(
@CurrentUser() me: User | undefined,
@@ -307,6 +326,29 @@ export class IssueResolver {
return this.issuesService.trash(me.id, issueId);
}
@Mutation(() => CommandResultGql, {
description:
'A new ticket like this one: what it says, not where it stands (the key comes in the result)',
})
duplicateIssue(
@CurrentUser() me: User,
@Args('issueId', { type: () => ID }) issueId: string,
) {
return this.issuesService.duplicate(me.id, issueId);
}
@Mutation(() => CommandResultGql, {
description:
'Vote for a ticket (on) or take the vote back: anyone signed in on a public project, members on a private one',
})
voteIssue(
@CurrentUser() me: User,
@Args('issueId', { type: () => ID }) issueId: string,
@Args('on') on: boolean,
) {
return this.issuesService.vote(me.id, issueId, on);
}
@Mutation(() => CommandResultGql, { description: 'Back from the trash' })
restoreIssue(
@CurrentUser() me: User,

View File

@@ -102,6 +102,10 @@ export class ProjectGql {
@Field(() => String, { nullable: true }) description!: string | null;
@Field({ description: 'Anyone can read it, also without signing in' })
isPublic!: boolean;
@Field({
description: 'Takes bug reports and ideas from anyone (while public)',
})
acceptsProposals!: boolean;
@Field(() => UserRefGql) owner!: UserRefGql;
@Field(() => [ProjectMemberGql]) members!: ProjectMemberGql[];
@Field() createdAt!: string;
@@ -374,6 +378,8 @@ export class IssueGql {
})
devLinks!: DevLinkGql[];
@Field(() => Int) commentCount!: number;
@Field(() => Int, { description: 'How many want it done' })
votes!: number;
@Field() createdAt!: string;
@Field() updatedAt!: string;
@Field(() => Int) version!: number;
@@ -440,6 +446,13 @@ export class BoardColumnGql {
@Field(() => Int) total!: number;
}
@ObjectType('CommentReaction', { description: 'One emoji on a comment' })
export class CommentReactionGql {
@Field() emoji!: string;
@Field(() => [UserRefGql], { description: 'Who chose it' })
users!: UserRefGql[];
}
@ObjectType('Comment')
export class CommentGql {
@Field(() => ID) id!: string;
@@ -456,6 +469,10 @@ export class CommentGql {
description: 'Deleted, but kept (without its text) while it has replies',
})
deleted!: boolean;
@Field(() => [CommentReactionGql], {
description: 'In the order they are offered; only the ones somebody chose',
})
reactions!: CommentReactionGql[];
@Field() createdAt!: string;
@Field(() => String, { nullable: true }) editedAt!: string | null;
@Field(() => Int) version!: number;

View File

@@ -36,7 +36,7 @@ import { IssuesService } from '@task-stream/api/tracker/application';
import type { Response } from 'express';
import { viewerOf } from '../common/viewer';
import { AttachFileDto } from './dto/requests.dto';
import { CommandResultDto } from './dto/responses.dto';
import { AttachmentResultDto, CommandResultDto } from './dto/responses.dto';
import { Refs } from './refs';
const ISSUE = ApiParam({
@@ -80,7 +80,7 @@ export class AttachmentsController {
'Multipart with the file as `file` and, optionally, `commentId` to place it under a comment. ' +
'Up to ATTACHMENTS_MAX_MB megabytes (25 by default) and 50 files per ticket.',
})
@ApiCreatedResponse({ type: CommandResultDto })
@ApiCreatedResponse({ type: AttachmentResultDto })
@ApiCommandErrors()
async attach(
@CurrentUser() me: User,

View File

@@ -1,4 +1,12 @@
import { Body, Controller, Delete, Param, Patch } from '@nestjs/common';
import {
Body,
Controller,
Delete,
HttpCode,
Param,
Patch,
Post,
} from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { User } from '@task-stream/api/identity/domain';
import {
@@ -7,7 +15,8 @@ import {
} from '@task-stream/api/identity/presenters';
import { ApiCommandErrors } from '@task-stream/api/shared/presenters';
import { CommentsService } from '@task-stream/api/tracker/application';
import { CommentBodyDto } from './dto/requests.dto';
import { REACTIONS } from '@task-stream/api/tracker/domain';
import { CommentBodyDto, ReactToCommentDto } from './dto/requests.dto';
import { CommandResultDto } from './dto/responses.dto';
/** REST adapter of the comment use cases (listing and adding live under /issues). */
@@ -29,6 +38,22 @@ export class CommentsController {
return this.comments.edit(me.id, commentId, body.body);
}
@Post(':commentId/reactions')
@HttpCode(200)
@ApiOperation({
summary: 'React to a comment, or take the reaction back (members)',
description: `One of ${REACTIONS.join(' ')}; repeating it changes nothing.`,
})
@ApiOkResponse({ type: CommandResultDto })
@ApiCommandErrors()
react(
@CurrentUser() me: User,
@Param('commentId') commentId: string,
@Body() body: ReactToCommentDto,
) {
return this.comments.react(me.id, commentId, body.emoji, body.on);
}
@Delete(':commentId')
@ApiOperation({ summary: 'Delete a comment (author or project admin)' })
@ApiOkResponse({ type: CommandResultDto })

View File

@@ -8,6 +8,7 @@ import {
IssueLinkType,
IssuePriority,
ProjectRole,
REACTIONS,
SETTING_COLORS,
StatusCategory,
TYPE_ICONS,
@@ -88,7 +89,15 @@ export class CreateProjectDto {
export class UpdateProjectDto extends PartialType(
OmitType(CreateProjectDto, ['key'] as const),
) {}
) {
@ApiPropertyOptional({
description:
'Take bug reports and ideas from anyone through the public form (while public)',
})
@IsOptional()
@IsBoolean()
acceptsProposals?: boolean;
}
export class DeleteProjectQueryDto {
@ApiProperty({
@@ -985,6 +994,59 @@ export class AddCommentDto extends CommentBodyDto {
replyTo?: string;
}
export class ReactToCommentDto {
@ApiProperty({ enum: REACTIONS, example: '👍' })
@IsIn(REACTIONS)
emoji!: string;
@ApiProperty({ description: 'true adds the reaction, false takes it back' })
@IsBoolean()
on!: boolean;
}
// ---- Public proposals -------------------------------------------------------
export class ProposalDto {
@ApiProperty({
enum: ['BUG', 'IDEA'],
description: 'A bug report or an idea',
})
@IsIn(['BUG', 'IDEA'])
kind!: 'BUG' | 'IDEA';
@ApiProperty({ minLength: 3, maxLength: 150 })
@IsString()
@MinLength(3)
@MaxLength(150)
title!: string;
@ApiPropertyOptional({
maxLength: 5000,
description: 'What happens, or what they would like (Markdown)',
})
@IsOptional()
@IsString()
@MaxLength(5000)
description?: string;
@ApiPropertyOptional({
maxLength: 80,
description:
'How they sign it; shown in the ticket (no e-mail: it would be public)',
})
@IsOptional()
@IsString()
@MaxLength(80)
author?: string;
@ApiPropertyOptional({
description: 'Leave empty: a field only bots fill in',
})
@IsOptional()
@IsString()
website?: string;
}
// ---- Releases ---------------------------------------------------------------
export class CreateReleaseDto {

View File

@@ -96,6 +96,11 @@ export class ProjectDto {
@ApiProperty({ type: String, nullable: true }) description!: string | null;
@ApiProperty({ description: 'Readable by anyone, also without a token' })
isPublic!: boolean;
@ApiProperty({
description:
'Takes bug reports and ideas from anyone (POST /api/explore/projects/{project}/proposals) while public',
})
acceptsProposals!: boolean;
@ApiProperty({ type: UserRefDto }) owner!: UserRefDto;
@ApiProperty({ type: [ProjectMemberDto] }) members!: ProjectMemberDto[];
@ApiProperty({ type: ProjectSettingsDto })
@@ -279,6 +284,7 @@ class ShowcaseEpicDto {
dueDate!: string | null;
@ApiProperty() percent!: number;
@ApiProperty() done!: boolean;
@ApiProperty({ description: 'How many want it' }) votes!: number;
@ApiProperty({
example: '/p/WEB/issues/WEB-3',
description: 'In the web app',
@@ -308,6 +314,27 @@ class ShowcaseIssueDto {
@ApiProperty({ example: '/p/WEB/issues/WEB-9' }) path!: string;
}
class ShowcaseProposalDto extends ShowcaseIssueDto {
@ApiProperty({ description: 'How many want it' }) votes!: number;
}
class ShowcaseProposalsDto {
@ApiProperty({ description: 'Whether it takes bug reports and ideas now' })
open!: boolean;
@ApiProperty({
type: String,
nullable: true,
example: '/p/WEB/proponer',
description: 'The form in the web app, while it takes them',
})
path!: string | null;
@ApiProperty({
type: [ShowcaseProposalDto],
description: 'Open proposals, most voted first',
})
top!: ShowcaseProposalDto[];
}
export class ShowcaseDto {
@ApiProperty({ type: ShowcaseProjectDto }) project!: ShowcaseProjectDto;
@ApiProperty({ type: ShowcaseSprintDto, nullable: true })
@@ -319,6 +346,25 @@ export class ShowcaseDto {
description: 'Open tickets labelled good-first-issue',
})
goodFirst!: ShowcaseIssueDto[];
@ApiProperty({ type: ShowcaseProposalsDto })
proposals!: ShowcaseProposalsDto;
}
export class ProposalResultDto {
@ApiProperty({
type: String,
nullable: true,
example: 'WEB-42',
description: 'The ticket it became',
})
key!: string | null;
@ApiProperty({
type: String,
nullable: true,
example: '/p/WEB/issues/WEB-42',
description: 'Where to see it in the web app',
})
path!: string | null;
}
export class GitDeliveryResultDto {
@@ -390,6 +436,13 @@ export class IssueDto {
description: 'The epic or ticket this one breaks down',
})
parent!: IssueParentDto | null;
@ApiProperty({
type: [IssueParentDto],
description:
'Open tickets it waits for: the ones that block it and the ones it depends on',
})
blockedBy!: IssueParentDto[];
@ApiProperty({ description: 'How many want it done' }) votes!: number;
@ApiProperty({
description:
'Place in the backlog and its board column (ascending, as text)',
@@ -462,6 +515,11 @@ export class BoardColumnDto {
total!: number;
}
export class CommentReactionDto {
@ApiProperty({ example: '👍' }) emoji!: string;
@ApiProperty({ type: [UserRefDto] }) users!: UserRefDto[];
}
export class CommentDto {
@ApiProperty({ format: 'uuid' }) id!: string;
@ApiProperty({ format: 'uuid' }) issueId!: string;
@@ -481,6 +539,11 @@ export class CommentDto {
description: 'Deleted, but kept (without its text) while it has replies',
})
deleted!: boolean;
@ApiProperty({
type: [CommentReactionDto],
description: 'In the order they are offered; only the ones somebody chose',
})
reactions!: CommentReactionDto[];
@ApiProperty({ format: 'date-time' }) createdAt!: string;
@ApiProperty({ type: String, nullable: true, format: 'date-time' })
editedAt!: string | null;
@@ -649,6 +712,15 @@ export class CommandResultDto {
version!: number;
}
export class AttachmentResultDto extends CommandResultDto {
@ApiProperty({
format: 'uuid',
description:
'The new file; `![name](attachment:<id>)` shows an image inside a description or comment',
})
attachmentId!: string;
}
// ---- Statistics ---------------------------------------------------------------
export class CreatedResolvedDto {

View File

@@ -1,6 +1,17 @@
import { Controller, Get, Header, Param } from '@nestjs/common';
import {
Body,
Controller,
Get,
Header,
Param,
Post,
Req,
} from '@nestjs/common';
import {
ApiCreatedResponse,
ApiForbiddenResponse,
ApiNotFoundResponse,
ApiTooManyRequestsResponse,
ApiOkResponse,
ApiOperation,
ApiParam,
@@ -8,14 +19,24 @@ import {
} from '@nestjs/swagger';
import { Public } from '@task-stream/api/identity/presenters';
import { ProjectsService } from '@task-stream/api/tracker/application';
import { ProjectDto, ShowcaseDto } from './dto/responses.dto';
import { Request } from 'express';
import { ProposalDto } from './dto/requests.dto';
import {
ProjectDto,
ProposalResultDto,
ShowcaseDto,
} from './dto/responses.dto';
import { ProposalLimiter } from './proposal-limiter';
import { toProjectDto } from './refs';
/** What anyone can read without signing in. */
@ApiTags('Explore')
@Controller('explore')
export class ExploreController {
constructor(private readonly projects: ProjectsService) {}
constructor(
private readonly projects: ProjectsService,
private readonly limiter: ProposalLimiter,
) {}
@Get('projects')
@Public()
@@ -47,4 +68,51 @@ export class ExploreController {
showcase(@Param('project') project: string) {
return this.projects.showcase(project);
}
@Post('projects/:project/proposals')
@Public()
@ApiParam({
name: 'project',
description: 'Project id or key',
example: 'WEB',
})
@ApiOperation({
summary: 'Report a bug or propose an idea (no token needed)',
description:
'For public projects that take proposals. It becomes a ticket labelled `propuesta`, opened by TaskStream in the first status (Bug or Feature), signed with `author` if given. Five per address every 15 minutes.',
})
@ApiCreatedResponse({ type: ProposalResultDto })
@ApiNotFoundResponse({ description: 'Not a public project' })
@ApiForbiddenResponse({ description: 'It does not take proposals' })
@ApiTooManyRequestsResponse({ description: 'Too many from this address' })
async propose(
@Param('project') project: string,
@Body() body: ProposalDto,
@Req() req: Request,
): Promise<ProposalResultDto> {
// Bots fill in every field: pretend it worked, and keep nothing.
if (body.website?.trim()) return { key: null, path: null };
this.limiter.take(addressOf(req));
const result = await this.projects.propose(
project,
body.kind,
body.title,
body.description ?? '',
body.author ?? null,
);
const key = result.key ?? null;
return {
key,
path: key ? `/p/${key.split('-')[0]}/issues/${key}` : null,
};
}
}
/** Behind a proxy (Traefik, nginx), who asked comes in X-Forwarded-For. */
function addressOf(req: Request): string {
const forwarded = req.headers['x-forwarded-for'];
const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)
?.split(',')[0]
?.trim();
return first || req.ip || 'unknown';
}

View File

@@ -338,6 +338,45 @@ export class IssuesController {
return this.issues.restore(me.id, await this.refs.issueId(me.id, issue));
}
@Put('issues/:issue/vote')
@ISSUE
@ApiOperation({
summary: 'Vote for the ticket',
description:
'Anyone signed in, on a public project (that is the point: the people it is for say what they want); members on a private one. Voting twice changes nothing.',
})
@ApiOkResponse({ type: CommandResultDto })
@ApiCommandErrors()
async vote(@CurrentUser() me: User, @Param('issue') issue: string) {
return this.issues.vote(me.id, await this.refs.issueId(me.id, issue), true);
}
@Delete('issues/:issue/vote')
@ISSUE
@ApiOperation({ summary: 'Take back my vote for the ticket' })
@ApiOkResponse({ type: CommandResultDto })
@ApiCommandErrors()
async unvote(@CurrentUser() me: User, @Param('issue') issue: string) {
return this.issues.vote(
me.id,
await this.refs.issueId(me.id, issue),
false,
);
}
@Post('issues/:issue/duplicate')
@ISSUE
@ApiOperation({
summary: 'Duplicate the ticket',
description:
'Copies what it says (type, title, description, area, priority, labels, Figma, estimate, dates, parent and checklist steps, unticked), not where it stands: the copy starts in the first status, unassigned, out of sprints and releases, without comments or files. The result carries its key.',
})
@ApiCreatedResponse({ type: CommandResultDto })
@ApiCommandErrors()
async duplicate(@CurrentUser() me: User, @Param('issue') issue: string) {
return this.issues.duplicate(me.id, await this.refs.issueId(me.id, issue));
}
@Get('projects/:project/trash')
@ApiOptionalPireonAuth()
@PROJECT

View File

@@ -0,0 +1,33 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
/** Proposals from one address within the window. */
const LIMIT = 5;
const WINDOW_MS = 15 * 60_000;
/**
* Keeps one address from flooding a project with proposals. In memory:
* enough for one instance, and an approximation with several (each counts
* its own), which is fine for what it guards against.
*/
@Injectable()
export class ProposalLimiter {
private readonly sent = new Map<string, number[]>();
take(address: string): void {
const now = Date.now();
const recent = (this.sent.get(address) ?? []).filter(
(at) => now - at < WINDOW_MS,
);
if (recent.length >= LIMIT)
throw new HttpException(
'Too many proposals from here; try again in a few minutes',
HttpStatus.TOO_MANY_REQUESTS,
);
recent.push(now);
this.sent.set(address, recent);
// Forget quiet addresses now and then, so the map does not grow forever.
if (this.sent.size > 10_000)
for (const [key, times] of this.sent)
if (times.every((at) => now - at >= WINDOW_MS)) this.sent.delete(key);
}
}

View File

@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import {
BlockersService,
IssuesService,
ProjectsService,
WorkflowsService,
@@ -23,6 +24,7 @@ export class Refs {
private readonly projects: ProjectsService,
private readonly issues: IssuesService,
private readonly workflows: WorkflowsService,
private readonly blockers: BlockersService,
) {}
async projectId(viewerId: string | null, ref: string): Promise<string> {
@@ -35,12 +37,15 @@ export class Refs {
return (await this.issues.findOne(viewerId, ref)).id;
}
/** The ticket as the REST API returns it: read model + allowed transitions. */
/** The ticket as the REST API returns it: read model, allowed transitions and what blocks it. */
async issueDto(issue: IssueReadModel) {
return {
...issue,
allowedTransitions: await this.workflows.allowedTransitions(issue),
};
const [allowedTransitions, blockedBy] = await Promise.all([
this.workflows.allowedTransitions(issue),
this.blockers.blockedBy(issue),
]);
// Who voted is only for telling someone whether they did.
const { voterIds: _voters, ...shown } = issue;
return { ...shown, allowedTransitions, blockedBy };
}
issueDtos(issues: IssueReadModel[]) {

View File

@@ -12,6 +12,7 @@ import { AttachmentsController } from './http/attachments.controller';
import { CommentsController } from './http/comments.controller';
import { IssuesController } from './http/issues.controller';
import { ExploreController } from './http/explore.controller';
import { ProposalLimiter } from './http/proposal-limiter';
import { ProjectsController } from './http/projects.controller';
import { Refs } from './http/refs';
import { ReleasesController } from './http/releases.controller';
@@ -63,6 +64,7 @@ import { AutomationResolver } from './graphql/automation.resolver';
],
providers: [
Refs,
ProposalLimiter,
ProjectResolver,
IssueResolver,
CommentResolver,

View File

@@ -43,6 +43,7 @@ export const APP_ICONS: Record<string, string> = {
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M6 6l12 12M18 6 6 18"/></svg>',
coins:
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="6.5" rx="7" ry="3"/><path d="M5 6.5v5c0 1.7 3.1 3 7 3s7-1.3 7-3v-5M5 11.5v5c0 1.7 3.1 3 7 3s7-1.3 7-3v-5"/></svg>',
copy: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg>',
document:
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z"/><path d="M14 3v5h5M9 13h6M9 17h4"/></svg>',
email:

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"]
}

Some files were not shown because too many files have changed in this diff Show More