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: theme mentions (#1303)

Peter Chinmand45e88f2579c
diff --git a/js/app/packages/block-theme/utils/__tests__/themeValidation.test.ts b/js/app/packages/block-theme/utils/__tests__/themeValidation.test.ts
new file mode 100644
index 0000000000..6ba8a7b731
--- /dev/null
+++ b/js/app/packages/block-theme/utils/__tests__/themeValidation.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest';
+import {
+ isThemeV1,
+ parseThemeV1Json,
+} from '@block-theme/utils/themeValidation';
+
+const validThemeJson = JSON.stringify({
+ id: 'test-theme-id',
+ name: 'dryblood',
+ version: 1,
+ tokens: {
+ a0: { l: 0.7, c: 0.15, h: 30 },
+ a1: { l: 0.6, c: 0.12, h: 30 },
+ a2: { l: 0.5, c: 0.1, h: 30 },
+ a3: { l: 0.4, c: 0.08, h: 30 },
+ a4: { l: 0.3, c: 0.06, h: 30 },
+ b0: { l: 0.2, c: 0.02, h: 300 },
+ b1: { l: 0.25, c: 0.02, h: 300 },
+ b2: { l: 0.15, c: 0.02, h: 300 },
+ b3: { l: 0.1, c: 0.02, h: 300 },
+ b4: { l: 0.05, c: 0.02, h: 300 },
+ c0: { l: 0.9, c: 0.02, h: 300 },
+ c1: { l: 0.8, c: 0.02, h: 300 },
+ c2: { l: 0.7, c: 0.02, h: 300 },
+ c3: { l: 0.6, c: 0.02, h: 300 },
+ c4: { l: 0.5, c: 0.02, h: 300 },
+ },
+});
+
+describe('parseThemeV1Json', () => {
+ it('returns parsed ThemeV1 for valid theme JSON', () => {
+ const result = parseThemeV1Json(validThemeJson);
+ expect(result).not.toBeNull();
+ expect(result!.id).toBe('test-theme-id');
+ expect(result!.name).toBe('dryblood');
+ expect(result!.version).toBe(1);
+ expect(result!.tokens.a0).toEqual({ l: 0.7, c: 0.15, h: 30 });
+ });
+
+ it('returns null for invalid JSON', () => {
+ expect(parseThemeV1Json('not json')).toBeNull();
+ });
+
+ it('returns null for JSON missing id', () => {
+ const json = JSON.parse(validThemeJson);
+ delete json.id;
+ expect(parseThemeV1Json(JSON.stringify(json))).toBeNull();
+ });
+
+ it('returns null for JSON missing name', () => {
+ const json = JSON.parse(validThemeJson);
+ delete json.name;
+ expect(parseThemeV1Json(JSON.stringify(json))).toBeNull();
+ });
+
+ it('returns null for JSON missing version', () => {
+ const json = JSON.parse(validThemeJson);
+ delete json.version;
+ expect(parseThemeV1Json(JSON.stringify(json))).toBeNull();
+ });
+
+ it('returns null for JSON missing tokens', () => {
+ const json = JSON.parse(validThemeJson);
+ delete json.tokens;
+ expect(parseThemeV1Json(JSON.stringify(json))).toBeNull();
+ });
+
+ it('returns null for JSON with incomplete tokens (missing a token key)', () => {
+ const json = JSON.parse(validThemeJson);
+ delete json.tokens.c4;
+ expect(parseThemeV1Json(JSON.stringify(json))).toBeNull();
+ });
+
+ it('returns null for JSON with invalid token value (missing l)', () => {
+ const json = JSON.parse(validThemeJson);
+ json.tokens.a0 = { c: 0.15, h: 30 };
+ expect(parseThemeV1Json(JSON.stringify(json))).toBeNull();
+ });
+
+ it('returns null for JSON with non-number token value', () => {
+ const json = JSON.parse(validThemeJson);
+ json.tokens.a0 = { l: 'not a number', c: 0.15, h: 30 };
+ expect(parseThemeV1Json(JSON.stringify(json))).toBeNull();
+ });
+
+ it('returns null for empty string', () => {
+ expect(parseThemeV1Json('')).toBeNull();
+ });
+
+ it('returns null for a plain URL', () => {
+ expect(parseThemeV1Json('https://example.com')).toBeNull();
+ });
+
+ it('returns null for an array', () => {
+ expect(parseThemeV1Json('[]')).toBeNull();
+ });
+
+ it('returns null for null', () => {
+ expect(parseThemeV1Json('null')).toBeNull();
+ });
+});
+
+describe('isThemeV1', () => {
+ it('returns true for a valid ThemeV1 object', () => {
+ const data = JSON.parse(validThemeJson);
+ expect(isThemeV1(data)).toBe(true);
+ });
+
+ it('returns false for null', () => {
+ expect(isThemeV1(null)).toBe(false);
+ });
+
+ it('returns false for a string', () => {
+ expect(isThemeV1('not an object')).toBe(false);
+ });
+
+ it('returns false for an object missing tokens', () => {
+ const data = JSON.parse(validThemeJson);
+ delete data.tokens;
+ expect(isThemeV1(data)).toBe(false);
+ });
+});
diff --git a/js/app/packages/block-theme/utils/themeValidation.ts b/js/app/packages/block-theme/utils/themeValidation.ts
new file mode 100644
index 0000000000..c48b13884d
--- /dev/null
+++ b/js/app/packages/block-theme/utils/themeValidation.ts
@@ -0,0 +1,56 @@
+import type { ThemeV1, ThemeV1Tokens } from '../types/themeTypes';
+
+const THEME_V1_TOKEN_KEYS: ReadonlyArray<keyof ThemeV1Tokens> = [
+ 'a0',
+ 'a1',
+ 'a2',
+ 'a3',
+ 'a4',
+ 'b0',
+ 'b1',
+ 'b2',
+ 'b3',
+ 'b4',
+ 'c0',
+ 'c1',
+ 'c2',
+ 'c3',
+ 'c4',
+];
+
+function isTokenValue(val: unknown): val is { l: number; c: number; h: number } {
+ if (typeof val !== 'object' || val === null) return false;
+ const obj = val as Record<string, unknown>;
+ return (
+ typeof obj.l === 'number' &&
+ typeof obj.c === 'number' &&
+ typeof obj.h === 'number'
+ );
+}
+
+export function isThemeV1(data: unknown): data is ThemeV1 {
+ if (typeof data !== 'object' || data === null) return false;
+ const obj = data as Record<string, unknown>;
+
+ if (typeof obj.id !== 'string') return false;
+ if (typeof obj.name !== 'string') return false;
+ if (typeof obj.version !== 'number') return false;
+ if (typeof obj.tokens !== 'object' || obj.tokens === null) return false;
+
+ const tokens = obj.tokens as Record<string, unknown>;
+ for (const key of THEME_V1_TOKEN_KEYS) {
+ if (!isTokenValue(tokens[key])) return false;
+ }
+
+ return true;
+}
+
+export function parseThemeV1Json(text: string): ThemeV1 | null {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (isThemeV1(parsed)) return parsed;
+ return null;
+ } catch {
+ return null;
+ }
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index 6ad18e5918..a87039b373 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -22,6 +22,7 @@ import {
type GroupMentionNode,
type HorizontalRuleNode,
type ImageNode,
+ type ThemeMentionNode,
isSupportedLanguage,
normalizedLanguage,
SupportedNodeTypes,
@@ -75,6 +76,7 @@ import { Equation as EquationDecorator } from '../decorator/Equation';
import { MarkdownImage as ImageDecorator } from '../decorator/MarkdownImage';
import { MarkdownVideo as VideoDecorator } from '../decorator/MarkdownVideo';
import { UserMention as UserMentionDecorator } from '../decorator/UserMention';
+import { ThemeMention as ThemeMentionDecorator } from '../decorator/ThemeMention';
import { Watermark as WatermarkDecorator } from '../decorator/Watermark';
import { LinkWithPreview } from './LinkWithPreview';
@@ -276,6 +278,20 @@ const DocumentMention: RenderableEntity<DocumentMentionNode> = {
),
};
+const ThemeMention: RenderableEntity<ThemeMentionNode> = {
+ guard: (node: LexicalNode): node is ThemeMentionNode =>
+ node.__type === 'theme-mention',
+ render: (props) => (
+ <span>
+ {ThemeMentionDecorator({
+ ...props.node.exportComponentProps(),
+ key: props.node.getKey(),
+ theme: props.theme,
+ })}
+ </span>
+ ),
+};
+
const Watermark: RenderableEntity<WatermarkNode> = {
guard: (node: LexicalNode): node is WatermarkNode =>
node.__type === 'watermark',
@@ -658,6 +674,7 @@ const InlineEntities: Array<RenderableEntity> = [
Video,
HorizontalRule,
Equation,
+ ThemeMention,
Watermark,
] as const;
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/ThemeMention.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/ThemeMention.tsx
new file mode 100644
index 0000000000..d0bfdb1226
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/ThemeMention.tsx
@@ -0,0 +1,99 @@
+import type { ThemeMentionDecoratorProps } from '@lexical-core';
+import type { ThemeV1 } from '@block-theme/types/themeTypes';
+import { isThemeV1 } from '@block-theme/utils/themeValidation';
+import { setUserThemes, userThemes } from '@block-theme/signals/themeSignals';
+import { applyTheme } from '@block-theme/utils/themeUtils';
+import { useSettingsState } from '@core/constant/SettingsState';
+
+export function ThemeMention(props: ThemeMentionDecoratorProps) {
+ const { openSettings } = useSettingsState();
+
+ const theme = (): ThemeV1 | null => {
+ if (isThemeV1(props.data)) return props.data;
+ return null;
+ };
+
+ const a0 = () => theme()?.tokens.a0;
+ const b0 = () => theme()?.tokens.b0;
+ const c0 = () => theme()?.tokens.c0;
+
+ const oklch = (token: { l: number; c: number; h: number } | undefined) => {
+ if (!token) return 'transparent';
+ return `oklch(${token.l} ${token.c} ${token.h}deg)`;
+ };
+
+ const handleClick = () => {
+ const t = theme();
+ if (!t) return;
+
+ const existing = userThemes().find((ut: ThemeV1) => ut.id === t.id);
+ if (!existing) {
+ setUserThemes([...userThemes(), t]);
+ }
+
+ applyTheme(t.id);
+ openSettings('Appearance');
+ };
+
+ return (
+ <span
+ class="pointer-events-auto"
+ style={{ cursor: 'var(--cursor-pointer)' }}
+ onClick={handleClick}
+ >
+ <span
+ style={{
+ display: 'inline-flex',
+ 'align-items': 'center',
+ gap: '3px',
+ 'vertical-align': 'baseline',
+ padding: '1px 4px',
+ 'border-radius': '3px',
+ border: '1px solid var(--color-edge-muted)',
+ }}
+ >
+ <span
+ style={{
+ display: 'inline-flex',
+ gap: '2px',
+ 'align-items': 'center',
+ }}
+ >
+ <span
+ style={{
+ display: 'inline-block',
+ width: '10px',
+ height: '10px',
+ 'border-radius': '2px',
+ 'background-color': oklch(a0()),
+ border: '1px solid var(--color-edge-muted)',
+ }}
+ />
+ <span
+ style={{
+ display: 'inline-block',
+ width: '10px',
+ height: '10px',
+ 'border-radius': '2px',
+ 'background-color': oklch(b0()),
+ border: '1px solid var(--color-edge-muted)',
+ }}
+ />
+ <span
+ style={{
+ display: 'inline-block',
+ width: '10px',
+ height: '10px',
+ 'border-radius': '2px',
+ 'background-color': oklch(c0()),
+ border: '1px solid var(--color-edge-muted)',
+ }}
+ />
+ </span>
+ <span style={{ 'margin-inline': '2px', cursor: 'default' }}>
+ {props.name}
+ </span>
+ </span>
+ </span>
+ );
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/init.ts b/js/app/packages/core/component/LexicalMarkdown/init.ts
index 129a98ecdf..0002c624aa 100644
--- a/js/app/packages/core/component/LexicalMarkdown/init.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/init.ts
@@ -10,6 +10,7 @@ import {
HorizontalRuleNode,
HtmlRenderNode,
ImageNode,
+ ThemeMentionNode,
UserMentionNode,
VideoNode,
WatermarkNode,
@@ -28,6 +29,7 @@ import { HtmlRender } from './component/decorator/HtmlRender';
import { MarkdownImage } from './component/decorator/MarkdownImage';
import { MarkdownVideo } from './component/decorator/MarkdownVideo';
import { UserMention } from './component/decorator/UserMention';
+import { ThemeMention } from './component/decorator/ThemeMention';
import { Watermark } from './component/decorator/Watermark';
import { registerDiffNodeFactory } from './component/dom-factory/diff-factory';
@@ -49,6 +51,7 @@ export function initializeLexical() {
setDecorator(EquationNode, Equation);
setDecorator(SnapshotNode, Snapshot);
setDecorator(HtmlRenderNode, HtmlRender);
+ setDecorator(ThemeMentionNode, ThemeMention);
setDecorator(WatermarkNode, Watermark);
registerDiffNodeFactory();
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
index 449e85e37d..182b7c62ec 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
@@ -10,6 +10,7 @@ import {
$createGroupMentionNode,
$createInlineSearchNode,
$createSnapshotNode,
+ $createThemeMentionNode,
$createUserMentionNode,
$handleInlineSearchNodeMutation,
$handleInlineSearchNodeTransform,
@@ -30,6 +31,7 @@ import {
InlineSearchNode,
InlineSearchNodesType,
type SnapshotNodeInfo,
+ type ThemeMentionInfo,
type UserMentionInfo,
UserMentionNode,
validTriggerPosition,
@@ -102,6 +104,9 @@ export const INSERT_USER_MENTION_COMMAND: LexicalCommand<UserMentionInfo> =
export const INSERT_GROUP_MENTION_COMMAND: LexicalCommand<GroupMentionInfo> =
createCommand('INSERT_GROUP_MENTION_COMMAND');
+export const INSERT_THEME_MENTION_COMMAND: LexicalCommand<ThemeMentionInfo> =
+ createCommand('INSERT_THEME_MENTION_COMMAND');
+
export type ItemMention = {
itemType:
| 'document'
@@ -460,6 +465,33 @@ function registerMentionsPlugin(
COMMAND_PRIORITY_NORMAL
),
+ editor.registerCommand(
+ INSERT_THEME_MENTION_COMMAND,
+ (payload) => {
+ editor.update(() => {
+ const selection = $getSelection();
+ const mentionNode = $createThemeMentionNode(
+ payload.name,
+ payload.data
+ );
+
+ if ($isRangeSelection(selection) && !selection.isCollapsed()) {
+ $collapseSelection(selection);
+ $insertNodes([$createTextNode(' '), mentionNode]);
+ mentionNode.selectEnd();
+ return true;
+ }
+ $insertNodes([mentionNode]);
+ if ($isRootOrShadowRoot(mentionNode.getParentOrThrow())) {
+ $wrapNodeInElement(mentionNode, $createParagraphNode);
+ }
+ mentionNode.selectEnd();
+ });
+ return true;
+ },
+ COMMAND_PRIORITY_NORMAL
+ ),
+
registerSymbolListener(),
editor.registerCommand(
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
index cde266f199..12a8d1e00b 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
@@ -1,5 +1,6 @@
import type { BlockAlias, BlockName } from '@core/block';
import { mergeRegister } from '@lexical/utils';
+import { parseThemeV1Json } from '@block-theme/utils/themeValidation';
import {
$getSelection,
$isRangeSelection,
@@ -7,7 +8,10 @@ import {
type LexicalEditor,
PASTE_COMMAND,
} from 'lexical';
-import { INSERT_DOCUMENT_MENTION_COMMAND } from '../mentions';
+import {
+ INSERT_DOCUMENT_MENTION_COMMAND,
+ INSERT_THEME_MENTION_COMMAND,
+} from '../mentions';
type MacroAppUrlParsed = {
isValid: boolean;
@@ -132,6 +136,21 @@ function registerTextPastePlugin(editor: LexicalEditor) {
const pastedText: string =
event.clipboardData?.getData('text/plain') || '';
+ // Check for theme JSON before checking for Macro URL
+ const themeV1 = parseThemeV1Json(pastedText);
+ if (themeV1) {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection) && !selection.isCollapsed())
+ return false;
+
+ event.preventDefault();
+ editor.dispatchCommand(INSERT_THEME_MENTION_COMMAND, {
+ name: themeV1.name,
+ data: themeV1,
+ });
+ return true;
+ }
+
const parsedMacroAppUrl = parseMacroAppUrl(pastedText);
if (
!parsedMacroAppUrl.isValid ||
diff --git a/js/app/packages/lexical-core/decoratorRegistry.ts b/js/app/packages/lexical-core/decoratorRegistry.ts
index 186553068e..98d61d8bd6 100644
--- a/js/app/packages/lexical-core/decoratorRegistry.ts
+++ b/js/app/packages/lexical-core/decoratorRegistry.ts
@@ -45,6 +45,10 @@ import type {
UserMentionNode,
} from './nodes/UserMentionNode';
import type { VideoDecoratorProps, VideoNode } from './nodes/VideoNode';
+import type {
+ ThemeMentionDecoratorProps,
+ ThemeMentionNode,
+} from './nodes/ThemeMentionNode';
import type {
WatermarkDecoratorProps,
WatermarkNode,
@@ -107,6 +111,10 @@ export interface NodeDecoratorMap {
klass: typeof HtmlRenderNode;
props: HtmlRenderDecoratorProps;
};
+ ThemeMentionNode: {
+ klass: typeof ThemeMentionNode;
+ props: ThemeMentionDecoratorProps;
+ };
WatermarkNode: {
klass: typeof WatermarkNode;
props: WatermarkDecoratorProps;
diff --git a/js/app/packages/lexical-core/index.ts b/js/app/packages/lexical-core/index.ts
index eaa17ae9d5..f6b8592f2e 100644
--- a/js/app/packages/lexical-core/index.ts
+++ b/js/app/packages/lexical-core/index.ts
@@ -25,6 +25,7 @@ export * from './nodes/MediaNode';
export * from './nodes/UnlinkedTextNode';
export * from './nodes/UserMentionNode';
export * from './nodes/VideoNode';
+export * from './nodes/ThemeMentionNode';
export * from './nodes/WatermarkNode';
export * from './plugins/nodeIdPlugin';
diff --git a/js/app/packages/lexical-core/node-list.ts b/js/app/packages/lexical-core/node-list.ts
index 2b64a2d79b..595b281001 100644
--- a/js/app/packages/lexical-core/node-list.ts
+++ b/js/app/packages/lexical-core/node-list.ts
@@ -35,6 +35,7 @@ import { SearchMatchNode } from './nodes/SearchMatchNode';
import { UnlinkedTextNode } from './nodes/UnlinkedTextNode';
import { UserMentionNode } from './nodes/UserMentionNode';
import { VideoNode } from './nodes/VideoNode';
+import { ThemeMentionNode } from './nodes/ThemeMentionNode';
import { WatermarkNode } from './nodes/WatermarkNode';
/**
@@ -93,6 +94,7 @@ export const SupportedNodeTypes = [
HtmlRenderNode,
ClassedBlockNode,
WatermarkNode,
+ ThemeMentionNode,
] as const;
export const NodeReplacements: LexicalNodeReplacement[] = [
diff --git a/js/app/packages/lexical-core/nodes/ThemeMentionNode.ts b/js/app/packages/lexical-core/nodes/ThemeMentionNode.ts
new file mode 100644
index 0000000000..34e12508a4
--- /dev/null
+++ b/js/app/packages/lexical-core/nodes/ThemeMentionNode.ts
@@ -0,0 +1,175 @@
+import {
+ $applyNodeReplacement,
+ DecoratorNode,
+ type DOMConversion,
+ type DOMConversionMap,
+ type EditorConfig,
+ type EditorThemeClasses,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
+
+const VERSION = 1;
+
+export type ThemeMentionInfo = {
+ name: string;
+ data: Record<string, unknown>;
+};
+
+export type SerializedThemeMentionNode = Spread<
+ ThemeMentionInfo,
+ SerializedLexicalNode
+>;
+
+export type ThemeMentionDecoratorProps = ThemeMentionInfo & {
+ key: NodeKey;
+ theme: EditorThemeClasses;
+};
+
+export class ThemeMentionNode extends DecoratorNode<
+ DecoratorComponent<ThemeMentionDecoratorProps> | undefined
+> {
+ __name: string;
+ __data: Record<string, unknown>;
+
+ static getType() {
+ return 'theme-mention';
+ }
+
+ isInline(): boolean {
+ return true;
+ }
+
+ isKeyboardSelectable(): boolean {
+ return true;
+ }
+
+ static clone(node: ThemeMentionNode) {
+ return new ThemeMentionNode(node.__name, node.__data, node.__key);
+ }
+
+ constructor(name: string, data: Record<string, unknown>, key?: NodeKey) {
+ super(key);
+ this.__name = name;
+ this.__data = data;
+ }
+
+ static importJSON(serializedNode: SerializedThemeMentionNode) {
+ const node = $createThemeMentionNode(
+ serializedNode.name,
+ serializedNode.data
+ );
+ $applyIdFromSerialized(node, serializedNode);
+ return node;
+ }
+
+ exportJSON(): SerializedThemeMentionNode {
+ return {
+ ...super.exportJSON(),
+ name: this.__name,
+ data: this.__data,
+ type: ThemeMentionNode.getType(),
+ version: VERSION,
+ };
+ }
+
+ exportComponentProps(): ThemeMentionInfo {
+ return {
+ name: this.__name,
+ data: this.__data,
+ };
+ }
+
+ createDOM(_config: EditorConfig): HTMLElement {
+ const span = document.createElement('span');
+ span.setAttribute('data-theme-mention', 'true');
+ return span;
+ }
+
+ updateDOM(_prevNode: ThemeMentionNode, _dom: HTMLElement): boolean {
+ return false;
+ }
+
+ static importDOM(): DOMConversionMap<HTMLElement> | null {
+ const convert = (domNode: HTMLElement) => {
+ const themeJson = domNode.getAttribute('data-theme-json');
+ if (!themeJson) return null;
+
+ try {
+ const parsed: unknown = JSON.parse(themeJson);
+ if (typeof parsed !== 'object' || parsed === null) return null;
+ const obj = parsed as Record<string, unknown>;
+ if (typeof obj.name !== 'string') return null;
+
+ const node = $createThemeMentionNode(
+ obj.name,
+ obj as Record<string, unknown>
+ );
+ return { node };
+ } catch {
+ return null;
+ }
+ };
+
+ const wrapInCheck = (conversion: DOMConversion) => {
+ return (node: HTMLElement) =>
+ node.hasAttribute('data-theme-mention') ? conversion : null;
+ };
+
+ return {
+ span: wrapInCheck({ conversion: convert, priority: 1 }),
+ };
+ }
+
+ exportDOM() {
+ const element = document.createElement('span');
+ element.setAttribute('data-theme-mention', 'true');
+ element.setAttribute('data-theme-json', JSON.stringify(this.__data));
+ element.textContent = this.__name;
+ return { element };
+ }
+
+ getTextContent(): string {
+ return this.__name;
+ }
+
+ getThemeName(): string {
+ return this.__name;
+ }
+
+ getThemeData(): Record<string, unknown> {
+ return this.__data;
+ }
+
+ decorate(_: LexicalEditor, config: EditorConfig) {
+ const decorator = getDecorator<ThemeMentionNode>(ThemeMentionNode);
+ if (decorator) {
+ return () =>
+ decorator({
+ name: this.__name,
+ data: this.__data,
+ key: this.getKey(),
+ theme: config.theme,
+ });
+ }
+ }
+}
+
+export function $createThemeMentionNode(
+ name: string,
+ data: Record<string, unknown>
+): ThemeMentionNode {
+ const node = new ThemeMentionNode(name, data);
+ return $applyNodeReplacement(node);
+}
+
+export function $isThemeMentionNode(
+ node: ThemeMentionNode | LexicalNode | null | undefined
+): node is ThemeMentionNode {
+ return node instanceof ThemeMentionNode;
+}
diff --git a/js/app/packages/lexical-core/transformers/index.ts b/js/app/packages/lexical-core/transformers/index.ts
index 08ef80405d..9969781219 100644
--- a/js/app/packages/lexical-core/transformers/index.ts
+++ b/js/app/packages/lexical-core/transformers/index.ts
@@ -21,6 +21,7 @@ import {
I_DOCUMENT_CARD,
I_DOCUMENT_MENTION,
I_GROUP_MENTION,
+ I_THEME_MENTION,
I_USER_MENTION,
} from './mentions';
import { E_TABLE_NODE, I_TABLE_NODE } from './tables';
@@ -57,6 +58,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_TABLE_NODE,
I_MACRO_QUOTE,
I_EQUATION_NODE,
+ I_THEME_MENTION,
I_WATERMARK,
I_SNAPSHOT_NODE,
...CUSTOM_TRANSFORMERS,
@@ -117,6 +119,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [
E_DATE_MENTION,
I_MACRO_QUOTE,
I_EQUATION_NODE,
+ I_THEME_MENTION,
I_WATERMARK,
E_WATERMARK,
I_SNAPSHOT_NODE,
diff --git a/js/app/packages/lexical-core/transformers/mentions.ts b/js/app/packages/lexical-core/transformers/mentions.ts
index b7fb14333b..b3589cd68b 100644
--- a/js/app/packages/lexical-core/transformers/mentions.ts
+++ b/js/app/packages/lexical-core/transformers/mentions.ts
@@ -8,6 +8,7 @@ import { DateMentionNode } from '../nodes/DateMentionNode';
import { DocumentCardNode } from '../nodes/DocumentCardNode';
import { DocumentMentionNode } from '../nodes/DocumentMentionNode';
import { GroupMentionNode } from '../nodes/GroupMentionNode';
+import { ThemeMentionNode } from '../nodes/ThemeMentionNode';
import { UserMentionNode } from '../nodes/UserMentionNode';
// NOTE: If you are changing this file, you may need to update the `mention_utils` crate in `macro-api` as well. Please notify @hutch should you update this file.
@@ -360,6 +361,37 @@ export const I_DOCUMENT_CARD: ElementTransformer = {
},
};
+// Internal Theme Mentions
+export const I_THEME_MENTION: TextMatchTransformer = {
+ dependencies: [ThemeMentionNode],
+ type: 'text-match',
+ regExp: /<m-theme-mention>(.*?)<\/m-theme-mention>/,
+ importRegExp: /<m-theme-mention>(.*?)<\/m-theme-mention>/,
+ export: (node) => {
+ if (!(node instanceof ThemeMentionNode)) return null;
+ const data = JSON.stringify({
+ name: node.getThemeName(),
+ data: node.getThemeData(),
+ });
+ return `<m-theme-mention>${data}</m-theme-mention>`;
+ },
+ replace: (node: TextNode, match: RegExpMatchArray) => {
+ try {
+ const parsed = JSON.parse(match[1]);
+ if (
+ typeof parsed !== 'object' ||
+ parsed === null ||
+ typeof parsed.name !== 'string'
+ )
+ throw new Error('Invalid theme mention JSON');
+ const themeMentionNode = new ThemeMentionNode(parsed.name, parsed.data);
+ node.replace(themeMentionNode);
+ } catch (e) {
+ console.error('Error in I_THEME_MENTION replace:', e);
+ }
+ },
+};
+
// External Document Cards
export const E_DOCUMENT_CARD: ElementTransformer = {
dependencies: [DocumentCardNode],
diff --git a/js/app/tsconfig.json b/js/app/tsconfig.json
index d857c7c87b..9dd9ae1c4b 100644
--- a/js/app/tsconfig.json
+++ b/js/app/tsconfig.json
@@ -195,6 +195,9 @@
],
"@ui/*": [
"./packages/ui/*"
+ ],
+ "@block-theme/*": [
+ "./packages/block-theme/*"
]
},
"rootDir": ".",
diff --git a/js/app/vitest.config.ts b/js/app/vitest.config.ts
index b7eb56ad70..cb660b203b 100644
--- a/js/app/vitest.config.ts
+++ b/js/app/vitest.config.ts
@@ -51,6 +51,13 @@ export default defineConfig({
name: 'lexical-core',
},
},
+ {
+ extends: './packages/lexical-core/vitest.config.ts',
+ test: {
+ include: ['packages/block-theme/**/*.{test,spec}.{ts,tsx}'],
+ name: 'block-theme',
+ },
+ },
{
extends: './packages/core/vitest.config.ts',
test: {