Make task list items clickable in markdown

This commit is contained in:
Brandon Oxendine
2026-10-06 14:33:08 +02:00
committed by Rūdolfs Ošiņš
parent dee73cb8f8
commit d6145300c1
14 changed files with 1053 additions and 79 deletions
+12 -1
View File
@@ -775,7 +775,18 @@
class="revision-description-body txt-body-m-regular"
bind:this={descriptionEl}>
{#if showRevisionDescription}
<Markdown {rid} breaks content={revisionDescription} />
<Markdown
{rid}
breaks
content={revision.description.slice(-1)[0]?.body ?? ""}
toggleTaskItem={canEditDescription && onSaveDescription
? async content => {
await onSaveDescription(
content,
revision.description.slice(-1)[0]?.embeds ?? [],
);
}
: undefined} />
{:else}
<span style:color="var(--color-text-tertiary)">No description</span>
{/if}
+12 -1
View File
@@ -404,7 +404,18 @@
{:else}
<div style:width="100%">
<div style:overflow="hidden">
<Markdown {rid} breaks content={body ?? ""} />
<Markdown
{rid}
breaks
content={body ?? ""}
toggleTaskItem={editComment
? async content => {
await editComment(
content,
Array.from(embeds?.values() ?? []),
);
}
: undefined} />
</div>
</div>
{/if}
+11 -1
View File
@@ -13,6 +13,7 @@
interface Props {
rid: string;
body: string;
embeds: Embed[];
reactions: Reaction[];
currentUserNid?: string;
allowedToEdit: boolean;
@@ -23,6 +24,7 @@
const {
rid,
body,
embeds,
reactions,
currentUserNid,
allowedToEdit,
@@ -98,7 +100,15 @@
{:else}
<div class="description-body txt-body-m-regular">
{#if body.trim() !== ""}
<Markdown {rid} breaks content={body} />
<Markdown
{rid}
breaks
content={body}
toggleTaskItem={allowedToEdit
? async content => {
await editComment(content, embeds);
}
: undefined} />
{:else}
<span style:color="var(--color-text-tertiary)">No description</span>
{/if}
+235 -70
View File
@@ -1,7 +1,6 @@
<script lang="ts">
import type { Embed } from "@bindings/cob/Embed";
import dompurify from "dompurify";
import { toDom } from "hast-util-to-dom";
import { mount, tick, unmount } from "svelte";
@@ -9,9 +8,10 @@
import { parseFrontmatter } from "@app/lib/frontmatter";
import { invoke } from "@app/lib/invoke";
import {
markdownWithExtensions,
isTaskCheckbox,
maximumReferences,
Renderer,
renderMarkdown,
toggleTask,
} from "@app/lib/markdown";
import { parseEntityHref } from "@app/lib/mentions";
import { isOid } from "@app/lib/radUri";
@@ -27,9 +27,19 @@
content: string;
// If true, add <br> on a single line break
breaks?: boolean;
toggleTaskItem?: (content: string) => Promise<void> | void;
}
const { rid = "", content, breaks = false }: Props = $props();
const {
rid = "",
content,
breaks = false,
toggleTaskItem = undefined,
}: Props = $props();
let taskInFlight = $state(false);
let refocusTask: number | undefined = undefined;
let scrolledToHash = false;
let container: HTMLElement;
@@ -44,6 +54,68 @@
$effect(() => unmountMentions);
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- imperative oid→element lookup, never rendered reactively
const embedPreviews = new Map<
string,
{ element: HTMLElement; url: string }
>();
let destroyed = false;
$effect(() => () => {
destroyed = true;
for (const { url } of embedPreviews.values()) {
URL.revokeObjectURL(url);
}
embedPreviews.clear();
});
function createEmbedPreview(
mimeType: string | null,
url: string,
): HTMLElement | undefined {
const kind = embedPreviewKind(mimeType);
if (kind === "image") {
const element = document.createElement("img");
element.setAttribute("src", url);
element.style.display = "block";
return element;
} else if (kind === "document") {
const element = document.createElement("embed");
element.setAttribute("src", url);
element.type = mimeType ?? "";
element.style.overflow = "scroll";
element.style.height = "40rem";
element.style.overscrollBehavior = "contain";
return element;
} else if (kind === "video") {
const element = document.createElement("video");
const node = document.createElement("source");
node.src = url;
element.controls = true;
node.type = mimeType ?? "";
element.style.width = "100%";
element.appendChild(node);
return element;
} else if (kind === "audio") {
const element = document.createElement("audio");
element.style.display = "block";
element.src = url;
element.controls = true;
return element;
}
}
function placeEmbedPreview(link: HTMLAnchorElement, element: HTMLElement) {
link.style.display = "block";
link.insertAdjacentElement(
"afterend",
container.contains(element)
? (element.cloneNode(true) as HTMLElement)
: element,
);
}
const doc = $derived(parseFrontmatter(content));
const frontMatter = $derived.by(() => {
try {
@@ -55,15 +127,6 @@
}
});
function render(content: string): string {
return dompurify.sanitize(
markdownWithExtensions.parse(content, {
renderer: new Renderer(),
breaks,
}) as string,
);
}
$effect(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
content;
@@ -78,18 +141,85 @@
unmountMentions();
// Replace native task-list checkboxes with read-only styled boxes.
twemoji(container, { exclude: ["21a9"] });
let taskIndex = 0;
for (const i of container.querySelectorAll('input[type="checkbox"]')) {
i.parentElement?.classList.add("task-item");
const box = document.createElement("span");
const isTask = isTaskCheckbox(i);
const index = isTask ? taskIndex++ : -1;
const item = i.closest("li");
item?.classList.add("task-item");
const checked = i.hasAttribute("checked");
const interactive = toggleTaskItem !== undefined && isTask;
const box = document.createElement(interactive ? "button" : "span");
box.classList.add("task-box");
if (i.hasAttribute("checked")) {
box.classList.add("checked");
icons.push(
mount(Icon, { target: box, props: { name: "checkmark" } }),
);
box.classList.toggle("checked", checked);
icons.push(mount(Icon, { target: box, props: { name: "checkmark" } }));
if (interactive && box instanceof HTMLButtonElement) {
box.type = "button";
box.setAttribute("role", "checkbox");
box.setAttribute("aria-checked", String(checked));
const label = item?.cloneNode(true) as HTMLElement | undefined;
label?.querySelectorAll("ul, ol").forEach(list => list.remove());
box.setAttribute("aria-label", label?.textContent?.trim() || "Task");
const setChecked = (value: boolean) => {
box.classList.toggle("checked", value);
box.setAttribute("aria-checked", String(value));
};
box.onclick = async () => {
if (taskInFlight || !toggleTaskItem) {
return;
}
const source = content;
const next = toggleTask(source, index);
if (next === undefined) {
console.warn("Not able to find task item in markdown source");
return;
}
taskInFlight = true;
if (document.activeElement === box) {
refocusTask = index;
}
setChecked(!checked);
try {
await toggleTaskItem(next);
} catch (error) {
console.error("Not able to save task item: ", error);
} finally {
taskInFlight = false;
if (content === source) {
setChecked(checked);
refocusTask = undefined;
}
}
};
}
i.replaceWith(box);
if (interactive && index === refocusTask) {
refocusTask = undefined;
box.focus();
}
const text = box.nextSibling;
if (text?.nodeType === Node.TEXT_NODE && text.textContent) {
text.textContent = text.textContent.replace(/^[ \t]+/, "");
}
}
for (const list of container.querySelectorAll("ul, ol")) {
const items = Array.from(list.children);
if (
items.length > 0 &&
items.every(c => c.classList.contains("task-item"))
) {
list.classList.add("task-list");
const lead = list.previousElementSibling;
if (lead instanceof HTMLParagraphElement) {
lead.classList.add("task-list-lead");
}
}
}
let references = 0;
@@ -163,53 +293,41 @@
name: e.innerText,
}).catch(console.error);
};
void invoke<Embed>("get_embed", {
rid,
name: e.innerText,
oid: href,
})
.then(({ mimeType, content }) => {
const buffer = Buffer.from(content);
const blob = new Blob([buffer]);
const url = URL.createObjectURL(blob);
const kind = embedPreviewKind(mimeType);
if (kind === "image") {
const element = document.createElement("img");
element.setAttribute("src", url);
element.style.display = "block";
e.style.display = "block";
e.insertAdjacentElement("afterend", element);
} else if (kind === "document") {
const element = document.createElement("embed");
element.setAttribute("src", url);
element.type = mimeType ?? "";
element.style.overflow = "scroll";
element.style.height = "40rem";
element.style.overscrollBehavior = "contain";
e.style.display = "block";
e.insertAdjacentElement("afterend", element);
} else if (kind === "video") {
const element = document.createElement("video");
const node = document.createElement("source");
node.src = url;
element.controls = true;
node.type = mimeType ?? "";
element.style.width = "100%";
e.style.display = "block";
element.appendChild(node);
e.insertAdjacentElement("afterend", element);
} else if (kind === "audio") {
const element = document.createElement("audio");
element.style.display = "block";
element.src = url;
element.controls = true;
e.style.display = "block";
e.insertAdjacentElement("afterend", element);
} else {
console.warn(`Not able to provide a preview for this file.`);
}
const cached = embedPreviews.get(href);
if (cached) {
placeEmbedPreview(e, cached.element);
} else {
void invoke<Embed>("get_embed", {
rid,
name: e.innerText,
oid: href,
})
.catch(console.error);
.then(({ mimeType, content }) => {
if (destroyed) {
return;
}
let preview = embedPreviews.get(href);
if (!preview) {
const url = URL.createObjectURL(
new Blob([Buffer.from(content)]),
);
const element = createEmbedPreview(mimeType, url);
if (!element) {
URL.revokeObjectURL(url);
console.warn(
`Not able to provide a preview for this file.`,
);
return;
}
preview = { element, url };
embedPreviews.set(href, preview);
}
if (e.isConnected) {
placeEmbedPreview(e, preview.element);
}
})
.catch(console.error);
}
}
}
@@ -247,9 +365,10 @@
void Promise.allSettled(treeChanges);
if (window.location.hash) {
if (!scrolledToHash && window.location.hash) {
scrollIntoView(window.location.hash.substring(1));
}
scrolledToHash = true;
});
return () => {
@@ -356,6 +475,25 @@
.markdown :global(li.task-item) {
list-style-type: none;
color: var(--color-text-secondary);
padding-left: 1.75rem;
text-indent: -1.75rem;
}
.markdown :global(li.task-item ul),
.markdown :global(li.task-item ol),
.markdown :global(li.task-item pre),
.markdown :global(li.task-item blockquote),
.markdown :global(li.task-item table) {
text-indent: 0;
}
.markdown :global(.task-list) {
padding-left: 0;
margin-top: 0;
}
.markdown :global(p.task-list-lead) {
margin-bottom: 0;
}
.markdown :global(li.task-item > p) {
margin-bottom: 0;
}
.markdown :global(li.task-item .task-box) {
display: inline-flex;
@@ -365,6 +503,8 @@
height: 1.25rem;
margin-right: 0.5rem;
vertical-align: middle;
position: relative;
top: -0.09em;
border: 1px solid var(--color-border-mid);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-base);
@@ -372,6 +512,27 @@
.markdown :global(li.task-item .task-box.checked) {
color: var(--color-text-brand);
}
.markdown :global(li.task-item .task-box:not(.checked) svg) {
visibility: hidden;
}
.markdown :global(li.task-item button.task-box) {
padding: 0;
cursor: pointer;
transition:
background-color 0.1s ease,
border-color 0.1s ease;
}
.markdown :global(li.task-item button.task-box:focus-visible) {
outline: 2px solid var(--color-border-brand);
outline-offset: 1px;
}
.markdown.busy :global(li.task-item button.task-box) {
cursor: progress;
}
.markdown :global(li.task-item button.task-box:hover) {
border-color: var(--color-border-strong);
background-color: var(--color-surface-subtle);
}
.markdown :global(li.task-item:not(:last-child)) {
margin-bottom: 0.25rem;
}
@@ -544,6 +705,10 @@
</div>
{/if}
<div class="markdown" bind:this={container} use:twemoji={{ exclude: ["21a9"] }}>
{@html render(doc.content)}
<div
class="markdown"
class:busy={taskInFlight}
aria-busy={taskInFlight}
bind:this={container}>
{@html renderMarkdown(doc.content, breaks)}
</div>
+11 -3
View File
@@ -20,10 +20,18 @@
summary: string;
timestamp: number;
onViewFullReview?: () => void;
toggleTaskItem?: (summary: string) => Promise<void>;
}
const { rid, author, verdict, summary, timestamp, onViewFullReview }: Props =
$props();
const {
rid,
author,
verdict,
summary,
timestamp,
onViewFullReview,
toggleTaskItem,
}: Props = $props();
const badge = $derived(verdictBadge(verdict));
</script>
@@ -112,7 +120,7 @@
</div>
{#if summary.trim() !== ""}
<div class="body txt-body-m-regular">
<Markdown {rid} breaks content={summary} />
<Markdown {rid} breaks content={summary} {toggleTaskItem} />
</div>
{/if}
</div>
+9 -1
View File
@@ -968,7 +968,15 @@
{:else if summary !== "" || isOwnPublishedReview}
<div class="summary">
{#if summary !== ""}
<Markdown {rid} breaks content={summary} />
<Markdown
{rid}
breaks
content={review.summary ?? ""}
toggleTaskItem={isOwnPublishedReview
? async content => {
await saveSummary(content);
}
: undefined} />
{:else}
<span class="summary-empty">No summary.</span>
{/if}
+59 -2
View File
@@ -4,6 +4,7 @@
import type { Operation } from "@bindings/cob/Operation";
import type { Action } from "@bindings/cob/patch/Action";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { Verdict } from "@bindings/cob/patch/Verdict";
import type { CodeLocation } from "@bindings/cob/thread/CodeLocation";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Thread } from "@bindings/cob/thread/Thread";
@@ -36,6 +37,7 @@
import {
groupCommitsByAuthor,
isCommitListDescription,
replaceDescriptionBody,
splitDescription,
visibleCommitsOf,
} from "@app/lib/revisionDescription";
@@ -596,6 +598,31 @@
}
}
async function editReviewSummary(
reviewId: string,
summary: string,
review: { verdict?: Verdict; labels?: string[] },
) {
try {
await invoke("edit_patch", {
rid,
cobId: patchId,
action: {
type: "review.edit",
review: reviewId,
summary,
verdict: review.verdict,
labels: review.labels ?? [],
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Editing review summary failed: ", error);
} finally {
await loadPatch();
}
}
async function createComment(
body: string,
embeds: Embed[],
@@ -1024,7 +1051,17 @@
{:else}
<div class="patch-body txt-body-m-regular">
{#if body.trim() !== ""}
<Markdown {rid} content={body} />
<Markdown
{rid}
content={body}
toggleTaskItem={canEdit
? async content => {
await editRevision(
content,
revision.description.slice(-1)[0]?.embeds ?? [],
);
}
: undefined} />
{:else}
<span style:color="var(--color-text-tertiary)">No description</span>
{/if}
@@ -1087,6 +1124,7 @@
repoDelegates.map(d => d.did),
targetRev.author.did,
)}
{@const fullDescription = data.op.description}
{@const descriptionSubject = splitDescription(
data.op.description,
).subject}
@@ -1140,7 +1178,19 @@
</div>
{:else if descriptionVisible}
<div class="revision-card-description txt-body-m-regular">
<Markdown {rid} breaks content={revBody} />
<Markdown
{rid}
breaks
content={revBody}
toggleTaskItem={canEditRevision
? async content => {
await editRevision(
replaceDescriptionBody(fullDescription, content),
targetRev?.description.slice(-1)[0]?.embeds ?? [],
revId,
);
}
: undefined} />
{#if canEditRevision}
<div class="revision-card-description-actions">
<button
@@ -1368,12 +1418,19 @@
r => r.id === opId,
)}
{@const hasReviewComments = (reviewRecord?.comments?.length ?? 0) > 0}
{@const reviewOp = data.op}
<ReviewItem
{rid}
author={data.op.author}
verdict={data.op.verdict}
summary={data.op.summary ?? ""}
timestamp={data.op.timestamp}
toggleTaskItem={data.op.author.did ===
didFromPublicKey(config.publicKey)
? async summary => {
await editReviewSummary(opId, summary, reviewOp);
}
: undefined}
onViewFullReview={hasReviewComments
? () =>
void push({
+12
View File
@@ -7,6 +7,7 @@
import type { Snippet } from "svelte";
import { tick } from "svelte";
import { SvelteMap } from "svelte/reactivity";
import type { Resolution } from "@app/lib/commentResolutions";
import { formatResolvedCaption, scrollIntoView } from "@app/lib/utils";
@@ -78,6 +79,15 @@
resolvedBy,
}: Props = $props();
function embedsOf(comment: { embeds?: Embed[] }): Map<string, Embed> {
return new SvelteMap(
(comment.embeds ?? []).map(embed => [
embed.content.replace(/^git:/, ""),
embed,
]),
);
}
function resolvedCaption(commentId: string): string | undefined {
const resolution = resolvedBy?.(commentId);
return (
@@ -218,6 +228,7 @@
reactions={reply.reactions}
timestamp={reply.edits[0].timestamp}
body={reply.edits.slice(-1)[0].body}
embeds={embedsOf(reply)}
editComment={canModifyComment(reply.author.did) &&
editComment?.bind(null, reply.id)}
reactOnComment={reactOnComment?.bind(null, reply.id)}
@@ -271,6 +282,7 @@
reactions={root.reactions}
timestamp={root.edits.slice(-1)[0].timestamp}
body={root.edits.slice(-1)[0].body}
embeds={embedsOf(root)}
editComment={canModifyComment(root.author.did) &&
editComment?.bind(null, root.id)}
reactOnComment={reactOnComment?.bind(null, root.id)}
+101
View File
@@ -14,6 +14,7 @@ import katexMarkedExtension from "marked-katex-extension";
import markedLinkifyIt from "marked-linkify-it";
import emojis from "@app/lib/emojis";
import { parseFrontmatter } from "@app/lib/frontmatter";
import { bareReferenceStart, matchBareReference } from "@app/lib/mentions";
// DOMPurify only keeps hrefs whose scheme it recognises, and drops `rad:` and
@@ -129,6 +130,8 @@ const radicleReferenceMarkedExtension: TokenizerExtension & RendererExtension =
`<a href="${escape(token.text)}">${escape(token.text)}</a>`,
};
const TASK_CHECKBOX_CLASS = "task-checkbox";
export class Renderer extends BaseRenderer {
/**
* If `baseUrl` is provided, all hrefs attributes in anchor tags, except those
@@ -152,6 +155,10 @@ export class Renderer extends BaseRenderer {
return `<h${depth} id="${id}">${text}</h${depth}>`;
}
checkbox({ checked }: Tokens.Checkbox): string {
return `<input class="${TASK_CHECKBOX_CLASS}" ${checked ? 'checked="" ' : ""}disabled="" type="checkbox"> `;
}
link({ href, title, tokens }: Tokens.Link): string {
const text = this.parser.parseInline(tokens);
const normalizedHref = href.startsWith("#") ? href.toLowerCase() : href;
@@ -176,3 +183,97 @@ export const markdownWithExtensions = new Marked(
extensions: [anchorMarkedExtension, radicleReferenceMarkedExtension],
}))(),
);
export function renderMarkdown(content: string, breaks = false): string {
return dompurify.sanitize(
markdownWithExtensions.parse(content, {
renderer: new Renderer(),
breaks,
}) as string,
);
}
const TASK_CANDIDATE_RE = /(?:[-*+]|\d{1,9}[.)])[ \t]+\[([ xX])\]/g;
const CODE_FENCE_RE = /^[ \t]*(`{3,}|~{3,})/;
export function isTaskCheckbox(element: Element): boolean {
return element.getAttribute("class") === TASK_CHECKBOX_CLASS;
}
function taskStates(content: string): boolean[] {
// A template's content is inert, so nothing in it loads or runs.
const template = document.createElement("template");
template.innerHTML = renderMarkdown(content);
return Array.from(template.content.querySelectorAll('input[type="checkbox"]'))
.filter(isTaskCheckbox)
.map(input => input.hasAttribute("checked"));
}
function fencedRanges(content: string): [number, number][] {
const ranges: [number, number][] = [];
let open: { fence: string; start: number } | undefined;
let offset = 0;
for (const line of content.split("\n")) {
const fence = CODE_FENCE_RE.exec(line)?.[1];
if (fence && open === undefined) {
open = { fence, start: offset };
} else if (
fence &&
open &&
fence[0] === open.fence[0] &&
fence.length >= open.fence.length
) {
ranges.push([open.start, offset + line.length]);
open = undefined;
}
offset += line.length + 1;
}
if (open) {
ranges.push([open.start, content.length]);
}
return ranges;
}
/// Flips the task-list box at `index`, counted in rendered order.
export function toggleTask(input: string, index: number): string | undefined {
// Frontmatter is not rendered, so it is left out of the search.
const { content } = parseFrontmatter(input);
const prefix = input.slice(0, input.length - content.length);
const states = taskStates(content);
if (index >= states.length) {
return undefined;
}
const positions = Array.from(
content.matchAll(TASK_CANDIDATE_RE),
match => match.index + match[0].length - 2,
);
const fenced = fencedRanges(content);
const inCode = (p: number) =>
fenced.some(([start, end]) => p >= start && p <= end);
const outside = positions.filter(p => !inCode(p));
const likely = outside[index];
const ordered = [
...(likely === undefined ? [] : [likely]),
...outside.filter(p => p !== likely),
...positions.filter(inCode),
];
for (const position of ordered) {
const next =
content.slice(0, position) +
(content[position] === " " ? "x" : " ") +
content.slice(position + 1);
const nextStates = taskStates(next);
if (
nextStates.length === states.length &&
nextStates.every((checked, i) =>
i === index ? checked !== states[i] : checked === states[i],
)
) {
return prefix + next;
}
}
return undefined;
}
+18
View File
@@ -18,6 +18,24 @@ export function splitDescription(text: string): {
};
}
/// Swaps the body beneath the subject, keeping everything else as written.
export function replaceDescriptionBody(
description: string,
body: string,
): string {
const { subject = "", body: current = "" } = splitDescription(description);
const subjectEnd = description.indexOf(subject) + subject.length;
const start = current ? description.indexOf(current, subjectEnd) : -1;
if (start === -1) {
return subject ? `${subject}\n\n${body}` : body;
}
return (
description.slice(0, start) +
body +
description.slice(start + current.length)
);
}
/// The first line of a revision's current description.
export function revisionTitle(revision: Revision): string | undefined {
return splitDescription(revision.description.at(-1)?.body ?? "").subject;
+1
View File
@@ -352,6 +352,7 @@
<IssueDescription
rid={repo.rid}
body={body.edits.slice(-1)[0].body}
embeds={body.embeds ?? []}
reactions={body.reactions}
currentUserNid={config.publicKey}
allowedToEdit={!!canEditIssue}
+474
View File
@@ -0,0 +1,474 @@
import type { Comment } from "@bindings/cob/thread/Comment";
import type { Thread } from "@bindings/cob/thread/Thread";
import type { Page } from "@playwright/test";
import type { RadiclePeer } from "@tests/support/peerManager.js";
import * as Fs from "node:fs/promises";
import * as Path from "node:path";
import * as issue from "@tests/support/cobs/issue.js";
import * as patch from "@tests/support/cobs/patch.js";
import {
clone,
createCollaborators,
createProject,
} from "@tests/support/collaboration.js";
import {
expect,
goto,
reload,
test,
useBackend,
waitForCommand,
} from "@tests/support/fixtures.js";
const taskList =
"Before the release:\n\n- [ ] Check the tone\n- [ ] Ask a reader";
const onePixelPng = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
"base64",
);
function api(page: Page, peer: RadiclePeer, command: string, data: object) {
return page.request
.post(`http://127.0.0.1:${peer.httpdBaseUrl.port}/${command}`, { data })
.then(response => response.json());
}
async function saveEmbed(
page: Page,
peer: RadiclePeer,
rid: string,
name: string,
bytes: Uint8Array,
) {
return (await api(page, peer, "save_embed_by_bytes", {
rid,
name,
bytes: Array.from(bytes),
})) as string;
}
async function createComment(
page: Page,
peer: RadiclePeer,
rid: string,
issueId: string,
body: string,
embedOid?: string,
replyTo?: string,
) {
return (await api(page, peer, "create_issue_comment", {
rid,
new: {
id: issueId,
body: embedOid ? `${body}\n\n[megaphone.txt](${embedOid})` : body,
embeds: embedOid
? [{ name: "megaphone.txt", content: `git:${embedOid}` }]
: [],
replyTo,
},
opts: { announce: false },
})) as Comment;
}
async function storedComment(
page: Page,
peer: RadiclePeer,
rid: string,
issueId: string,
text: string,
) {
const threads = (await api(page, peer, "comment_threads_by_issue_id", {
rid,
id: issueId,
})) as Thread[];
return threads
.flatMap(thread => [thread.root, ...thread.replies])
.find(comment => comment.edits.at(-1)?.body.includes(text));
}
async function createTaskIssue(peer: RadiclePeer, description = taskList) {
const { rid, repoFolder } = await createProject(peer);
const issueId = await issue.create(peer, "Tidy the notes", description, [], {
cwd: repoFolder,
});
return { rid, issueId, repoFolder };
}
async function openTaskIssue(
page: Page,
peer: RadiclePeer,
description = taskList,
) {
const { rid, issueId } = await createTaskIssue(peer, description);
await page.goto(`/repos/${rid}/issues/${issueId}`);
await expect(page.getByText("Before the release:")).toBeVisible();
}
test("ticking a task in an issue description is saved", async ({
page,
peer,
}) => {
await openTaskIssue(page, peer);
const tone = page.getByRole("checkbox", { name: "Check the tone" });
const reader = page.getByRole("checkbox", { name: "Ask a reader" });
await expect(tone).not.toBeChecked();
await waitForCommand(page, "edit_issue", () => tone.press("Space"));
await expect(tone).toBeChecked();
await expect(tone).toBeFocused();
await reload(page);
await expect(tone).toBeChecked();
await expect(reader).not.toBeChecked();
await waitForCommand(page, "edit_issue", () => tone.click());
await reload(page);
await expect(tone).not.toBeChecked();
});
test("a task that fails to save is unticked again", async ({ page, peer }) => {
await openTaskIssue(page, peer);
let release: (() => void) | undefined;
const released = new Promise<void>(resolve => (release = resolve));
await page.route("**/edit_issue", async route => {
await released;
await route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ code: "Unknown", message: "Not saved" }),
});
});
const tone = page.getByRole("checkbox", { name: "Check the tone" });
await tone.click();
await expect(tone).toBeChecked();
release?.();
await expect(tone).not.toBeChecked();
});
test("emojis stay rendered after ticking a task", async ({ page, peer }) => {
await openTaskIssue(page, peer, `${taskList}\n\nParty after 🎉`);
const party = page.getByRole("img", { name: "🎉" });
await expect(party).toBeVisible();
await waitForCommand(page, "edit_issue", () =>
page.getByRole("checkbox", { name: "Check the tone" }).click(),
);
await expect(
page.getByRole("checkbox", { name: "Check the tone" }),
).toBeChecked();
await expect(party).toBeVisible();
});
test("ticking a task doesn't load the embeds again", async ({ page, peer }) => {
const { rid, repoFolder } = await createProject(peer);
const oid = await saveEmbed(page, peer, rid, "dot.png", onePixelPng);
const issueId = await issue.create(
peer,
"Tidy the notes",
`${taskList}\n\n[dot.png](${oid})`,
[],
{ cwd: repoFolder },
);
let loads = 0;
page.on("request", request => {
if (new URL(request.url()).pathname === "/get_embed") {
loads++;
}
});
await page.goto(`/repos/${rid}/issues/${issueId}`);
const preview = page.locator('img[src^="blob:"]');
await expect(preview).toBeVisible();
expect(loads).toBe(1);
const tone = page.getByRole("checkbox", { name: "Check the tone" });
await waitForCommand(page, "edit_issue", () => tone.click());
await expect(tone).toBeChecked();
await expect(preview).toBeVisible();
expect(loads).toBe(1);
});
test("ticking a task in a comment keeps the comment's embeds", async ({
page,
peer,
}) => {
const { rid, issueId } = await createTaskIssue(peer);
const oid = await saveEmbed(
page,
peer,
rid,
"megaphone.txt",
new TextEncoder().encode("loud"),
);
await createComment(
page,
peer,
rid,
issueId,
"Before the meeting:\n\n- [ ] Bring a megaphone",
oid,
);
await page.goto(`/repos/${rid}/issues/${issueId}`);
const megaphone = page.getByRole("checkbox", { name: "Bring a megaphone" });
await waitForCommand(page, "edit_issue", () => megaphone.click());
await expect(megaphone).toBeChecked();
const comment = await storedComment(
page,
peer,
rid,
issueId,
"Bring a megaphone",
);
expect(comment?.edits.at(-1)?.body).toContain("- [x] Bring a megaphone");
expect(comment?.embeds).toEqual([
{ name: "megaphone.txt", content: `git:${oid}` },
]);
});
test("ticking a task in a reply keeps the reply's embeds", async ({
page,
peer,
}) => {
const { rid, issueId } = await createTaskIssue(peer);
const oid = await saveEmbed(
page,
peer,
rid,
"megaphone.txt",
new TextEncoder().encode("loud"),
);
const root = await createComment(page, peer, rid, issueId, "Who brings it?");
await createComment(
page,
peer,
rid,
issueId,
"- [ ] Bring a megaphone",
oid,
root.id,
);
await page.goto(`/repos/${rid}/issues/${issueId}`);
const megaphone = page.getByRole("checkbox", { name: "Bring a megaphone" });
await waitForCommand(page, "edit_issue", () => megaphone.click());
await expect(megaphone).toBeChecked();
const reply = await storedComment(
page,
peer,
rid,
issueId,
"Bring a megaphone",
);
expect(reply?.replyTo).toBe(root.id);
expect(reply?.embeds).toEqual([
{ name: "megaphone.txt", content: `git:${oid}` },
]);
});
test("editing a comment keeps its embeds", async ({ page, peer }) => {
const { rid, issueId } = await createTaskIssue(peer);
const oid = await saveEmbed(
page,
peer,
rid,
"megaphone.txt",
new TextEncoder().encode("loud"),
);
await createComment(page, peer, rid, issueId, "Bring a megaphone", oid);
await page.goto(`/repos/${rid}/issues/${issueId}`);
await page.getByText("Bring a megaphone").hover();
const toggle = page.getByTitle("Comment actions").last();
await toggle.click();
await toggle
.locator(`xpath=following::*[@role="button"][normalize-space()="Edit"][1]`)
.click();
await page
.getByPlaceholder("Leave a comment")
.first()
.fill(`Bring two megaphones\n\n[megaphone.txt](${oid})`);
await waitForCommand(page, "edit_issue", () =>
page.getByRole("button", { name: /^Save/ }).click(),
);
const comment = await storedComment(
page,
peer,
rid,
issueId,
"Bring two megaphones",
);
expect(comment?.embeds).toEqual([
{ name: "megaphone.txt", content: `git:${oid}` },
]);
});
test("a contributor can't tick tasks in someone else's issue", async ({
page,
peerManager,
}) => {
const { bob, eve } = await createCollaborators(peerManager);
const { rid, issueId, repoFolder } = await createTaskIssue(bob);
await bob.rad(
[
"issue",
"comment",
issueId,
"--message",
"Before the meeting:\n\n- [ ] Bring a megaphone",
"--quiet",
],
{ cwd: repoFolder },
);
await clone(eve, rid);
await eve.startHttpd();
await useBackend(page, eve);
await page.goto(`/repos/${rid}/issues/${issueId}`);
await expect(page.getByText("Check the tone")).toBeVisible();
await expect(page.getByText("Bring a megaphone")).toBeVisible();
await expect(page.getByRole("checkbox")).toHaveCount(0);
});
async function createTaskPatch(peer: RadiclePeer) {
const { rid, repoFolder } = await createProject(peer);
const notes = Path.join(repoFolder, "notes.txt");
const patchId = await patch.create(
peer,
["Quiet the notes"],
"feature/quiet",
() => Fs.writeFile(notes, "one\n"),
["Quiet the notes", "- [ ] Lower the volume"],
{ cwd: repoFolder },
);
await Fs.writeFile(notes, "one\ntwo\n");
await peer.git(["commit", "-am", "Keep the second line"], {
cwd: repoFolder,
});
// Push options can't hold line breaks, so each task is its own message.
await peer.git(
[
"push",
"-o",
"patch.message=Quieter after all",
"-o",
"patch.message=- [ ] Check the tone",
"-o",
"patch.message=- [ ] Ask a reader",
"rad",
`HEAD:refs/heads/patches/${patchId}`,
],
{ cwd: repoFolder },
);
await peer.rad(
[
"patch",
"review",
patchId,
"--message=Before merging:\n\n- [ ] Rename the file",
"--accept",
],
{ cwd: repoFolder },
);
return { rid, patchId };
}
async function openTaskPatch(page: Page, peer: RadiclePeer, query = "") {
const { rid, patchId } = await createTaskPatch(peer);
await page.goto(`/repos/${rid}/patches/${patchId}${query}`);
await expect(page.getByText("Quieter after all").first()).toBeVisible();
}
test("ticking a task in a patch description is saved", async ({
page,
peer,
}) => {
await openTaskPatch(page, peer);
const volume = page.getByRole("checkbox", { name: "Lower the volume" });
await waitForCommand(page, "edit_patch", () => volume.click());
await expect(volume).toBeChecked();
await reload(page);
await expect(volume).toBeChecked();
await expect(
page.getByRole("checkbox", { name: "Check the tone" }),
).not.toBeChecked();
});
test("ticking a task in a revision keeps its subject", async ({
page,
peer,
}) => {
await openTaskPatch(page, peer);
const tone = page.getByRole("checkbox", { name: "Check the tone" });
await waitForCommand(page, "edit_patch", () => tone.click());
await expect(tone).toBeChecked();
await reload(page);
await expect(tone).toBeChecked();
await expect(
page.getByRole("checkbox", { name: "Ask a reader" }),
).not.toBeChecked();
await expect(page.getByText("Quieter after all").first()).toBeVisible();
});
test("ticking a task on the changes tab is saved", async ({ page, peer }) => {
await openTaskPatch(page, peer, "?view=changes");
const reader = page.getByRole("checkbox", { name: "Ask a reader" });
await waitForCommand(page, "edit_patch", () => reader.click());
await expect(reader).toBeChecked();
await reload(page);
await expect(reader).toBeChecked();
});
test("ticking a task in your own review summary keeps the verdict", async ({
page,
peer,
}) => {
await openTaskPatch(page, peer);
const rename = page.getByRole("checkbox", { name: "Rename the file" });
await waitForCommand(page, "edit_patch", () => rename.click());
await expect(rename).toBeChecked();
await reload(page);
await expect(rename).toBeChecked();
await expect(page.getByText("Accepted").first()).toBeVisible();
});
test("a contributor can't tick tasks in someone else's patch", async ({
page,
peerManager,
}) => {
const { bob, eve } = await createCollaborators(peerManager);
const { rid, patchId } = await createTaskPatch(bob);
await clone(eve, rid);
await eve.startHttpd();
await useBackend(page, eve);
await page.goto(`/repos/${rid}/patches/${patchId}`);
await expect(
page.getByText("Lower the volume", { exact: true }),
).toBeVisible();
await expect(page.getByText("Check the tone", { exact: true })).toBeVisible();
await expect(
page.getByText("Rename the file", { exact: true }),
).toBeVisible();
await expect(page.getByRole("checkbox")).toHaveCount(0);
await goto(page, `/repos/${rid}/patches/${patchId}?view=changes`);
await expect(page.getByText("Ask a reader", { exact: true })).toBeVisible();
await expect(page.getByRole("checkbox")).toHaveCount(0);
});
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect, test } from "vitest";
import { toggleTask } from "@app/lib/markdown";
describe("toggleTask", () => {
test.each([
["ticks an open box", "- [ ] a\n- [ ] b", 0, "- [x] a\n- [ ] b"],
["clears a ticked box", "- [ ] a\n- [x] b", 1, "- [ ] a\n- [ ] b"],
["clears an upper-case box", "- [X] a", 0, "- [ ] a"],
["works on ordered lists", "1. [ ] a\n2) [ ] b", 1, "1. [ ] a\n2) [x] b"],
[
"works on nested items",
"- a\n - [ ] n\n- [x] b",
0,
"- a\n - [x] n\n- [x] b",
],
["works inside a blockquote", "> - [ ] q", 0, "> - [x] q"],
[
"keeps CRLF line endings",
"- [ ] a\r\n- [x] b\r\n",
0,
"- [x] a\r\n- [x] b\r\n",
],
[
"keeps frontmatter",
"---\nx: 1\n---\n- [ ] a",
0,
"---\nx: 1\n---\n- [x] a",
],
])("%s", (_, input, index, expected) => {
expect(toggleTask(input, index)).toBe(expected);
});
test.each([
["an HTML comment", "<!--\n- [ ] hint\n-->\n"],
["an HTML block", "<details>\n- [ ] hidden\n</details>\n\n"],
["an indented code block", "para\n\n - [ ] code\n\n"],
["a fence holding a shorter fence", "````\n```\n- [ ] c\n```\n````\n"],
["a fence inside a blockquote", "> ```\n> - [ ] c\n> ```\n\n"],
["a math block", "$$\n- [ ] x\n$$\n\n"],
["an ordered list that can't interrupt a paragraph", "para\n2. [ ] x\n\n"],
["a checkbox written as HTML", '<input type="checkbox"> hi\n\n'],
[
"a checkbox with a look-alike class",
'- foo <input class="x task-checkbox" type="checkbox">\n',
],
])("skips %s", (_, prefix) => {
expect(toggleTask(`${prefix}- [ ] real`, 0)).toBe(`${prefix}- [x] real`);
});
test("counts boxes in the order they are rendered", () => {
// Footnotes render at the end, after the list that follows them.
const doc = "t[^1]\n\n[^1]: - [ ] note\n\n- [ ] real";
expect(toggleTask(doc, 0)).toBe("t[^1]\n\n[^1]: - [ ] note\n\n- [x] real");
expect(toggleTask(doc, 1)).toBe("t[^1]\n\n[^1]: - [x] note\n\n- [ ] real");
});
test("ignores a box inside an unclosed fence", () => {
expect(toggleTask("- [ ] real\n```\n- [ ] c", 0)).toBe(
"- [x] real\n```\n- [ ] c",
);
});
test.each([
["an index past the last box", "- [ ] a", 1],
["an empty document", "", 0],
["a document without tasks", "- a\n- b", 0],
["a box with no text after it", "- [ ]", 0],
])("returns undefined for %s", (_, input, index) => {
expect(toggleTask(input, index)).toBeUndefined();
});
});
+26
View File
@@ -5,6 +5,7 @@ import { describe, expect, test } from "vitest";
import {
groupCommitsByAuthor,
isCommitListDescription,
replaceDescriptionBody,
revisionTitle,
splitDescription,
visibleCommitsOf,
@@ -36,6 +37,31 @@ describe("splitDescription", () => {
});
});
describe("replaceDescriptionBody", () => {
test.each([
["Subject\n\nold", "Subject\n\nnew"],
["Subject\nold", "Subject\nnew"],
["Subject\r\n\r\nold\r\n", "Subject\r\n\r\nnew\r\n"],
[" Subject \n\n old \n", " Subject \n\n new \n"],
])("keeps the subject and spacing of %j", (description, expected) => {
expect(replaceDescriptionBody(description, "new")).toBe(expected);
});
test("replaces the body even when the subject contains its text", () => {
expect(replaceDescriptionBody("Fix old\n\nold", "new")).toBe(
"Fix old\n\nnew",
);
});
test("adds a body to a description that has none", () => {
expect(replaceDescriptionBody("Subject", "new")).toBe("Subject\n\nnew");
});
test("leaves an empty description as just the body", () => {
expect(replaceDescriptionBody("", "new")).toBe("new");
});
});
test("revisionTitle is the first line of the current description", () => {
const edit = (body: string) => ({
author: revision().author,