Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions apps/web/src/components/page-editor/MentionMenu.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Avatar } from '../ui';
import { getImageUrl } from '../../lib/utils';
import { useActiveItemScroll, type SuggestionMenuProps } from './suggestionPopup';
import type { MentionItem } from './mentionTypes';

export function MentionMenu({ items, selectedIndex, onSelect }: SuggestionMenuProps<MentionItem>) {
const listRef = useActiveItemScroll(selectedIndex);
if (items.length === 0) {
return (
<div className="w-60 rounded-md border border-(--border-subtle) bg-(--bg-surface-1) px-3 py-2 text-sm text-(--txt-tertiary) shadow-(--shadow-overlay)">
No members found
</div>
);
}
return (
<div
ref={listRef}
className="max-h-72 w-60 overflow-y-auto rounded-md border border-(--border-subtle) bg-(--bg-surface-1) py-1 shadow-(--shadow-overlay)"
>
{items.map((item, i) => (
<button
key={item.id}
type="button"
onMouseDown={(e) => {
e.preventDefault();
onSelect(i);
}}
className={
'flex w-full items-center gap-2 px-2 py-1.5 text-left text-sm text-(--txt-primary) ' +
(i === selectedIndex ? 'bg-(--bg-layer-1-hover)' : 'hover:bg-(--bg-layer-1-hover)')
}
>
<Avatar name={item.label} src={getImageUrl(item.avatarUrl) ?? undefined} size="sm" />
<span className="truncate">{item.label}</span>
</button>
))}
</div>
);
}
1 change: 1 addition & 0 deletions apps/web/src/components/page-editor/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { usePageEditor, type UsePageEditorOptions } from './usePageEditor';
export { type MentionItem } from './mentionTypes';
export { PageEditorToolbar } from './PageEditorToolbar';
export { PageEditorContent } from './PageEditorContent';
export { PageOutline } from './PageOutline';
Expand Down
5 changes: 5 additions & 0 deletions apps/web/src/components/page-editor/mentionTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface MentionItem {
id: string;
label: string;
avatarUrl?: string | null;
}
25 changes: 25 additions & 0 deletions apps/web/src/components/page-editor/mentions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Mention from '@tiptap/extension-mention';
import { createSuggestionRenderer } from './suggestionPopup';
import { MentionMenu } from './MentionMenu';
import type { MentionItem } from './mentionTypes';

