Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(markdown): add document outline (#4834)

Eric Hayesc7c638795cdd
diff --git a/apps/web/src/components/ui/components/Scroll.tsx b/apps/web/src/components/ui/components/Scroll.tsx
index e22b484a84..640deee4fd 100644
--- a/apps/web/src/components/ui/components/Scroll.tsx
+++ b/apps/web/src/components/ui/components/Scroll.tsx
@@ -1,5 +1,5 @@
import type { JSX } from 'solid-js';
-import { createSignal, onCleanup, onMount } from 'solid-js';
+import { createSignal, onCleanup, onMount, splitProps } from 'solid-js';
const THUMB_WIDTH = 2;
const HIDE_DELAY = 500;
@@ -7,7 +7,12 @@ const GUTTER_WIDTH = 8;
const MIN_THUMB_HEIGHT = 24;
const THUMB_INSET = (GUTTER_WIDTH - THUMB_WIDTH) * 0.5;
-export function Scroll(props: JSX.HTMLAttributes<HTMLDivElement>) {
+type ScrollProps = JSX.HTMLAttributes<HTMLDivElement> & {
+ scrollRef?: (element: HTMLDivElement) => void;
+};
+
+export function Scroll(props: ScrollProps) {
+ const [local, rest] = splitProps(props, ['children', 'scrollRef']);
const [translateY, setTranslateY] = createSignal(THUMB_INSET);
const [thumbHeight, setThumbHeight] = createSignal(MIN_THUMB_HEIGHT);
const [visible, setVisible] = createSignal(false);
@@ -95,7 +100,7 @@ export function Scroll(props: JSX.HTMLAttributes<HTMLDivElement>) {
return (
<div
- {...props}
+ {...rest}
style={{
position: 'relative',
'min-height': '0',
@@ -105,7 +110,10 @@ export function Scroll(props: JSX.HTMLAttributes<HTMLDivElement>) {
}}
>
<div
- ref={scrollRef}
+ ref={(element) => {
+ scrollRef = element;
+ local.scrollRef?.(element);
+ }}
onScroll={handleScroll}
style={{
'scrollbar-width': 'none',
@@ -113,7 +121,7 @@ export function Scroll(props: JSX.HTMLAttributes<HTMLDivElement>) {
height: '100%',
}}
>
- <div ref={contentRef}>{props.children}</div>
+ <div ref={contentRef}>{local.children}</div>
</div>
<div
ref={gutterRef}
diff --git a/apps/web/src/features/block-md/component/Block.tsx b/apps/web/src/features/block-md/component/Block.tsx
index 389c52e832..a09bf215e9 100644
--- a/apps/web/src/features/block-md/component/Block.tsx
+++ b/apps/web/src/features/block-md/component/Block.tsx
@@ -211,7 +211,7 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
class="w-full grow overflow-hidden relative"
data-block-content
>
- <Scroll class="relative" ref={setScrollRef}>
+ <Scroll class="relative" scrollRef={setScrollRef}>
<div class="relative portal-scope mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">
<Suspense>
<Show
diff --git a/apps/web/src/features/block-md/component/MarkdownOutline.test.ts b/apps/web/src/features/block-md/component/MarkdownOutline.test.ts
new file mode 100644
index 0000000000..005d95fabe
--- /dev/null
+++ b/apps/web/src/features/block-md/component/MarkdownOutline.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { getActiveHeadingIndex, shouldShowOutline } from './MarkdownOutline';
+
+describe('getActiveHeadingIndex', () => {
+ it('selects the first heading before the document reaches it', () => {
+ expect(getActiveHeadingIndex([120, 320, 640], 80)).toBe(0);
+ });
+
+ it('selects the last heading above the active line', () => {
+ expect(getActiveHeadingIndex([20, 100, 300], 150)).toBe(1);
+ });
+
+ it('returns no selection when the document has no headings', () => {
+ expect(getActiveHeadingIndex([], 150)).toBe(-1);
+ });
+});
+
+describe('shouldShowOutline', () => {
+ it('requires layout eligibility and at least three headings', () => {
+ expect(shouldShowOutline(2, true)).toBe(false);
+ expect(shouldShowOutline(3, false)).toBe(false);
+ expect(shouldShowOutline(3, true)).toBe(true);
+ });
+});
diff --git a/apps/web/src/features/block-md/component/MarkdownOutline.tsx b/apps/web/src/features/block-md/component/MarkdownOutline.tsx
new file mode 100644
index 0000000000..25ea7aa55d
--- /dev/null
+++ b/apps/web/src/features/block-md/component/MarkdownOutline.tsx
@@ -0,0 +1,255 @@
+import { HoverCard } from '@core/component/HoverCard';
+import { $isHeadingNode } from '@lexical/rich-text';
+import { $getRoot, type LexicalEditor } from 'lexical';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ For,
+ onCleanup,
+} from 'solid-js';
+
+type OutlineHeading = {
+ key: string;
+ level: number;
+ text: string;
+};
+
+const ACTIVE_HEADING_OFFSET = 80;
+const MIN_OUTLINE_HEADINGS = 3;
+export const MARKDOWN_OUTLINE_WIDTH = 40;
+
+export function shouldShowOutline(
+ headingCount: number,
+ enabled: boolean
+): boolean {
+ return enabled && headingCount >= MIN_OUTLINE_HEADINGS;
+}
+
+export function getActiveHeadingIndex(
+ headingTops: number[],
+ activeLine: number
+): number {
+ if (headingTops.length === 0) return -1;
+
+ let activeIndex = 0;
+ for (const [index, top] of headingTops.entries()) {
+ if (top > activeLine) break;
+ activeIndex = index;
+ }
+ return activeIndex;
+}
+
+function headingsEqual(a: OutlineHeading[], b: OutlineHeading[]) {
+ return (
+ a.length === b.length &&
+ a.every(
+ (heading, index) =>
+ heading.key === b[index]?.key &&
+ heading.level === b[index]?.level &&
+ heading.text === b[index]?.text
+ )
+ );
+}
+
+export function useMarkdownOutline(props: {
+ editor: Accessor<LexicalEditor | undefined>;
+ enabled: Accessor<boolean>;
+}) {
+ const [headings, setHeadings] = createSignal<OutlineHeading[]>([]);
+
+ createEffect(() => {
+ const editor = props.editor();
+ if (!editor) {
+ setHeadings([]);
+ return;
+ }
+
+ const refreshHeadings = () => {
+ const nextHeadings = editor.getEditorState().read(() =>
+ $getRoot()
+ .getChildren()
+ .filter($isHeadingNode)
+ .map((node) => ({
+ key: node.getKey(),
+ level: Number(node.getTag().slice(1)),
+ text: node.getTextContent().trim(),
+ }))
+ .filter((heading) => heading.text.length > 0)
+ );
+
+ setHeadings((current) =>
+ headingsEqual(current, nextHeadings) ? current : nextHeadings
+ );
+ };
+
+ refreshHeadings();
+ onCleanup(editor.registerUpdateListener(refreshHeadings));
+ });
+
+ return {
+ headings,
+ show: () => shouldShowOutline(headings().length, props.enabled()),
+ };
+}
+
+type MarkdownOutlineState = ReturnType<typeof useMarkdownOutline>;
+
+function OutlineDash(props: { active: boolean }) {
+ return (
+ <span
+ class={
+ props.active
+ ? 'h-px w-3 rounded-full bg-accent'
+ : 'h-px w-2 rounded-full bg-ink/20'
+ }
+ />
+ );
+}
+
+function OutlineItem(props: {
+ active: boolean;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={props.label}
+ aria-current={props.active ? 'location' : undefined}
+ class="h-7 w-full truncate rounded-md px-2 text-left text-xs text-ink-muted hover:bg-hover hover:text-ink"
+ classList={{ 'font-semibold text-accent': props.active }}
+ onClick={props.onClick}
+ >
+ {props.label}
+ </button>
+ );
+}
+
+export function MarkdownOutline(props: {
+ editor: Accessor<LexicalEditor | undefined>;
+ outline: MarkdownOutlineState;
+ portalMount: Accessor<HTMLElement>;
+ scrollContainer: Accessor<HTMLElement | undefined>;
+}) {
+ const [activeHeadingKey, setActiveHeadingKey] = createSignal<string>();
+ const [viewportCenter, setViewportCenter] = createSignal(0);
+
+ createEffect(() => {
+ const scrollContainer = props.scrollContainer();
+ if (!scrollContainer) return;
+
+ const syncViewportCenter = () => {
+ setViewportCenter(scrollContainer.clientHeight / 2);
+ };
+ const resizeObserver = new ResizeObserver(syncViewportCenter);
+ syncViewportCenter();
+ resizeObserver.observe(scrollContainer);
+ onCleanup(() => resizeObserver.disconnect());
+ });
+
+ createEffect(() => {
+ const editor = props.editor();
+ const scrollContainer = props.scrollContainer();
+ const currentHeadings = props.outline.headings();
+ if (!editor || !scrollContainer) return;
+
+ let frame: number | undefined;
+
+ const syncActiveHeading = () => {
+ const containerTop = scrollContainer.getBoundingClientRect().top;
+ const activeLine = containerTop + ACTIVE_HEADING_OFFSET;
+ const headingTops = currentHeadings.map(
+ (heading) =>
+ editor.getElementByKey(heading.key)?.getBoundingClientRect().top ??
+ Number.POSITIVE_INFINITY
+ );
+ const activeIndex = getActiveHeadingIndex(headingTops, activeLine);
+ setActiveHeadingKey(currentHeadings[activeIndex]?.key);
+ };
+
+ const queueViewportSync = () => {
+ if (frame !== undefined) cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ syncActiveHeading();
+ });
+ };
+ queueViewportSync();
+ scrollContainer.addEventListener('scroll', queueViewportSync, {
+ passive: true,
+ });
+ onCleanup(() => {
+ scrollContainer.removeEventListener('scroll', queueViewportSync);
+ if (frame !== undefined) cancelAnimationFrame(frame);
+ });
+ });
+
+ const scrollToElement = (element: HTMLElement) => {
+ const scrollContainer = props.scrollContainer();
+ if (!scrollContainer) return;
+
+ const containerTop = scrollContainer.getBoundingClientRect().top;
+ const elementTop = element.getBoundingClientRect().top;
+ scrollContainer.scrollTo({
+ top:
+ scrollContainer.scrollTop +
+ elementTop -
+ containerTop -
+ ACTIVE_HEADING_OFFSET,
+ behavior: 'smooth',
+ });
+ };
+
+ const scrollToHeading = (heading: OutlineHeading) => {
+ const headingElement = props.editor()?.getElementByKey(heading.key);
+ if (!headingElement) return;
+
+ scrollToElement(headingElement);
+ setActiveHeadingKey(heading.key);
+ };
+
+ return (
+ <div
+ class="pointer-events-auto sticky z-1 w-3 -translate-y-1/2"
+ style={{ top: `${viewportCenter()}px` }}
+ >
+ <HoverCard
+ closeDelay={0}
+ content={
+ <div class="max-h-[calc(100vh-6rem)] w-52 overflow-y-auto rounded-xl bg-surface p-2 shadow-menu ring ring-edge">
+ <For each={props.outline.headings()}>
+ {(heading) => (
+ <OutlineItem
+ active={activeHeadingKey() === heading.key}
+ label={heading.text}
+ onClick={() => scrollToHeading(heading)}
+ />
+ )}
+ </For>
+ </div>
+ }
+ contentZIndexClass="z-item-options-menu"
+ gutter={-12}
+ openDelay={0}
+ placement="right"
+ portalMount={props.portalMount()}
+ trigger={
+ <div
+ aria-hidden="true"
+ class="flex w-3 flex-col items-start gap-2 py-1"
+ >
+ <For each={props.outline.headings()}>
+ {(heading) => (
+ <OutlineDash active={activeHeadingKey() === heading.key} />
+ )}
+ </For>
+ </div>
+ }
+ triggerAriaLabel="Document outline"
+ triggerAs="nav"
+ triggerClass="w-3 outline-none"
+ triggerTabIndex={0}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-md/component/MarkdownScrollViewport.test.tsx b/apps/web/src/features/block-md/component/MarkdownScrollViewport.test.tsx
new file mode 100644
index 0000000000..89af60cbde
--- /dev/null
+++ b/apps/web/src/features/block-md/component/MarkdownScrollViewport.test.tsx
@@ -0,0 +1,32 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { render } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { Scroll } from '../../../components/ui/components/Scroll';
+
+class ResizeObserverStub {
+ observe() {}
+ disconnect() {}
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('Markdown scroll viewport', () => {
+ it('exposes the element that owns vertical scrolling', () => {
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+ const setScrollRef = vi.fn<(element: HTMLDivElement) => void>();
+
+ const { container } = render(() => (
+ <Scroll scrollRef={setScrollRef}>Content</Scroll>
+ ));
+
+ expect(setScrollRef).toHaveBeenCalledOnce();
+ const viewport = setScrollRef.mock.calls[0]?.[0];
+ expect(viewport?.style.overflowY).toBe('auto');
+ expect(viewport?.parentElement).toBe(container.firstElementChild);
+ });
+});
diff --git a/apps/web/src/features/block-md/component/Notebook.tsx b/apps/web/src/features/block-md/component/Notebook.tsx
index 9632ae4e22..4429f3153c 100644
--- a/apps/web/src/features/block-md/component/Notebook.tsx
+++ b/apps/web/src/features/block-md/component/Notebook.tsx
@@ -50,6 +50,11 @@ import { InlineTaskGithubPullRequests } from './InlineTaskGithubPullRequests';
import { InlineTaskProperties } from './InlineTaskProperties';
import { InstructionsEditor } from './InstructionsEditor';
import { MarkdownEditor } from './MarkdownEditor';
+import {
+ MARKDOWN_OUTLINE_WIDTH,
+ MarkdownOutline,
+ useMarkdownOutline,
+} from './MarkdownOutline';
import { TaskDuplicateMatchPill } from './TaskDuplicateMatches';
import { TitleEditor } from './TitleEditor';
import {
@@ -71,6 +76,9 @@ const NoteTargetWidth = 768;
const CommentTargetWidth = 320;
const GapTargetWidth = 24;
const MinimizedCommentTargetWidth = 48;
+const OutlineEdgeInset = 16;
+const OutlineMinWidth =
+ NoteTargetWidth + 2 * (MARKDOWN_OUTLINE_WIDTH + OutlineEdgeInset);
enum CommentLayoutMode {
lg = 'lg',
@@ -120,11 +128,20 @@ export function Notebook(props: {
let notebookRef!: HTMLDivElement;
let commentMarginRef: HTMLDivElement | undefined;
let contentRef!: HTMLDivElement;
+ // Escape the notebook's isolated stacking context so the menu covers editor
+ // handles, while remaining inside the block so app chrome still covers it.
+ const outlinePortalMount = () =>
+ notebookRef.closest<HTMLElement>('.portal-scope') ?? notebookRef;
const [layoutMode, setLayoutMode] = createSignal(CommentLayoutMode.none);
const [width, setWidth] = createSignal(0);
const [leftFloatX, setLeftFloatX] = createSignal(0);
const canUseLexicalStateDebugger = useCanUseLexicalStateDebugger();
+ const outline = useMarkdownOutline({
+ editor: () => md.editor,
+ enabled: () =>
+ width() >= OutlineMinWidth && !history.isOpen() && !isMobile(),
+ });
const comments = commentsStore.get;
const hasComment = createMemo(() => {
@@ -309,6 +326,22 @@ export function Notebook(props: {
return (
<div class={containerClasses()} ref={notebookRef}>
+ <Show when={outline.show()}>
+ <div
+ class="pointer-events-none absolute inset-y-0 z-1"
+ style={{
+ left: `${OutlineEdgeInset}px`,
+ width: `${MARKDOWN_OUTLINE_WIDTH}px`,
+ }}
+ >
+ <MarkdownOutline
+ editor={() => md.editor}
+ outline={outline}
+ portalMount={outlinePortalMount}
+ scrollContainer={() => md.scrollContainer}
+ />
+ </div>
+ </Show>
<div
class={contentDivClasses()}
ref={contentRef}
diff --git a/apps/web/src/lib/core/component/HoverCard.tsx b/apps/web/src/lib/core/component/HoverCard.tsx
index dd92edb06c..c8ae5e77f9 100644
--- a/apps/web/src/lib/core/component/HoverCard.tsx
+++ b/apps/web/src/lib/core/component/HoverCard.tsx
@@ -3,7 +3,7 @@ import {
type HoverCardRootProps,
HoverCard as KobalteHoverCard,
} from '@kobalte/core/hover-card';
-import { cn } from '@ui';
+import { cn } from '@ui/utils/classname';
import type { JSX, Setter } from 'solid-js';
import {
createContext,
@@ -42,11 +42,15 @@ type HoverCardComponentProps = {
gutter?: number;
/** Additional class for content */
contentClass?: string;
+ /** Semantic z-index class for the portaled content. Defaults to `z-tool-tip`. */
+ contentZIndexClass?: string;
/**
* Element type Kobalte should render the trigger as. Defaults to `span`.
- * Use `div` when the trigger child is itself block-level (e.g. a chip).
+ * Use `div` for block-level children or `nav` for navigation triggers.
*/
- triggerAs?: 'span' | 'div';
+ triggerAs?: 'span' | 'div' | 'nav';
+ /** Accessible label applied to the trigger element. */
+ triggerAriaLabel?: string;
/** Class applied to the underlying trigger element. */
triggerClass?: string;
/** Tab index for the trigger element. Use -1 to remove from tab order. */
@@ -67,6 +71,8 @@ type HoverCardComponentProps = {
* can dismiss the card via a close callback).
*/
open?: boolean;
+ /** Element that should receive the portaled hover-card content. */
+ portalMount?: HTMLElement;
/** Placement of the hover card */
placement?: HoverCardRootProps['placement'];
};
@@ -204,6 +210,7 @@ export function HoverCard(props: HoverCardComponentProps) {
>
<KobalteHoverCard.Trigger
as={props.triggerAs ?? 'span'}
+ aria-label={props.triggerAriaLabel}
class={props.triggerClass}
disabled={isDisabled()}
tabIndex={props.triggerTabIndex}
@@ -211,12 +218,15 @@ export function HoverCard(props: HoverCardComponentProps) {
{props.trigger}
</KobalteHoverCard.Trigger>
- <KobalteHoverCard.Portal>
+ <KobalteHoverCard.Portal mount={props.portalMount}>
<KobalteHoverCard.Content
ref={(el) => {
contentEl = el;
}}
- class={cn('z-tool-tip', props.contentClass)}
+ class={cn(
+ props.contentZIndexClass ?? 'z-tool-tip',
+ props.contentClass
+ )}
>
<HoverCardPortalNestedPreviewOpenContext.Provider
value={{ count: nestedOpenCount, setCount: setNestedOpenCount }}