Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat(web): link issue identifiers and highlight mentions of the viewer (#435)

Enrique Cardona6d71dca523f3
diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css
index 62741a63..bcc94a43 100644
--- a/apps/web/src/app/globals.css
+++ b/apps/web/src/app/globals.css
@@ -389,6 +389,48 @@
font-weight: 500;
white-space: nowrap;
}
+.md-content .mention.mention-self {
+ color: var(--foreground);
+ background: color-mix(in oklab, var(--warning) 45%, transparent);
+}
+a.issue-ref {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 0.35em;
+ max-width: 100%;
+ vertical-align: baseline;
+ color: var(--primary);
+ background: color-mix(in oklab, var(--primary) 12%, transparent);
+ border-radius: 0.375em;
+ padding: 0.05em 0.35em;
+ font-weight: 500;
+ line-height: inherit;
+ text-decoration: none;
+ white-space: nowrap;
+ cursor: pointer;
+}
+.md-content a.issue-ref {
+ text-decoration: none;
+}
+.issue-ref-dot {
+ display: inline-block;
+ width: 0.55em;
+ height: 0.55em;
+ border-radius: 9999px;
+ flex: none;
+ align-self: center;
+}
+.issue-ref-title {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 16em;
+ font-weight: 400;
+ color: var(--foreground);
+}
+.md-content .issue-ref-source {
+ font-size: 0;
+ line-height: 0;
+}
.md-content code {
background: var(--muted);
border-radius: 0.25em;
diff --git a/apps/web/src/components/common/editor/IssueRefChip.tsx b/apps/web/src/components/common/editor/IssueRefChip.tsx
new file mode 100644
index 00000000..a293a19c
--- /dev/null
+++ b/apps/web/src/components/common/editor/IssueRefChip.tsx
@@ -0,0 +1,32 @@
+import { useRef } from 'react';
+import { issuePath } from '@/utils/paths';
+import type { ResolvedLinkPreview } from './resolveLinkPreview';
+import { useLinkPreviewQuery } from './useLinkPreviewQuery';
+
+// The link an issue identifier is drawn as in read-only text: the state colour, the
+// identifier and the title, read through the same query as the hover card.
+export default function IssueRefChip({
+ projectKey,
+ sequence,
+}: {
+ projectKey: string;
+ sequence: number;
+}) {
+ const path = issuePath(projectKey, sequence);
+ const { data, isError } = useLinkPreviewQuery(new URL(path, window.location.origin).href);
+ // The query hides an internal preview while it revalidates, which the hover card
+ // starts on every open. The chip keeps what it showed until the answer is a failure.
+ const shown = useRef<ResolvedLinkPreview | undefined>(undefined);
+ if (data) shown.current = data;
+ if (isError) shown.current = undefined;
+ const preview = shown.current;
+ return (
+ <a href={path} className="issue-ref">
+ {preview?.status && (
+ <span className="issue-ref-dot" style={{ backgroundColor: preview.status.color }} />
+ )}
+ <span className="issue-ref-id">{`${projectKey}-${sequence}`}</span>
+ {preview?.issueTitle && <span className="issue-ref-title">{preview.issueTitle}</span>}
+ </a>
+ );
+}
diff --git a/apps/web/src/components/common/editor/MarkdownEditor.tsx b/apps/web/src/components/common/editor/MarkdownEditor.tsx
index fcaac450..a3a764f9 100644
--- a/apps/web/src/components/common/editor/MarkdownEditor.tsx
+++ b/apps/web/src/components/common/editor/MarkdownEditor.tsx
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
+import { useRouter } from 'next/navigation';
import { useEditor, EditorContent, type Editor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
@@ -10,6 +11,10 @@ import { Markdown } from 'tiptap-markdown';
import { pasteMarkdown } from './pasteMarkdown';
import { ResizableImage } from './tiptap-image';
import { Mention } from '@/lib/tiptap-mention';
+import { useSession } from '@/lib/auth-client';
+import { useIssueRefs } from '@/context/issueRefs';
+import { IssueRef } from './issueRefDecorations';
+import { refreshDecorations } from './refreshDecorations';
import { SlashCommand } from '@/lib/tiptap-slash-command';
import { MarkdownTable } from './tiptap-table';
import { Video } from './tiptap-video';
@@ -72,9 +77,25 @@ export default function MarkdownEditor({
const linkKeyboardHandlers = useMemo(() => createLinkKeyboardHandlers(true), []);
// Held in a ref because the extensions are built once: the "@" menu reads the
// roster through it, so a list that arrives later is still offered.
+ const router = useRouter();
+ const { data: session } = useSession();
+ const issueRefs = useIssueRefs();
const mentionCandidates = useMentionCandidates();
const mentionCandidatesRef = useRef(mentionCandidates);
mentionCandidatesRef.current = mentionCandidates;
+ const issueRefsRef = useRef(issueRefs);
+ issueRefsRef.current = issueRefs;
+ const openIssueRefRef = useRef(router.push);
+ openIssueRefRef.current = (href: string) => router.push(href);
+ const selfHandle = session?.user.username ?? '';
+ const selfHandleRef = useRef(selfHandle);
+ selfHandleRef.current = selfHandle;
+ const editableRef = useRef(editable);
+ editableRef.current = editable;
+ // False while the field can be typed into but has no focus: the chip shows, and
+ // swaps for the plain identifier only once editing actually starts.
+ const focusedRef = useRef(false);
+ const [focused, setFocused] = useState(false);
// Whether the document has changed since this editor was mounted. The markdown
// round trip is not an identity: the link extension's autolink parses a bare URL
// into a link node, which serialises back in angle brackets. A blur reporting every
@@ -115,7 +136,16 @@ export default function MarkdownEditor({
ResizableImage,
// Renders an @username in the text as a mention chip, and offers the project's
// members and agents while one is typed.
- Mention.configure({ items: () => mentionCandidatesRef.current }),
+ Mention.configure({
+ items: () => mentionCandidatesRef.current,
+ self: () => selfHandleRef.current,
+ }),
+ // Paints KEY-123 as a link without writing the link into the markdown.
+ IssueRef.configure({
+ keys: () => issueRefsRef.current.keys,
+ open: (href) => openIssueRefRef.current(href),
+ rich: () => issueRefsRef.current.resolve && (!editableRef.current || !focusedRef.current),
+ }),
// Renders video attachments as an inline <video> player.
Video,
// TableKit carries the row and cell nodes around MarkdownTable's table node.
@@ -178,7 +208,13 @@ export default function MarkdownEditor({
changedRef.current = true;
onChange?.(editor.storage.markdown.getMarkdown());
},
+ onFocus: () => {
+ focusedRef.current = true;
+ setFocused(true);
+ },
onBlur: ({ editor }) => {
+ focusedRef.current = false;
+ setFocused(false);
if (changedRef.current) onBlur?.(editor.storage.markdown.getMarkdown());
},
});
@@ -189,6 +225,13 @@ export default function MarkdownEditor({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editor]);
+ const issueRefKeyList = issueRefs.keys.join(',');
+ useEffect(() => {
+ // After the commit. The refresh mounts the chip, and doing it here calls flushSync.
+ const frame = requestAnimationFrame(() => refreshDecorations(editor));
+ return () => cancelAnimationFrame(frame);
+ }, [editor, issueRefKeyList, issueRefs.resolve, selfHandle, editable, focused]);
+
if (!editor) return null;
return (
diff --git a/apps/web/src/components/common/editor/issueRef.test.ts b/apps/web/src/components/common/editor/issueRef.test.ts
new file mode 100644
index 00000000..cb8c0435
--- /dev/null
+++ b/apps/web/src/components/common/editor/issueRef.test.ts
@@ -0,0 +1,33 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { splitIssueRefs } from './issueRef';
+
+describe('issue ref text', () => {
+ it('links only the keys it was given, longest key first', () => {
+ assert.deepEqual(splitIssueRefs('See MKT-42 and OPS-7.', ['MKT', 'OPS']), [
+ { kind: 'text', text: 'See ' },
+ { kind: 'issue', key: 'MKT', sequence: 42 },
+ { kind: 'text', text: ' and ' },
+ { kind: 'issue', key: 'OPS', sequence: 7 },
+ { kind: 'text', text: '.' },
+ ]);
+ assert.deepEqual(splitIssueRefs('AB-1 is not A-1', ['A', 'AB']), [
+ { kind: 'issue', key: 'AB', sequence: 1 },
+ { kind: 'text', text: ' is not ' },
+ { kind: 'issue', key: 'A', sequence: 1 },
+ ]);
+ });
+
+ it('leaves lowercase, other keys and joined words as text', () => {
+ for (const text of ['mkt-42', 'Mkt-42', 'UTF-8', 'MKT-42x', 'xMKT-1', 'MKT-0', 'MKT-'])
+ assert.deepEqual(splitIssueRefs(text, ['MKT']), [{ kind: 'text', text }], text);
+ assert.deepEqual(splitIssueRefs('MKT-42', []), [{ kind: 'text', text: 'MKT-42' }]);
+ });
+
+ it('follows a change of keys', () => {
+ assert.equal(splitIssueRefs('OPS-3', ['MKT']).length, 1);
+ assert.deepEqual(splitIssueRefs('OPS-3', ['MKT', 'OPS']), [
+ { kind: 'issue', key: 'OPS', sequence: 3 },
+ ]);
+ });
+});
diff --git a/apps/web/src/components/common/editor/issueRef.ts b/apps/web/src/components/common/editor/issueRef.ts
new file mode 100644
index 00000000..06b3f230
--- /dev/null
+++ b/apps/web/src/components/common/editor/issueRef.ts
@@ -0,0 +1,33 @@
+export type IssueRefPart =
+ { kind: 'text'; text: string } | { kind: 'issue'; key: string; sequence: number };
+
+let cached: { id: string; pattern: RegExp | null } | null = null;
+
+// Keys are uppercase (see utils/projectKey), so a lowercase "ops-7" stays text. Longest
+// key first, so a project AB is not read as project A in "AB-1".
+function issueRefPattern(keys: readonly string[]): RegExp | null {
+ const id = keys.join(',');
+ if (cached?.id === id) return cached.pattern;
+ const valid = [...new Set(keys.filter((key) => /^[A-Z0-9]{1,10}$/.test(key)))].sort(
+ (a, b) => b.length - a.length,
+ );
+ const pattern = valid.length
+ ? new RegExp(`(?<![A-Za-z0-9])(${valid.join('|')})-([1-9]\\d*)(?![A-Za-z0-9])`, 'g')
+ : null;
+ cached = { id, pattern };
+ return pattern;
+}
+
+export function splitIssueRefs(text: string, keys: readonly string[]): IssueRefPart[] {
+ const pattern = issueRefPattern(keys);
+ if (!pattern) return [{ kind: 'text', text }];
+ const parts: IssueRefPart[] = [];
+ let cursor = 0;
+ for (const match of text.matchAll(pattern)) {
+ if (match.index > cursor) parts.push({ kind: 'text', text: text.slice(cursor, match.index) });
+ parts.push({ kind: 'issue', key: match[1]!, sequence: Number(match[2]) });
+ cursor = match.index + match[0].length;
+ }
+ if (cursor < text.length) parts.push({ kind: 'text', text: text.slice(cursor) });
+ return parts;
+}
diff --git a/apps/web/src/components/common/editor/issueRefDecorations.test.ts b/apps/web/src/components/common/editor/issueRefDecorations.test.ts
new file mode 100644
index 00000000..87e7768a
--- /dev/null
+++ b/apps/web/src/components/common/editor/issueRefDecorations.test.ts
@@ -0,0 +1,98 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { Editor } from '@tiptap/core';
+import Link from '@tiptap/extension-link';
+import StarterKit from '@tiptap/starter-kit';
+import { Markdown } from 'tiptap-markdown';
+import { JSDOM } from 'jsdom';
+import { editorStarterKitOptions } from './MarkdownEditor';
+import { IssueRef } from './issueRefDecorations';
+import { refreshDecorations } from './refreshDecorations';
+
+let dom: JSDOM;
+let originals: Map<string, PropertyDescriptor | undefined>;
+
+beforeEach(() => {
+ dom = new JSDOM('<!doctype html><div></div>', { url: 'https://planner.test' });
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ navigator: dom.window.navigator,
+ DOMParser: dom.window.DOMParser,
+ Node: dom.window.Node,
+ NodeFilter: dom.window.NodeFilter,
+ Element: dom.window.Element,
+ HTMLElement: dom.window.HTMLElement,
+ };
+ originals = new Map(
+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
+ );
+ for (const [key, value] of Object.entries(globals))
+ Object.defineProperty(globalThis, key, { configurable: true, value });
+});
+
+afterEach(() => {
+ dom.window.close();
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+function mount(content: string, keys: () => string[], open: (href: string) => void = () => {}) {
+ return new Editor({
+ element: document.querySelector('div')!,
+ editable: false,
+ extensions: [
+ StarterKit.configure(editorStarterKitOptions),
+ Link.configure({ openOnClick: false, autolink: true }),
+ IssueRef.configure({ keys, open, rich: () => false }),
+ Markdown.configure({ html: true, linkify: true, breaks: true }),
+ ],
+ content,
+ });
+}
+
+const links = (editor: Editor) => [...editor.view.dom.querySelectorAll('a.issue-ref')];
+
+describe('issue identifiers in the editor', () => {
+ it('links an identifier without changing the stored markdown', () => {
+ const content = 'See MKT-42, mkt-7 and `MKT-9` in [MKT-3](https://example.com)';
+ const editor = mount(content, () => ['MKT']);
+ assert.deepEqual(
+ links(editor).map((link) => [link.textContent, link.getAttribute('href')]),
+ [['MKT-42', '/project/MKT/issue/42']],
+ );
+ assert.equal(editor.storage.markdown.getMarkdown(), content);
+ editor.destroy();
+ });
+
+ it('links the keys that arrive after the editor was built', () => {
+ let keys: string[] = [];
+ const editor = mount('OPS-3 and MKT-42', () => keys);
+ assert.equal(links(editor).length, 0);
+ keys = ['MKT', 'OPS'];
+ refreshDecorations(editor);
+ assert.deepEqual(
+ links(editor).map((link) => link.textContent),
+ ['OPS-3', 'MKT-42'],
+ );
+ editor.destroy();
+ });
+
+ it('opens the issue on a plain click in read-only text', () => {
+ const opened: string[] = [];
+ const editor = mount(
+ 'See MKT-42',
+ () => ['MKT'],
+ (href) => opened.push(href),
+ );
+ const event = new dom.window.MouseEvent('click', { button: 0, cancelable: true });
+ Object.defineProperty(event, 'target', { value: links(editor)[0] });
+ const handled = editor.view.someProp('handleClick', (handle) => handle(editor.view, 5, event));
+ assert.equal(handled, true);
+ assert.equal(event.defaultPrevented, true);
+ assert.deepEqual(opened, ['/project/MKT/issue/42']);
+ editor.destroy();
+ });
+});
diff --git a/apps/web/src/components/common/editor/issueRefDecorations.ts b/apps/web/src/components/common/editor/issueRefDecorations.ts
new file mode 100644
index 00000000..8e130b48
--- /dev/null
+++ b/apps/web/src/components/common/editor/issueRefDecorations.ts
@@ -0,0 +1,130 @@
+import { Extension } from '@tiptap/core';
+import { ReactRenderer, type Editor as ReactEditor } from '@tiptap/react';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import { issuePath } from '@/utils/paths';
+import { splitIssueRefs } from './issueRef';
+import { REFRESH_DECORATIONS } from './refreshDecorations';
+import IssueRefChip from './IssueRefChip';
+
+type IssueRefOptions = {
+ keys: () => readonly string[];
+ open: (href: string) => void;
+ // Read-only text shows the issue's state and title. Editable text keeps the
+ // identifier as typed, so the caret moves through characters that are all there.
+ rich: () => boolean;
+};
+
+const key = new PluginKey<DecorationSet>('issueRef');
+
+export const IssueRef = Extension.create<IssueRefOptions>({
+ name: 'issueRef',
+
+ addOptions() {
+ return { keys: () => [], open: () => undefined, rich: () => false };
+ },
+
+ addProseMirrorPlugins() {
+ const options = this.options;
+ const editor = this.editor as ReactEditor;
+ const renderers = new Map<Node, ReactRenderer>();
+
+ function build(doc: ProseMirrorNode) {
+ const keys = options.keys();
+ if (keys.length === 0) return DecorationSet.empty;
+ const rich = options.rich();
+ const decorations: Decoration[] = [];
+ doc.descendants((node, pos) => {
+ if (node.type.name === 'codeBlock') return false;
+ if (!node.isText || !node.text) return;
+ if (node.marks.some((mark) => mark.type.name === 'code' || mark.type.name === 'link'))
+ return;
+ let from = pos;
+ for (const part of splitIssueRefs(node.text, keys)) {
+ if (part.kind === 'text') {
+ from += part.text.length;
+ continue;
+ }
+ const to = from + part.key.length + 1 + String(part.sequence).length;
+ const href = issuePath(part.key, part.sequence);
+ if (rich) {
+ decorations.push(
+ Decoration.inline(from, to, { class: 'issue-ref-source', 'aria-hidden': 'true' }),
+ Decoration.widget(
+ from,
+ () => {
+ const renderer = new ReactRenderer(IssueRefChip, {
+ editor,
+ as: 'span',
+ props: { projectKey: part.key, sequence: part.sequence },
+ });
+ renderer.element.setAttribute('data-issue-ref', '');
+ renderers.set(renderer.element, renderer);
+ return renderer.element;
+ },
+ {
+ side: -1,
+ key: `issue-ref:${part.key}-${part.sequence}`,
+ ignoreSelection: true,
+ stopEvent: () => true,
+ destroy: (dom) => {
+ renderers.get(dom)?.destroy();
+ renderers.delete(dom);
+ },
+ },
+ ),
+ );
+ } else {
+ decorations.push(
+ Decoration.inline(from, to, { nodeName: 'a', class: 'issue-ref', href }),
+ );
+ }
+ from = to;
+ }
+ });
+ return DecorationSet.create(doc, decorations);
+ }
+
+ return [
+ new Plugin<DecorationSet>({
+ key,
+ state: {
+ init: (_, state) => build(state.doc),
+ apply: (tr, previous) =>
+ tr.docChanged || tr.getMeta(REFRESH_DECORATIONS)
+ ? build(tr.doc)
+ : previous.map(tr.mapping, tr.doc),
+ },
+ props: {
+ decorations: (state) => key.getState(state),
+ handleDOMEvents: {
+ // While the field is being edited a click places the caret. Before that,
+ // the same click opens the issue; preventDefault keeps the editor from
+ // taking focus and swapping the chip away under the pointer.
+ mousedown(view, event) {
+ if (view.editable && view.hasFocus()) return false;
+ if (!(event.target instanceof Element)) return false;
+ const anchor = event.target.closest('a.issue-ref');
+ if (!anchor || event.metaKey || event.ctrlKey || event.button !== 0) return false;
+ event.preventDefault();
+ const href = anchor.getAttribute('href');
+ if (href) options.open(href);
+ return true;
+ },
+ },
+ handleClick(view, _pos, event) {
+ if (event.defaultPrevented || view.editable) return false;
+ if (!(event.target instanceof Element)) return false;
+ const anchor = event.target.closest('a.issue-ref');
+ if (!anchor || event.metaKey || event.ctrlKey || event.button !== 0) return false;
+ event.preventDefault();
+ const href = anchor.getAttribute('href');
+ if (href) options.open(href);
+ return true;
+ },
+ },
+ }),
+ ];
+ },
+});
diff --git a/apps/web/src/components/common/editor/refreshDecorations.ts b/apps/web/src/components/common/editor/refreshDecorations.ts
new file mode 100644
index 00000000..28175634
--- /dev/null
+++ b/apps/web/src/components/common/editor/refreshDecorations.ts
@@ -0,0 +1,12 @@
+import type { Editor } from '@tiptap/core';
+
+// A transaction carrying this meta rebuilds the decorations that depend on something
+// outside the document: the project keys, the viewer's handle, whether it is editable.
+export const REFRESH_DECORATIONS = 'refreshDecorations';
+
+export function refreshDecorations(editor: Editor | null) {
+ if (!editor || editor.isDestroyed) return;
+ editor.view.dispatch(
+ editor.state.tr.setMeta(REFRESH_DECORATIONS, true).setMeta('addToHistory', false),
+ );
+}
diff --git a/apps/web/src/components/common/editor/resolveLinkPreview.ts b/apps/web/src/components/common/editor/resolveLinkPreview.ts
index 72cd14e9..7f616499 100644
--- a/apps/web/src/components/common/editor/resolveLinkPreview.ts
+++ b/apps/web/src/components/common/editor/resolveLinkPreview.ts
@@ -10,8 +10,11 @@ import { internalLinkTarget } from './internalLinkTarget';
import { previewExcerpt } from './previewExcerpt';
import { viewPreviewFilters, type PreviewFilter } from './viewPreviewFilters';
+type ProjectLoader = (projectKey: string, signal: AbortSignal) => ReturnType<typeof getProject>;
+
export type ResolvedLinkPreview = LinkPreview & {
kind?: 'project' | 'issue' | 'notes' | 'document' | 'view';
+ issueTitle?: string;
status?: { name: string; color: string };
updatedAt?: string;
noteCount?: number;
@@ -22,6 +25,7 @@ export type ResolvedLinkPreview = LinkPreview & {
async function resolveInternalLinkPreview(
url: URL,
signal: AbortSignal,
+ loadProject: ProjectLoader,
): Promise<ResolvedLinkPreview> {
const empty: LinkPreview = {
url: url.href,
@@ -38,18 +42,19 @@ async function resolveInternalLinkPreview(
? await getIssueBySeq(target.projectKey, target.id, signal)
: await getIssue(target.id, signal);
const projectKey = issue.identifier.replace(/-\d+$/, '');
- const project = await getProject(projectKey, signal);
+ const project = await loadProject(projectKey, signal);
return {
...empty,
kind: 'issue',
title: `${issue.identifier} · ${issue.title}`,
+ issueTitle: issue.title,
description: previewExcerpt(issue.description),
siteName: project.project.name,
status: project.columns.find((column) => column.id === issue.columnId),
updatedAt: issue.updatedAt,
};
}
- const project = await getProject(target.projectKey, signal);
+ const project = await loadProject(target.projectKey, signal);
const base = { ...empty, siteName: project.project.name };
switch (target.kind) {
case 'project':
@@ -108,10 +113,11 @@ export function resolveLinkPreview(
url: string,
origin: string,
signal: AbortSignal,
+ loadProject: ProjectLoader = getProject,
): Promise<ResolvedLinkPreview> {
const target = new URL(url, origin);
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password)
throw new ApiError(400, 'Invalid preview URL');
- if (target.origin === origin) return resolveInternalLinkPreview(target, signal);
+ if (target.origin === origin) return resolveInternalLinkPreview(target, signal, loadProject);
return getLinkPreview(target.href, signal);
}
diff --git a/apps/web/src/components/common/editor/useLinkPreviewQuery.ts b/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
index c58e3eb5..35fbdfab 100644
--- a/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
+++ b/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
@@ -1,5 +1,7 @@
-import { useQuery } from '@tanstack/react-query';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useSession } from '@/lib/auth-client';
+import { getProject } from '@/lib/api/endpoints/projects';
+import { qk } from '@/services/queryKeys';
import { resolveLinkPreview } from './resolveLinkPreview';
import { linkPreviewDestination } from './linkPreviewDestination';
@@ -24,6 +26,7 @@ async function preloadImage(src: string, signal: AbortSignal) {
}
export function useLinkPreviewQuery(url: string | undefined) {
+ const queryClient = useQueryClient();
const { data: session, isPending: sessionPending } = useSession();
const origin = typeof window === 'undefined' ? undefined : window.location.origin;
const destination = url ? linkPreviewDestination(url, origin) : null;
@@ -36,7 +39,11 @@ export function useLinkPreviewQuery(url: string | undefined) {
queryKey,
enabled,
queryFn: async ({ signal }) => {
- const preview = await resolveLinkPreview(href!, window.location.origin, signal);
+ // Through the project query, links to several issues of one project that load at
+ // the same time share one request, and each load still checks access again.
+ const preview = await resolveLinkPreview(href!, window.location.origin, signal, (key) =>
+ queryClient.fetchQuery({ queryKey: qk.project(key), queryFn: () => getProject(key) }),
+ );
if (preview.image && !signal.aborted) {
await preloadImage(preview.image, signal);
}
diff --git a/apps/web/src/components/layout/Shell.tsx b/apps/web/src/components/layout/Shell.tsx
index eb5144b9..096925d4 100644
--- a/apps/web/src/components/layout/Shell.tsx
+++ b/apps/web/src/components/layout/Shell.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useState, type ReactNode } from 'react';
+import { useMemo, useState, type ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import { useInitiativeOptionsQuery } from '@/services/initiatives.service';
import { useIssueBySeqQuery } from '@/services/issues.service';
@@ -15,6 +15,7 @@ import { useShellRoute } from '@/hooks/useShellRoute';
import { useProjectRouteSync } from '@/hooks/useProjectRouteSync';
import { projectPath, issuePath } from '@/utils/paths';
import { defaultsFromFilters, type NewIssueDefaults } from '@/utils/project';
+import { IssueRefsProvider } from '@/context/issueRefs';
import { ShellCtx, type ShellContext } from '@/context/shellContext';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import AppSidebar from '@/components/layout/AppSidebar';
@@ -55,6 +56,7 @@ export default function Shell({
errorMsg,
forbidden,
} = useShellProject(projectKey, route.activeViewId);
+ const issueRefKeys = useMemo(() => projects.map((item) => item.key), [projects]);
const initiativeOptions = useInitiativeOptionsQuery(projectKey).data ?? [];
const { issueOpenMode, showChatByDefault } = useAccountPreferences();
@@ -185,7 +187,7 @@ export default function Shell({
projectsLoaded={projectsLoaded}
projectCount={projects.length}
>
- {children}
+ <IssueRefsProvider keys={issueRefKeys}>{children}</IssueRefsProvider>
</ShellBody>
</div>
@@ -226,7 +228,9 @@ export default function Shell({
onToggleChat={chatPanel.toggle}
/>
- <ShellOverlays project={project} projectKey={projectKey} overlays={overlays} />
+ <IssueRefsProvider keys={issueRefKeys}>
+ <ShellOverlays project={project} projectKey={projectKey} overlays={overlays} />
+ </IssueRefsProvider>
</SidebarProvider>
</ShellCtx.Provider>
);
diff --git a/apps/web/src/context/issueRefs.tsx b/apps/web/src/context/issueRefs.tsx
new file mode 100644
index 00000000..a7bb776d
--- /dev/null
+++ b/apps/web/src/context/issueRefs.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { createContext, useContext, type ReactNode } from 'react';
+
+// The project keys an issue identifier is linked for, and whether the link may read
+// the issue it names to show its state and title.
+type IssueRefs = { keys: readonly string[]; resolve: boolean };
+
+const IssueRefsContext = createContext<IssueRefs>({ keys: [], resolve: false });
+
+export function IssueRefsProvider({
+ keys,
+ resolve = true,
+ children,
+}: {
+ keys: readonly string[];
+ resolve?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <IssueRefsContext.Provider value={{ keys, resolve }}>{children}</IssueRefsContext.Provider>
+ );
+}
+
+export function useIssueRefs() {
+ return useContext(IssueRefsContext);
+}
diff --git a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
index 6e4d0394..bf590983 100644
--- a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
+++ b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
@@ -1,6 +1,7 @@
'use client';
-import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useRouter } from 'next/navigation';
import type { JSONContent } from '@tiptap/core';
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
import Color from '@tiptap/extension-color';
@@ -20,6 +21,9 @@ import { Markdown } from 'tiptap-markdown';
import EditorSelectionMenu from '@/components/common/editor/EditorSelectionMenu';
import EditorTableMenu from '@/components/common/editor/EditorTableMenu';
import EditorLinkPreview from '@/components/common/editor/EditorLinkPreview';
+import { IssueRef } from '@/components/common/editor/issueRefDecorations';
+import { refreshDecorations } from '@/components/common/editor/refreshDecorations';
+import { useIssueRefs } from '@/context/issueRefs';
import { createLinkKeyboardHandlers } from '@/components/common/editor/linkKeyboardHandlers';
import { openLinkOnModifierClick } from '@/components/common/editor/modifierClickLink';
import { ResizableImage } from '@/components/common/editor/tiptap-image';
@@ -148,10 +152,20 @@ export default function DocumentMarkdownEditor({
onUploadImage?: (file: File) => Promise<{ url: string; filename: string }>;
}) {
const t = useTranslations('documents.toolbar');
+ const router = useRouter();
+ const issueRefs = useIssueRefs();
const editorRef = useRef<Editor | null>(null);
const linkKeyboardHandlers = useMemo(createLinkKeyboardHandlers, []);
const editableRef = useRef(editable);
editableRef.current = editable;
+ // False while the document can be typed into but has no focus: the chip shows,
+ // and swaps for the plain identifier only once editing actually starts.
+ const focusedRef = useRef(false);
+ const [focused, setFocused] = useState(false);
+ const issueRefsRef = useRef(issueRefs);
+ issueRefsRef.current = issueRefs;
+ const openIssueRefRef = useRef(router.push);
+ openIssueRefRef.current = (href: string) => router.push(href);
const editor = useEditor({
editable,
@@ -176,7 +190,13 @@ export default function DocumentMarkdownEditor({
divider: t('divider'),
},
image: onPickImage ? { label: t('uploadImage'), onPick: onPickImage } : undefined,
- }),
+ }).concat(
+ IssueRef.configure({
+ keys: () => issueRefsRef.current.keys,
+ open: (href) => openIssueRefRef.current(href),
+ rich: () => issueRefsRef.current.resolve && (!editableRef.current || !focusedRef.current),
+ }),
+ ),
content: defaultJson ?? defaultValue,
editorProps: {
handleDOMEvents: linkKeyboardHandlers,
@@ -226,7 +246,15 @@ export default function DocumentMarkdownEditor({
onUpdate: ({ editor: currentEditor }) => {
if (!collaborative) onChange(editorValue(currentEditor));
},
- onBlur: ({ editor: currentEditor }) => onBlur(editorValue(currentEditor)),
+ onFocus: () => {
+ focusedRef.current = true;
+ setFocused(true);
+ },
+ onBlur: ({ editor: currentEditor }) => {
+ focusedRef.current = false;
+ setFocused(false);
+ onBlur(editorValue(currentEditor));
+ },
onDestroy: () => {
editorRef.current = null;
},
@@ -240,6 +268,12 @@ export default function DocumentMarkdownEditor({
return () => onReady(null);
}, [editor, onReady]);
+ const issueRefKeyList = issueRefs.keys.join(',');
+ useEffect(() => {
+ const frame = requestAnimationFrame(() => refreshDecorations(editor));
+ return () => cancelAnimationFrame(frame);
+ }, [editor, issueRefKeyList, issueRefs.resolve, editable, focused]);
+
useLayoutEffect(() => {
syncDocumentEditorEditable(editor, editable);
}, [editable, editor]);
diff --git a/apps/web/src/features/issue/components/detail/CommentItem.tsx b/apps/web/src/features/issue/components/detail/CommentItem.tsx
index c974a984..3b398dde 100644
--- a/apps/web/src/features/issue/components/detail/CommentItem.tsx
+++ b/apps/web/src/features/issue/components/detail/CommentItem.tsx
@@ -101,7 +101,7 @@ export default function CommentItem({
</div>
) : (
<MarkdownEditor
- className="mt-1 ps-7 text-sm text-foreground/85"
+ className="mt-1 ps-7 text-sm text-foreground/85 [&_a.issue-ref]:mx-1 [&_a.issue-ref]:text-[0.9em]"
defaultValue={item.body ?? ''}
editable={false}
/>
diff --git a/apps/web/src/features/issue/components/detail/ReadOnlyIssueDetail.tsx b/apps/web/src/features/issue/components/detail/ReadOnlyIssueDetail.tsx
index a804679e..9bbef545 100644
--- a/apps/web/src/features/issue/components/detail/ReadOnlyIssueDetail.tsx
+++ b/apps/web/src/features/issue/components/detail/ReadOnlyIssueDetail.tsx
@@ -3,6 +3,7 @@ import { toPublicProjectDetail } from '@/utils/publicProject';
import { usePersistedOpen, usePersistedOpenGroups } from '../../hooks/usePersistedOpen';
import { fieldDefsForType } from '../../utils/fieldDefs';
import MarkdownEditor from '@/components/common/editor/MarkdownEditor';
+import { IssueRefsProvider } from '@/context/issueRefs';
import IssueCustomFieldBody from '../fields/IssueCustomFieldBody';
import IssueProperties from './IssueProperties';
import IssueSubtasksPanel from './IssueSubtasksPanel';
@@ -55,8 +56,13 @@ export default function ReadOnlyIssueDetail({
</div>
<h1 className="mt-1 text-lg font-semibold">{issue.title}</h1>
+ {/* A share is read without a session, so an identifier links without reading the
+ issue it names: the api answers that read with 401, and lib/api treats every
+ 401 as an ended session and sends the reader to the sign-in screen. */}
{issue.description.trim() && (
- <MarkdownEditor className="mt-4" defaultValue={issue.description} editable={false} />
+ <IssueRefsProvider keys={[scaffold.project.key]} resolve={false}>
+ <MarkdownEditor className="mt-4" defaultValue={issue.description} editable={false} />
+ </IssueRefsProvider>
)}
{fieldDefs
diff --git a/apps/web/src/lib/tiptap-mention.test.ts b/apps/web/src/lib/tiptap-mention.test.ts
new file mode 100644
index 00000000..3002a32e
--- /dev/null
+++ b/apps/web/src/lib/tiptap-mention.test.ts
@@ -0,0 +1,63 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { Editor } from '@tiptap/core';
+import StarterKit from '@tiptap/starter-kit';
+import { Markdown } from 'tiptap-markdown';
+import { JSDOM } from 'jsdom';
+import { refreshDecorations } from '@/components/common/editor/refreshDecorations';
+import { Mention } from './tiptap-mention';
+
+let dom: JSDOM;
+let originals: Map<string, PropertyDescriptor | undefined>;
+
+beforeEach(() => {
+ dom = new JSDOM('<!doctype html><div></div>', { url: 'https://planner.test' });
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ navigator: dom.window.navigator,
+ DOMParser: dom.window.DOMParser,
+ Node: dom.window.Node,
+ NodeFilter: dom.window.NodeFilter,
+ Element: dom.window.Element,
+ HTMLElement: dom.window.HTMLElement,
+ };
+ originals = new Map(
+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
+ );
+ for (const [key, value] of Object.entries(globals))
+ Object.defineProperty(globalThis, key, { configurable: true, value });
+});
+
+afterEach(() => {
+ dom.window.close();
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+describe('mentions of the viewer', () => {
+ it('marks only the viewer, including once the session arrives', () => {
+ let self = '';
+ const editor = new Editor({
+ element: document.querySelector('div')!,
+ editable: false,
+ extensions: [
+ StarterKit.configure({ link: false }),
+ Mention.configure({ items: () => [], self: () => self }),
+ Markdown.configure({ html: true, linkify: true, breaks: true }),
+ ],
+ content: 'Hi @Ana, see @bob',
+ });
+ const marked = () =>
+ [...editor.view.dom.querySelectorAll('.mention-self')].map((node) => node.textContent);
+ assert.equal(editor.view.dom.querySelectorAll('.mention').length, 2);
+ assert.deepEqual(marked(), []);
+ self = 'ana';
+ refreshDecorations(editor);
+ assert.deepEqual(marked(), ['@Ana']);
+ assert.equal(editor.storage.markdown.getMarkdown(), 'Hi @Ana, see @bob');
+ editor.destroy();
+ });
+});
diff --git a/apps/web/src/lib/tiptap-mention.ts b/apps/web/src/lib/tiptap-mention.ts
index 3157e3f0..0fc64bee 100644
--- a/apps/web/src/lib/tiptap-mention.ts
+++ b/apps/web/src/lib/tiptap-mention.ts
@@ -1,6 +1,9 @@
import { Node, mergeAttributes } from '@tiptap/core';
-import { PluginKey } from '@tiptap/pm/state';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { ReactRenderer } from '@tiptap/react';
+import { REFRESH_DECORATIONS } from '@/components/common/editor/refreshDecorations';
import Suggestion from '@tiptap/suggestion';
import EditorMentionMenu, {
type MentionMenuRef,
@@ -18,11 +21,27 @@ export type MentionOptions = {
// Read on every keystroke rather than captured once, so a roster that arrives
// after the editor was built is still offered.
items: () => MentionCandidate[];
+ // The viewer's own handle. A mention of it is painted in a second colour.
+ self: () => string;
};
// Its own key, so this suggestion plugin and the slash command's can both run in
// one editor — two plugins under the default key are rejected by ProseMirror.
const mentionPluginKey = new PluginKey('mentionSuggestion');
+const selfMentionKey = new PluginKey<DecorationSet>('selfMention');
+
+// A decoration rather than a class set in renderHTML: the session can arrive after the
+// nodes are drawn, and a decoration is recomputed on refresh where a node is not.
+function selfMentions(doc: ProseMirrorNode, self: string): DecorationSet {
+ if (!self) return DecorationSet.empty;
+ const handle = self.toLowerCase();
+ const decorations: Decoration[] = [];
+ doc.descendants((node, pos) => {
+ if (node.type.name === 'mention' && String(node.attrs.username).toLowerCase() === handle)
+ decorations.push(Decoration.node(pos, pos + node.nodeSize, { class: 'mention-self' }));
+ });
+ return DecorationSet.create(doc, decorations);
+}
// A mention in the text is @handle — a member's username, or an agent's. Handles
// hold letters, digits and . _ - and never end on . or -, so a mention that closes a
@@ -76,7 +95,7 @@ export const Mention = Node.create<MentionOptions>({
selectable: false,
addOptions() {
- return { items: () => [] };
+ return { items: () => [], self: () => '' };
},
addAttributes() {
@@ -126,8 +145,19 @@ export const Mention = Node.create<MentionOptions>({
},
addProseMirrorPlugins() {
- const { items } = this.options;
+ const { items, self } = this.options;
return [
+ new Plugin<DecorationSet>({
+ key: selfMentionKey,
+ state: {
+ init: (_, state) => selfMentions(state.doc, self()),
+ apply: (tr, previous) =>
+ tr.docChanged || tr.getMeta(REFRESH_DECORATIONS)
+ ? selfMentions(tr.doc, self())
+ : previous.map(tr.mapping, tr.doc),
+ },
+ props: { decorations: (state) => selfMentionKey.getState(state) },
+ }),
Suggestion<MentionCandidate, MentionCandidate>({
pluginKey: mentionPluginKey,
editor: this.editor,