/**
* @mention of workspace members. `getItems` is read at suggestion time so the
* editor picks up members loaded after it mounts.
*/
export const createMention = (getItems: () => MentionItem[]) =>
Mention.configure({
HTMLAttributes: { class: 'page-mention' },
suggestion: {
char: '@',
// Keep filtering across spaces so multi-word names like "John Doe" match.
allowSpaces: true,
items: ({ query }) => {
const q = query.trim().toLowerCase();
const list = getItems();
const matched = q ? list.filter((i) => i.label.toLowerCase().includes(q)) : list;
return matched.slice(0, 8);
},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
render: createSuggestionRenderer(MentionMenu),
},
});
206 changes: 206 additions & 0 deletions apps/web/src/components/page-editor/slashCommands.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { Extension, type Range } from '@tiptap/core';
import Suggestion from '@tiptap/suggestion';
import type { Editor } from '@tiptap/react';
import {
Code2,
Heading1,
Heading2,
Heading3,
Image as ImageIcon,
List,
ListOrdered,
ListTodo,
Minus,
Table as TableIcon,
TextQuote,
Type,
type LucideIcon,
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { safeUrl } from '../../lib/sanitize';
import {
createSuggestionRenderer,
useActiveItemScroll,
type SuggestionMenuProps,
} from './suggestionPopup';

interface SlashItem {
title: string;
subtitle: string;
icon: LucideIcon;
keywords: string[];
run: (editor: Editor, range: Range) => void;
}

const ITEMS: SlashItem[] = [
{
title: 'Text',
subtitle: 'Plain paragraph',
icon: Type,
keywords: ['paragraph', 'body'],
run: (editor, range) => editor.chain().focus().deleteRange(range).setParagraph().run(),
},
{
title: 'Heading 1',
subtitle: 'Large section heading',
icon: Heading1,
keywords: ['h1', 'title'],
run: (editor, range) =>
editor.chain().focus().deleteRange(range).setNode('heading', { level: 1 }).run(),
},
{
title: 'Heading 2',
subtitle: 'Medium section heading',
icon: Heading2,
keywords: ['h2', 'subtitle'],
run: (editor, range) =>
editor.chain().focus().deleteRange(range).setNode('heading', { level: 2 }).run(),
},
{
title: 'Heading 3',
subtitle: 'Small section heading',
icon: Heading3,
keywords: ['h3'],
run: (editor, range) =>
editor.chain().focus().deleteRange(range).setNode('heading', { level: 3 }).run(),
},
{
title: 'Bulleted list',
subtitle: 'Unordered list',
icon: List,
keywords: ['ul', 'unordered', 'bullet'],
run: (editor, range) => editor.chain().focus().deleteRange(range).toggleBulletList().run(),
},
{
title: 'Numbered list',
subtitle: 'Ordered list',
icon: ListOrdered,
keywords: ['ol', 'ordered', 'number'],
run: (editor, range) => editor.chain().focus().deleteRange(range).toggleOrderedList().run(),
},
{
title: 'To-do list',
subtitle: 'Checklist',
icon: ListTodo,
keywords: ['task', 'checkbox', 'todo'],
run: (editor, range) => editor.chain().focus().deleteRange(range).toggleTaskList().run(),
},
{
title: 'Quote',
subtitle: 'Block quote',
icon: TextQuote,
keywords: ['blockquote', 'citation'],
run: (editor, range) => editor.chain().focus().deleteRange(range).toggleBlockquote().run(),
},
{
title: 'Code block',
subtitle: 'Formatted code',
icon: Code2,
keywords: ['pre', 'snippet'],
run: (editor, range) => editor.chain().focus().deleteRange(range).toggleCodeBlock().run(),
},
{
title: 'Table',
subtitle: '3x3 table',
icon: TableIcon,
keywords: ['grid'],
run: (editor, range) =>
editor
.chain()
.focus()
.deleteRange(range)
.insertTable({ rows: 3, cols: 3, withHeaderRow: true })
.run(),
},
{
title: 'Image',
subtitle: 'Embed by URL',
icon: ImageIcon,
keywords: ['picture', 'photo', 'embed'],
run: (editor, range) => {
const input = window.prompt('Image URL')?.trim();
const chain = editor.chain().focus().deleteRange(range);
// Only allow http(s) or site-relative URLs so an image can't smuggle a
// javascript: / data: payload into an <img src>.
const src = input ? safeUrl(input) : '#';
if (input && src !== '#' && !src.startsWith('mailto:')) chain.setImage({ src }).run();
else chain.run();
},
},
{
title: 'Divider',
subtitle: 'Horizontal rule',
icon: Minus,
keywords: ['hr', 'separator', 'line'],
run: (editor, range) => editor.chain().focus().deleteRange(range).setHorizontalRule().run(),
},
];

function filterItems(query: string): SlashItem[] {
const q = query.trim().toLowerCase();
if (!q) return ITEMS;
return ITEMS.filter(
(i) => i.title.toLowerCase().includes(q) || i.keywords.some((k) => k.includes(q)),
);
}

function SlashMenu({ items, selectedIndex, onSelect }: SuggestionMenuProps<SlashItem>) {
const listRef = useActiveItemScroll(selectedIndex);
if (items.length === 0) {
return (
<div className="w-64 rounded-md border border-(--border-subtle) bg-(--bg-surface-1) px-3 py-2 text-sm text-(--txt-tertiary) shadow-(--shadow-overlay)">
No matching blocks
</div>
);
}
return (
<div
ref={listRef}
className="max-h-72 w-64 overflow-y-auto rounded-md border border-(--border-subtle) bg-(--bg-surface-1) py-1 shadow-(--shadow-overlay)"
>
{items.map((item, i) => (
<button
key={item.title}
type="button"
onMouseDown={(e) => {
e.preventDefault();
onSelect(i);
}}
className={cn(
'flex w-full items-center gap-2 px-2 py-1.5 text-left',
i === selectedIndex ? 'bg-(--bg-layer-1-hover)' : 'hover:bg-(--bg-layer-1-hover)',
)}
>
<span className="grid size-7 shrink-0 place-items-center rounded border border-(--border-subtle) text-(--txt-secondary)">
<item.icon size={15} />
</span>
<span className="min-w-0">
<span className="block truncate text-sm text-(--txt-primary)">{item.title}</span>
<span className="block truncate text-xs text-(--txt-tertiary)">{item.subtitle}</span>
</span>
</button>
))}
</div>
);
}
Comment thread
martian56 marked this conversation as resolved.

/**
* Slash-command menu: type "/" to insert headings, lists, quotes, code, tables,
* images, and dividers.
*/
export const SlashCommand = Extension.create({
name: 'slashCommand',
addProseMirrorPlugins() {
return [
Suggestion<SlashItem>({
editor: this.editor,
char: '/',
allowSpaces: false,
startOfLine: false,
items: ({ query }) => filterItems(query),
command: ({ editor, range, props }) => props.run(editor, range),
render: createSuggestionRenderer(SlashMenu),
}),
];
},
});
109 changes: 109 additions & 0 deletions apps/web/src/components/page-editor/suggestionPopup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { ReactRenderer } from '@tiptap/react';
import type { SuggestionOptions, SuggestionProps } from '@tiptap/suggestion';
import { useLayoutEffect, useRef, type ComponentType } from 'react';

export interface SuggestionMenuProps<T> {
items: T[];
selectedIndex: number;
onSelect: (index: number) => void;
}

/**
* Ref for a menu list container that scrolls its active child into view as the
* keyboard selection moves, so arrowing past the visible area follows along.
*/
export function useActiveItemScroll(selectedIndex: number) {
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const active = ref.current?.children[selectedIndex] as HTMLElement | undefined;
active?.scrollIntoView({ block: 'nearest' });
}, [selectedIndex]);
return ref;
}

