File size: 11,257 Bytes
561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 76fc93a 8fc8501 76fc93a 8fc8501 76fc93a 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 8fc8501 561e6f0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | import { ReactRenderer } from "@tiptap/react";
import tippy, { type Instance as TippyInstance } from "tippy.js";
import { type SuggestionProps, type SuggestionKeyDownProps } from "@tiptap/suggestion";
import {
forwardRef,
useEffect,
useImperativeHandle,
useMemo,
useState,
useCallback,
} from "react";
import type { Editor } from "@tiptap/core";
import { getComponentSlashItems } from "./components";
type SlashSection =
| "Insert"
| "Text"
| "Academic"
| "Media"
| "Layout"
| "Advanced";
interface SlashItem {
title: string;
description: string;
icon: string;
section: SlashSection;
command: (editor: Editor) => void;
}
const BUILT_IN_ITEMS: SlashItem[] = [
{
title: "Heading 1",
description: "Large section heading",
icon: "H1",
section: "Text",
command: (editor) =>
editor.chain().focus().toggleHeading({ level: 1 }).run(),
},
{
title: "Heading 2",
description: "Medium section heading",
icon: "H2",
section: "Text",
command: (editor) =>
editor.chain().focus().toggleHeading({ level: 2 }).run(),
},
{
title: "Heading 3",
description: "Small section heading",
icon: "H3",
section: "Text",
command: (editor) =>
editor.chain().focus().toggleHeading({ level: 3 }).run(),
},
{
title: "Bullet list",
description: "Unordered list",
icon: "•",
section: "Text",
command: (editor) => editor.chain().focus().toggleBulletList().run(),
},
{
title: "Numbered list",
description: "Ordered list",
icon: "1.",
section: "Text",
command: (editor) => editor.chain().focus().toggleOrderedList().run(),
},
{
title: "Quote",
description: "Blockquote",
icon: "❝",
section: "Text",
command: (editor) => editor.chain().focus().toggleBlockquote().run(),
},
{
title: "Code block",
description: "Code with syntax highlighting",
icon: "<>",
section: "Text",
command: (editor) => editor.chain().focus().toggleCodeBlock().run(),
},
{
title: "Divider",
description: "Horizontal rule",
icon: "—",
section: "Text",
command: (editor) => editor.chain().focus().setHorizontalRule().run(),
},
{
title: "Image",
description: "Upload or embed an image",
icon: "🖼",
section: "Insert",
command: (editor) => {
editor.chain().focus().insertImageUpload().run();
},
},
{
title: "Citation",
description: "Cite a paper (DOI or BibTeX)",
icon: "📎",
section: "Academic",
command: () => {
window.dispatchEvent(new CustomEvent("open-citation-panel"));
},
},
{
title: "Glossary",
description: "Highlighted term with tooltip definition",
icon: "📖",
section: "Academic",
command: (editor) => {
editor.chain().focus().insertGlossary("term", "Definition here…").run();
},
},
{
title: "Footnote",
description: "Numbered footnote reference",
icon: "¹",
section: "Academic",
command: (editor) => {
editor.chain().focus().insertFootnote("Footnote content…").run();
},
},
{
title: "Stack",
description: "Multi-column layout (2-4 columns)",
icon: "▥",
section: "Layout",
command: (editor) => {
editor.chain().focus().insertStack(2).run();
},
},
{
title: "New Chart",
description: "Create a D3 chart with AI (Embed Studio)",
icon: "📊",
section: "Insert",
command: (editor) => {
const id = `d3-chart-${Date.now().toString(36)}`;
const src = `${id}.html`;
(editor.chain().focus() as any).insertHtmlEmbed().run();
setTimeout(() => {
const { doc } = editor.state;
let targetPos = -1;
doc.descendants((node, pos) => {
if (node.type.name === "htmlEmbed" && !node.attrs.src) {
targetPos = pos;
return false;
}
});
if (targetPos >= 0) {
editor.view.dispatch(
editor.state.tr.setNodeMarkup(targetPos, undefined, {
...editor.state.doc.nodeAt(targetPos)?.attrs,
src,
title: "New chart",
}),
);
}
window.dispatchEvent(
new CustomEvent("open-embed-studio", { detail: { src } }),
);
}, 50);
},
},
];
/**
* Component-driven slash items (Accordion, Note, HtmlEmbed, ...) come
* from the shared component registry. We map each tag to its slash
* section here so the menu stays categorized when new components are
* added.
*/
const COMPONENT_SECTION_MAP: Record<string, SlashSection> = {
Accordion: "Layout",
Note: "Academic",
Quote: "Text",
Wide: "Layout",
FullWidth: "Layout",
Sidenote: "Academic",
Reference: "Media",
HtmlEmbed: "Media",
HfUser: "Media",
RawHtml: "Advanced",
Mermaid: "Media",
};
function inferSection(title: string): SlashSection {
// Component slash items don't carry the original tag; match by label.
const byLabel: Record<string, SlashSection> = {
Accordion: "Layout",
"Note / Callout": "Academic",
"Quote block": "Text",
Wide: "Layout",
"Full width": "Layout",
Sidenote: "Academic",
"Reference / Figure": "Media",
"HTML Embed": "Media",
"HF User card": "Media",
"Raw HTML": "Advanced",
"Mermaid diagram": "Media",
};
return byLabel[title] ?? "Layout";
}
function withInferredSection(
items: Array<Omit<SlashItem, "section"> & { section?: SlashSection }>,
): SlashItem[] {
return items.map((item) => ({
...item,
section: item.section ?? inferSection(item.title),
}));
}
const ITEMS: SlashItem[] = [
...BUILT_IN_ITEMS,
...withInferredSection(getComponentSlashItems()),
];
// Display order of section groups in the menu. "Insert" is a tiny
// featured section at the very top holding the two flagship heavy
// inserts (New Chart, Image) - this editor's signature features.
// Text blocks follow because they're 80% of real usage.
const SECTION_ORDER: SlashSection[] = [
"Insert",
"Text",
"Media",
"Academic",
"Layout",
"Advanced",
];
// Used to re-export so we can also feed the section map to anyone who
// wants it (e.g. the TopBar "more" menu could list categories).
export { SECTION_ORDER, COMPONENT_SECTION_MAP };
interface SlashGroup {
section: SlashSection;
items: SlashItem[];
}
function groupItems(items: SlashItem[]): SlashGroup[] {
const map = new Map<SlashSection, SlashItem[]>();
for (const item of items) {
const list = map.get(item.section) ?? [];
list.push(item);
map.set(item.section, list);
}
return SECTION_ORDER.filter((s) => map.has(s)).map((section) => ({
section,
items: map.get(section)!,
}));
}
interface SlashMenuListProps {
items: SlashItem[];
command: (item: SlashItem) => void;
}
interface SlashMenuListRef {
onKeyDown: (props: SuggestionKeyDownProps) => boolean;
}
const SlashMenuList = forwardRef<SlashMenuListRef, SlashMenuListProps>(
({ items, command }, ref) => {
const [selectedIndex, setSelectedIndex] = useState(0);
// We render items in section groups. Keyboard navigation still
// operates on the flat `items` array (not on section headers),
// so ArrowDown moves between actual items regardless of their
// section.
const groups = useMemo(() => groupItems(items), [items]);
useEffect(() => {
setSelectedIndex(0);
}, [items]);
const selectItem = useCallback(
(index: number) => {
const item = items[index];
if (item) command(item);
},
[items, command],
);
useImperativeHandle(ref, () => ({
onKeyDown: ({ event }: SuggestionKeyDownProps) => {
if (event.key === "ArrowUp") {
setSelectedIndex((i) => (i + items.length - 1) % items.length);
return true;
}
if (event.key === "ArrowDown") {
setSelectedIndex((i) => (i + 1) % items.length);
return true;
}
if (event.key === "Enter") {
selectItem(selectedIndex);
return true;
}
return false;
},
}));
if (items.length === 0) return null;
return (
<div className="slash-menu">
{groups.map((group) => (
<div key={group.section} className="slash-menu-group">
<div className="slash-menu-section" aria-hidden="true">
{group.section}
</div>
{group.items.map((item) => {
// Map back to the flat index so keyboard state and
// click highlight stay in sync.
const flatIndex = items.indexOf(item);
return (
<button
key={`${group.section}:${item.title}`}
className={`slash-menu-item ${flatIndex === selectedIndex ? "is-selected" : ""}`}
onClick={() => selectItem(flatIndex)}
onMouseEnter={() => setSelectedIndex(flatIndex)}
>
<span className="slash-menu-item-icon">{item.icon}</span>
<span className="slash-menu-item-content">
<span className="slash-menu-item-title">{item.title}</span>
<span className="slash-menu-item-desc">{item.description}</span>
</span>
</button>
);
})}
</div>
))}
</div>
);
},
);
SlashMenuList.displayName = "SlashMenuList";
export function slashMenuSuggestion() {
return {
items: ({ query }: { query: string }) => {
const q = query.toLowerCase();
if (!q) return ITEMS;
// Match on title OR description so typing "image" surfaces
// both "Image" and "HTML Embed", etc.
return ITEMS.filter(
(item) =>
item.title.toLowerCase().includes(q) ||
item.description.toLowerCase().includes(q),
);
},
render: () => {
let component: ReactRenderer<SlashMenuListRef> | null = null;
let popup: TippyInstance[] | null = null;
return {
onStart: (props: SuggestionProps<SlashItem>) => {
component = new ReactRenderer(SlashMenuList, {
props,
editor: props.editor,
});
if (!props.clientRect) return;
popup = tippy("body", {
getReferenceClientRect: props.clientRect as () => DOMRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: "manual",
placement: "bottom-start",
});
},
onUpdate(props: SuggestionProps<SlashItem>) {
component?.updateProps(props);
if (!props.clientRect || !popup?.[0]) return;
popup[0].setProps({
getReferenceClientRect: props.clientRect as () => DOMRect,
});
},
onKeyDown(props: SuggestionKeyDownProps) {
if (props.event.key === "Escape") {
popup?.[0]?.hide();
return true;
}
return component?.ref?.onKeyDown(props) ?? false;
},
onExit() {
popup?.[0]?.destroy();
component?.destroy();
},
};
},
};
}
|