/**
* Builds a TipTap suggestion `render` that shows `Menu` in a body-level popup
* positioned under the caret, with arrow-key navigation and Enter to pick. All
* mutable state lives in the returned closure so the menu component stays pure.
*/
export function createSuggestionRenderer<T>(
Menu: ComponentType<SuggestionMenuProps<T>>,
): NonNullable<SuggestionOptions<T>['render']> {
return () => {
let renderer: ReactRenderer | null = null;
let popup: HTMLDivElement | null = null;
let items: T[] = [];
let selectedIndex = 0;
let choose: (item: T) => void = () => {};
let getRect: (() => DOMRect | null) | null | undefined;

const paint = () => {
renderer?.updateProps({ items, selectedIndex, onSelect: (i: number) => choose(items[i]) });
};
const place = (rect?: DOMRect | null) => {
if (!popup || !rect) return;
popup.style.top = `${rect.bottom + window.scrollY + 4}px`;
popup.style.left = `${rect.left + window.scrollX}px`;
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
// Keep the popup pinned to the caret if the page scrolls or resizes while it
// is open. Capture-phase catches scrolling inside the editor's scroll area.
const reposition = () => place(getRect?.());

return {
onStart: (props: SuggestionProps<T>) => {
items = props.items;
selectedIndex = 0;
choose = (item) => props.command(item);
getRect = props.clientRect;
renderer = new ReactRenderer(Menu, {
props: { items, selectedIndex, onSelect: (i: number) => choose(items[i]) },
editor: props.editor,
});
popup = document.createElement('div');
popup.style.position = 'absolute';
popup.style.zIndex = '10200';
popup.appendChild(renderer.element);
document.body.appendChild(popup);
place(getRect?.());
window.addEventListener('scroll', reposition, true);
window.addEventListener('resize', reposition);
},
onUpdate: (props: SuggestionProps<T>) => {
items = props.items;
selectedIndex = 0;
choose = (item) => props.command(item);
getRect = props.clientRect;
paint();
place(getRect?.());
},
onKeyDown: (props: { event: KeyboardEvent }) => {
if (props.event.key === 'Escape') return false;
if (items.length === 0) return false;
if (props.event.key === 'ArrowUp') {
selectedIndex = (selectedIndex + items.length - 1) % items.length;
paint();
return true;
}
if (props.event.key === 'ArrowDown') {
selectedIndex = (selectedIndex + 1) % items.length;
paint();
return true;
}
if (props.event.key === 'Enter') {
choose(items[selectedIndex]);
return true;
}
return false;
},
onExit: () => {
window.removeEventListener('scroll', reposition, true);
window.removeEventListener('resize', reposition);
popup?.remove();
renderer?.destroy();
popup = null;
renderer = null;
getRect = null;
},
};
};
}
Loading
Loading