Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(md): tag-mentions, tag ui improvements (#4901)
Seamusc210e4d68e4d
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsxindex dbbea47c81..6ca3dce0e0 100644--- a/apps/web/src/features/block-md/component/ComposeTask.tsx+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx@@ -3,13 +3,16 @@ import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';+import { TagsMenu } from '@core/component/LexicalMarkdown/component/menu/TagsMenu';import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';import {autoRegister,emojisPlugin,singleLinePlugin,+ tagsPlugin,} from '@core/component/LexicalMarkdown/plugins';import { addMediaFromFile } from '@core/component/LexicalMarkdown/plugins/media';+import type { TagMentionLifecycle } from '@core/component/LexicalMarkdown/plugins/tags';import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';import {$getCaretRect,@@ -18,6 +21,7 @@ import {isRectFlushWith,trimWhitespace,} from '@core/component/LexicalMarkdown/utils';+import type { PortalScope } from '@core/component/ScopedPortal';import { toast } from '@core/component/Toast/Toast';import { useUserId } from '@core/context/user';import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';@@ -63,6 +67,7 @@ import {COMMAND_PRIORITY_NORMAL,KEY_ARROW_DOWN_COMMAND,KEY_ARROW_RIGHT_COMMAND,+ KEY_BACKSPACE_COMMAND,KEY_ENTER_COMMAND,KEY_ESCAPE_COMMAND,type LexicalEditor,@@ -98,6 +103,7 @@ const COMPOSER_PROPERTIES = [SYSTEM_PROPERTY_IDS.DUE_DATE,];const COMPOSER_PROPERTY_SET = new Set<string>(COMPOSER_PROPERTIES);+type ComposerTagLayoutMode = 'bottom' | 'title';function composerTitleNavigationPlugin(bodyEditor: Accessor<LexicalEditor | undefined>,@@ -157,6 +163,33 @@ function composerTitleNavigationPlugin();}+function isTitleSelectionAtStart() {+ const selection = $getSelection();+ if (+ !$isRangeSelection(selection) ||+ !selection.isCollapsed() ||+ selection.anchor.offset !== 0+ ) {+ return false;+ }++ const root = $getRoot();+ let topLevel = selection.anchor.getNode();+ while (topLevel.getParent() !== root) {+ const parent = topLevel.getParent();+ if (!parent) return false;+ topLevel = parent;+ }++ let previous = topLevel.getPreviousSibling();+ while (previous) {+ if (previous.getTextContent().length > 0) return false;+ previous = previous.getPreviousSibling();+ }++ return true;+}+function ComposeTaskTitleEditor(props: {value: Accessor<string>;onChange: (value: string) => void;@@ -164,6 +197,9 @@ function ComposeTaskTitleEditor(props: {bodyEditor: Accessor<LexicalEditor | undefined>;containerRef: Accessor<HTMLDivElement | undefined>;onUserInput: () => void;+ onTagSelected: (tag: TagMentionLifecycle) => void;+ onDeleteTagsAtStart: () => boolean;+ portalScope?: PortalScope;}) {const [state, setState] = createSignal(props.value());const [showPlaceholder, setShowPlaceholder] = createSignal(@@ -178,6 +214,9 @@ function ComposeTaskTitleEditor(props: {});const emojiMenuOperations = createMenuOperations();+ const tagMenuOperations = createMenuOperations();+ const inlineMenuOpen = () =>+ emojiMenuOperations.isOpen() || tagMenuOperations.isOpen();initializeEditorEmpty(editor);forceSetTextContent(editor, props.value());@@ -188,11 +227,13 @@ function ComposeTaskTitleEditor(props: {.use(singleLinePlugin()).use(emojisPlugin({ menu: emojiMenuOperations })).use(- composerTitleNavigationPlugin(- props.bodyEditor,- emojiMenuOperations.isOpen- )+ tagsPlugin({+ menu: tagMenuOperations,+ insertTags: false,+ onCreateTag: props.onTagSelected,+ }))+ .use(composerTitleNavigationPlugin(props.bodyEditor, inlineMenuOpen)).state<string>(setState, 'plain');plugins.onUpdate(({ editorState }) => {@@ -226,15 +267,28 @@ function ComposeTaskTitleEditor(props: {});autoRegister(- editor.registerCommand(- KEY_ESCAPE_COMMAND,- (event) => {- props.containerRef()?.focus();- event?.preventDefault();- event?.stopPropagation();- return true;- },- COMMAND_PRIORITY_NORMAL+ mergeRegister(+ editor.registerCommand(+ KEY_BACKSPACE_COMMAND,+ (event) => {+ if (!isTitleSelectionAtStart()) return false;+ if (!props.onDeleteTagsAtStart()) return false;+ event?.preventDefault();+ event?.stopPropagation();+ return true;+ },+ COMMAND_PRIORITY_NORMAL+ ),+ editor.registerCommand(+ KEY_ESCAPE_COMMAND,+ (event) => {+ props.containerRef()?.focus();+ event?.preventDefault();+ event?.stopPropagation();+ return true;+ },+ COMMAND_PRIORITY_NORMAL+ )));@@ -248,7 +302,7 @@ function ComposeTaskTitleEditor(props: {};return (- <div class="relative w-full mb-4">+ <div class="relative w-full"><divcontentEditable={!props.disabled()}class="ph-no-capture w-full text-xl font-medium outline-none whitespace-pre-wrap wrap-break-words"@@ -260,6 +314,13 @@ function ComposeTaskTitleEditor(props: {editor={editor}menu={emojiMenuOperations}useBlockBoundary={true}+ portalScope={props.portalScope}+ />+ <TagsMenu+ editor={editor}+ menu={tagMenuOperations}+ useBlockBoundary={true}+ portalScope={props.portalScope}/><Show when={showPlaceholder()}><div class="pointer-events-none absolute top-1.5 text-xl font-medium text-ink-placeholder">@@ -464,6 +525,8 @@ export function ComposeTask(props: ComposeTaskProps) {const [createMore, setCreateMore] = createSignal(false);const [errorMessage, setErrorMessage] = createSignal<string>('');const [isCreating, setIsCreating] = createSignal(false);+ const [tagLayoutMode, setTagLayoutMode] =+ createSignal<ComposerTagLayoutMode>('bottom');let attachInputRef: HTMLInputElement | undefined;const handleAttachFiles = async (event: Event) => {@@ -616,6 +679,26 @@ export function ComposeTask(props: ComposeTaskProps) {});+ const clearComposerTags = () => {+ const next = structuredClone(unwrap(propertyValues));+ for (const [definitionId, value] of Object.entries(next)) {+ if (+ value.valueType === 'SELECT_STRING' &&+ !COMPOSER_PROPERTY_SET.has(definitionId)+ ) {+ delete next[definitionId];+ }+ }+ setPropertyValues(reconcile(next));+ };++ const deleteTitleTagsAtStart = () => {+ if (tagLayoutMode() !== 'title') return false;+ clearComposerTags();+ setTagLayoutMode('bottom');+ return true;+ };+const showTaskCreatedToast = async (documentId: string) => {// Auto-copy link to clipboardconst url = buildSimpleEntityUrl({ type: 'task', id: documentId });@@ -743,6 +826,7 @@ export function ComposeTask(props: ComposeTaskProps) {setTitle('');setContent('');setPropertyValues(reconcile(getDefaultPropertyValues()));+ setTagLayoutMode('bottom');setIsDraftLoaded(false);const ed = bodyEditor();ed && initializeEditorEmpty(ed);@@ -834,6 +918,7 @@ export function ComposeTask(props: ComposeTaskProps) {setTitle('');setContent('');setPropertyValues(reconcile(getDefaultPropertyValues()));+ setTagLayoutMode('bottom');setIsDraftLoaded(false);const ed = bodyEditor();ed && initializeEditorEmpty(ed);@@ -884,6 +969,11 @@ export function ComposeTask(props: ComposeTaskProps) {const editorConfig = buildConfig('markdown').withMentions()+ .withTags({+ onCreate: (tag) => {+ void composerTags.applyTag(tag.scope, tag.optionId);+ },+ }).withEmojis().withActions().withCode()@@ -902,10 +992,12 @@ export function ComposeTask(props: ComposeTaskProps) {const editor = editorConfig.buildHandle().lexical;setBodyEditor(editor);+ const portalScope = (): PortalScope =>+ splitPanel.handle.isPopover() ? 'local' : 'block';return (<div- class="flex flex-col relative h-full max-h-full min-h-0 p-4 gap-4"+ class="portal-scope flex flex-col relative h-full max-h-full min-h-0 p-4 gap-4"tabIndex={-1}ref={setContainerRef}>@@ -948,7 +1040,14 @@ export function ComposeTask(props: ComposeTaskProps) {</Show></div><div class="flex-1 min-h-0 flex flex-col overflow-hidden">- <div class="shrink-0 flex gap-2 items-start px-2">+ <div class="shrink-0 flex gap-2 items-center px-2 mb-4">+ <Show when={tagLayoutMode() === 'title'}>+ <InlineTagsPill+ docTags={composerTags}+ showPlaceholder+ class="shrink-0"+ />+ </Show><ComposeTaskTitleEditorvalue={title}onChange={setTitle}@@ -960,6 +1059,12 @@ export function ComposeTask(props: ComposeTaskProps) {setErrorMessage('');}}}+ onTagSelected={(tag) => {+ setTagLayoutMode('title');+ void composerTags.applyTag(tag.scope, tag.optionId);+ }}+ onDeleteTagsAtStart={deleteTitleTagsAtStart}+ portalScope={portalScope()}/></div>@@ -974,7 +1079,7 @@ export function ComposeTask(props: ComposeTaskProps) {: initialState.content || undefined}placeholder={props.placeholder ?? 'Add description...'}- portalScope={splitPanel.handle.isPopover() ? 'local' : 'block'}+ portalScope={portalScope()}/></Scroll></div>@@ -1030,7 +1135,9 @@ export function ComposeTask(props: ComposeTaskProps) {/>)}</For>- <InlineTagsPill docTags={composerTags} showPlaceholder />+ <Show when={tagLayoutMode() === 'bottom'}>+ <InlineTagsPill docTags={composerTags} showPlaceholder />+ </Show></div><Modals /></PropertiesProvider>diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsxindex a508415a5f..49322cf41e 100644--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx@@ -31,6 +31,7 @@ import TableActionMenu, {menuButtonRefSignal,tableCellNodeKeySignal,} from '@core/component/LexicalMarkdown/component/menu/TableActionMenu';+import { TagsMenu } from '@core/component/LexicalMarkdown/component/menu/TagsMenu';import { DraggableBlockMenu } from '@core/component/LexicalMarkdown/component/misc/DraggableBlockMenu';import { DragInsertIndicator } from '@core/component/LexicalMarkdown/component/misc/DragInsertIndicator';import { TableCellResizer } from '@core/component/LexicalMarkdown/component/misc/TableCellResizer';@@ -66,6 +67,7 @@ import {tableActionMenuPlugin,tableCellResizerPlugin,tablePlugin,+ tagsPlugin,textPastePlugin,wordcountPlugin,} from '@core/component/LexicalMarkdown/plugins';@@ -165,6 +167,8 @@ import {peerIdPlugin,} from '@macro-inc/lexical-core';import WarningIcon from '@phosphor/warning.svg';+import { useDocTags } from '@property/tags';+import { EntityType } from '@service-properties/generated/schemas/entityType';import { onElementConnect } from '@solid-primitives/lifecycle';import { isIOS } from '@solid-primitives/platform';import { createCallback } from '@solid-primitives/rootless';@@ -224,6 +228,10 @@ export function MarkdownEditor(props: {const blockId = useBlockId();const userId = useUserId();const blockName = useMaybeBlockAliasedName();+ const documentTags = useDocTags(+ blockId,+ blockName === 'task' ? EntityType.TASK : EntityType.DOCUMENT+ );const mdDocumentName = useBlockDocumentName('');@@ -306,6 +314,7 @@ export function MarkdownEditor(props: {autoRegister(editorFocusSignal(editor, setEditorFocus));const mentionsMenuOperations = createMenuOperations();+ const tagsMenuOperations = createMenuOperations();const emojiMenuOperations = createMenuOperations();const actionsMenuOperations = createMenuOperations();const snippetsMenuOperations = createMenuOperations();@@ -541,6 +550,15 @@ export function MarkdownEditor(props: {sourceDocumentId: blockId,}))+ .use(+ tagsPlugin({+ menu: tagsMenuOperations,+ peerIdValidator: peerIdValidator(),+ onCreateTag: (tag) => {+ void documentTags.applyTag(tag.scope, tag.optionId);+ },+ })+ ).use(snippetsPlugin({menu: snippetsMenuOperations,@@ -1069,6 +1087,12 @@ export function MarkdownEditor(props: {showOpenTabs/>+ <TagsMenu+ editor={editor}+ menu={tagsMenuOperations}+ useBlockBoundary={true}+ />+<SnippetsMenueditor={editor}menu={snippetsMenuOperations}diff --git a/apps/web/src/features/block-md/component/TitleEditor.tsx b/apps/web/src/features/block-md/component/TitleEditor.tsxindex 28a22acf2a..9237d561ae 100644--- a/apps/web/src/features/block-md/component/TitleEditor.tsx+++ b/apps/web/src/features/block-md/component/TitleEditor.tsx@@ -1,10 +1,16 @@-import { createBlockSignal, useBlockAliasedName } from '@core/block';+import {+ createBlockSignal,+ useBlockAliasedName,+ useBlockId,+} from '@core/block';import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';+import { TagsMenu } from '@core/component/LexicalMarkdown/component/menu/TagsMenu';import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';import {autoRegister,emojisPlugin,singleLinePlugin,+ tagsPlugin,} from '@core/component/LexicalMarkdown/plugins/';import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';import {@@ -17,6 +23,8 @@ import {import { blockNameToDefaultFile } from '@core/constant/allBlocks';import { useCanEdit } from '@core/signal/permissions';import { mergeRegister } from '@lexical/utils';+import { useDocTags } from '@property/tags';+import { EntityType } from '@service-properties/generated/schemas/entityType';import { onElementConnect } from '@solid-primitives/lifecycle';import { debounce } from '@solid-primitives/scheduled';import {@@ -147,7 +155,12 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {const [titlePlaceholder, _setTitlePlaceholder] = TitlePlaceholderSignal;const [titleFocused, setTitleFocused] = createSignal(false);+ const blockId = useBlockId();const blockName = useBlockAliasedName();+ const documentTags = useDocTags(+ blockId,+ blockName === 'task' ? EntityType.TASK : EntityType.DOCUMENT+ );const titlePlaceholderFallback = blockNameToDefaultFile(blockName);let pendingRename:@@ -188,6 +201,9 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {setMdData('titleEditor', editor);const emojiMenuOperations = createMenuOperations();+ const tagMenuOperations = createMenuOperations();+ const inlineMenuOpen = () =>+ emojiMenuOperations.isOpen() || tagMenuOperations.isOpen();plugins.plainText()@@ -198,6 +214,15 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {menu: emojiMenuOperations,}))+ .use(+ tagsPlugin({+ menu: tagMenuOperations,+ insertTags: false,+ onCreateTag: (tag) => {+ void documentTags.applyTag(tag.scope, tag.optionId);+ },+ })+ ).state<string>(setState, 'plain');plugins.onUpdate(({ editorState }) => {@@ -214,11 +239,7 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {createEffect(() => {const mainDocumentEditor = mdData.editor;if (!mainDocumentEditor) return;- plugins.use(- titleNavigationPlugin(mainDocumentEditor, () =>- emojiMenuOperations.isOpen()- )- );+ plugins.use(titleNavigationPlugin(mainDocumentEditor, inlineMenuOpen));});function onBlur() {@@ -274,7 +295,7 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {);createEffect(() => {- if (emojiMenuOperations.isOpen()) return;+ if (inlineMenuOpen()) return;const currentState = state();if (!untrack(initialized)) {setInitialized(true);@@ -335,6 +356,11 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {menu={emojiMenuOperations}useBlockBoundary={true}/>+ <TagsMenu+ editor={editor}+ menu={tagMenuOperations}+ useBlockBoundary={true}+ /><Show when={showFallback()}><div class="text-2xl font-semibold text-ink-placeholder absolute top-0 pointer-events-none">{titlePlaceholder() ?? titlePlaceholderFallback}diff --git a/apps/web/src/features/property/tags/TagPicker.tsx b/apps/web/src/features/property/tags/TagPicker.tsxindex 86f2d9ccec..1dc0e0c9dc 100644--- a/apps/web/src/features/property/tags/TagPicker.tsx+++ b/apps/web/src/features/property/tags/TagPicker.tsx@@ -1,4 +1,5 @@import { Popover } from '@kobalte/core/popover';+import CircleDashedEmpty from '@phosphor/circle-dashed.svg';import PlusIcon from '@phosphor/plus.svg';import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';import {@@ -332,7 +333,12 @@ function TagPickerBody(props: {};const showCreateRow = () =>createLabel().length >= 2 && !exactTagMatchExists();+ const showClearAllRow = () =>+ selectedIds().size > 0 && !search().trim() && !createStep();+ const itemIndex = (item: TagOptionItem) => filteredItems().indexOf(item);const createRowIndex = () => filteredItems().length;+ const clearAllRowIndex = () =>+ filteredItems().length + (showCreateRow() ? 1 : 0);const teamName = () => currentTeamQuery.data?.team.name?.trim() || 'Team';const scopeOptions = createMemo<{ scope: TagScope; label: string }[]>(() => [{ scope: 'user', label: 'Personal' },@@ -428,13 +434,22 @@ function TagPickerBody(props: {};const dropdown = useDropdownSearch({- itemCount: () => filteredItems().length + (showCreateRow() ? 1 : 0),+ itemCount: () =>+ filteredItems().length ++ (showCreateRow() ? 1 : 0) ++ (showClearAllRow() ? 1 : 0),onSelect: (index, event) => {if (showCreateRow() && index === createRowIndex()) {beginCreate();return;}+ if (showClearAllRow() && index === clearAllRowIndex()) {+ setSelectedIds(new Set<string>());+ void saveAndClose();+ return;+ }+const item = filteredItems()[index];if (!item) return;@@ -509,7 +524,11 @@ function TagPickerBody(props: {style={{ 'max-height': `${MAX_LIST_HEIGHT}px` }}><Show- when={filteredItems().length > 0 || showCreateRow()}+ when={+ showClearAllRow() ||+ filteredItems().length > 0 ||+ showCreateRow()+ }fallback={<div class="px-2 py-4 text-center text-ink-muted">{initialTagState().items.length === 0@@ -522,12 +541,11 @@ function TagPickerBody(props: {{(item) => (<TagPickerRowitem={item}- index={filteredItems().indexOf(item)}+ index={itemIndex(item)}teamName={teamName()}checked={isSelected(item.option.id)}selected={- dropdown.selectedIndex() ===- filteredItems().indexOf(item)+ dropdown.selectedIndex() === itemIndex(item)}onSelect={(event) => {toggleSelected(item.option.id);@@ -535,9 +553,7 @@ function TagPickerBody(props: {}}onMouseEnter={() => {if (!dropdown.keyboardMode()) {- dropdown.setSelectedIndex(- filteredItems().indexOf(item)- );+ dropdown.setSelectedIndex(itemIndex(item));}}}/>@@ -558,12 +574,11 @@ function TagPickerBody(props: {{(item) => (<TagPickerRowitem={item}- index={filteredItems().indexOf(item)}+ index={itemIndex(item)}teamName={teamName()}checked={isSelected(item.option.id)}selected={- dropdown.selectedIndex() ===- filteredItems().indexOf(item)+ dropdown.selectedIndex() === itemIndex(item)}onSelect={(event) => {toggleSelected(item.option.id);@@ -571,9 +586,7 @@ function TagPickerBody(props: {}}onMouseEnter={() => {if (!dropdown.keyboardMode()) {- dropdown.setSelectedIndex(- filteredItems().indexOf(item)- );+ dropdown.setSelectedIndex(itemIndex(item));}}}/>@@ -596,6 +609,32 @@ function TagPickerBody(props: {}}/></Show>+ <Show when={showClearAllRow()}>+ <div class="my-1 border-t border-edge-muted" />+ <div data-tag-index={clearAllRowIndex()}>+ <DropdownSelectableRow+ isSelected={+ dropdown.selectedIndex() === clearAllRowIndex()+ }+ onClick={() => {+ setSelectedIds(new Set<string>());+ void saveAndClose();+ }}+ onMouseEnter={() => {+ if (!dropdown.keyboardMode()) {+ dropdown.setSelectedIndex(clearAllRowIndex());+ }+ }}+ >+ <CircleDashedEmpty class="size-3 shrink-0 text-ink-extra-muted" />+ <div class="min-w-0 flex-1 text-left">+ <p class="truncate text-ink-muted">+ Clear all tags+ </p>+ </div>+ </DropdownSelectableRow>+ </div>+ </Show></Show></div></div>diff --git a/apps/web/src/features/property/tags/tagNavigation.ts b/apps/web/src/features/property/tags/tagNavigation.tsindex cddc4bb3c2..723917aa4a 100644--- a/apps/web/src/features/property/tags/tagNavigation.ts+++ b/apps/web/src/features/property/tags/tagNavigation.ts@@ -60,3 +60,17 @@ export function buildTaggedItemsSplitOptions(referredFrom: null,};}++export function navigateToTag(+ openWithSplit: (+ content: SplitContent,+ options?: OpenWithSplitOptions+ ) => unknown,+ tag: TagNavigationTarget,+ options: Pick<OpenWithSplitOptions, 'handle'> = {}+) {+ return openWithSplit(+ buildTaggedItemsSplitContent(tag),+ buildTaggedItemsSplitOptions(options)+ );+}diff --git a/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.ts b/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.tsindex a91200c9f5..ae790cbeac 100644--- a/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.ts+++ b/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.ts@@ -16,6 +16,7 @@ const OTHER_MACRO_XML_TAGS = ['<m-pr-mention>{"id":"foreign-1","label":"macro/macro#123"}</m-pr-mention>','<m-group-mention>{"groupAlias":"here"}</m-group-mention>','<m-theme-mention>{"name":"onboarding","data":{}}</m-theme-mention>',+ '<m-tag>{"optionId":"tag-1","propertyDefinitionId":"prop-1","scope":"team","name":"Launch"}</m-tag>','<m-await>{"awaitId":"a1","text":"Waiting","inline":true}</m-await>','<m-future-widget>{"value":1}</m-future-widget>',];diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.tsindex 11264d039b..f924dc41b2 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts@@ -18,6 +18,7 @@ import type {LinksOptions,MediaOptions,MentionsOptions,+ TagsOptions,} from './types';export class EditorConfigBuilder implements EditorBuilder {@@ -55,6 +56,13 @@ export class EditorConfigBuilder implements EditorBuilder {return this;}+ withTags(config: TagsOptions = {}): this {+ this.state.tags = {+ ...config,+ };+ return this;+ }+withEmojis(config: EmojisOptions = {}): this {this.state.emojis = config;return this;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsxindex 75ad488f40..ed8587e73f 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx@@ -26,6 +26,7 @@ import { FloatingFormatMenu } from '../component/menu/FloatingFormatMenu';import { FloatingLinkMenu } from '../component/menu/FloatingLinkMenu';import { MentionsMenu } from '../component/menu/MentionsMenu';import { SnippetsMenu } from '../component/menu/SnippetsMenu';+import { TagsMenu } from '../component/menu/TagsMenu';import { DragInsertIndicator } from '../component/misc/DragInsertIndicator';import { FloatingMenuGroup } from '../context/FloatingMenuContext';import { LexicalWrapperContext } from '../context/LexicalWrapperContext';@@ -267,6 +268,17 @@ export const MarkdownShell: Component<)}</Show>+ <Show when={state.tagsMenuOps}>+ {(menu) => (+ <TagsMenu+ editor={editor}+ menu={menu()}+ useBlockBoundary={false}+ portalScope={props.portalScope}+ />+ )}+ </Show>+<Show when={state.actionsMenuOps}>{(menu) => (<ActionMenudiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.tsindex 93ac5734f9..cb969da243 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts@@ -23,6 +23,7 @@ import {singleLinePlugin,snippetsPlugin,tabIndentationPlugin,+ tagsPlugin,textPastePlugin,} from '../plugins';import { checkboxToTaskPlugin } from '../plugins/checkbox-to-task';@@ -73,6 +74,7 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {? createMenuOperations(): undefined;const mentionsMenuOps = config.mentions ? createMenuOperations() : undefined;+ const tagsMenuOps = config.tags ? createMenuOperations() : undefined;const emojisMenuOps = config.emojis ? createMenuOperations() : undefined;// Snippets (`;` menu) follow mentions: any markdown area that can @-mention// can also insert snippets, unless explicitly opted out. Editors with a@@ -163,6 +165,18 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {);}+ if (config.tags && tagsMenuOps) {+ plugins.use(+ tagsPlugin({+ menu: tagsMenuOps,+ insertTags: config.tags.insertTags,+ onCreateTag: config.tags.onCreate,+ onRemoveTag: config.tags.onRemove,+ setTags: config.tags.setTags,+ })+ );+ }+if (emojisMenuOps) {plugins.use(emojisPlugin({ menu: emojisMenuOps }));}@@ -270,6 +284,7 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {ignoreKeys: () =>(actionsMenuOps?.isOpen() ?? false) ||(mentionsMenuOps?.isOpen() ?? false) ||+ (tagsMenuOps?.isOpen() ?? false) ||(emojisMenuOps?.isOpen() ?? false) ||(snippetsMenuOps?.isOpen() ?? false),})@@ -292,10 +307,11 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {getLexical: () => editor,isInlineMenuOpen: () => {const mentions = mentionsMenuOps?.isOpen() ?? false;+ const tags = tagsMenuOps?.isOpen() ?? false;const emojis = emojisMenuOps?.isOpen() ?? false;const actions = actionsMenuOps?.isOpen() ?? false;const snippets = snippetsMenuOps?.isOpen() ?? false;- return mentions || emojis || actions || snippets;+ return mentions || tags || emojis || actions || snippets;},};@@ -314,6 +330,7 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {markdownState,actionsMenuOps,mentionsMenuOps,+ tagsMenuOps,emojisMenuOps,snippetsMenuOps,accessoryStore,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.tsindex c91eb90fae..0f0959cab2 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts@@ -17,6 +17,7 @@ import type {SelectionData,} from '../plugins';import type { Action } from '../plugins/actions/types';+import type { TagMentionLifecycle } from '../plugins/tags';import type { createMenuOperations } from '../shared/inlineMenu';import type { UserMentionRecord } from '../utils/mentionsUtils';@@ -46,6 +47,14 @@ export interface MentionsOptions {disableMentionTracking?: boolean;}+export interface TagsOptions {+ /** Insert inline tag mentions into the editor document. Defaults to true. */+ insertTags?: boolean;+ onCreate?: (tag: TagMentionLifecycle) => void;+ onRemove?: (tag: TagMentionLifecycle) => void;+ setTags?: (tags: ReadonlySet<TagMentionLifecycle>) => void;+}+/** Intentional extension point — no options yet. */export type EmojisOptions = Record<string, never>;@@ -128,6 +137,7 @@ export interface EditorConfig {type: EditorType;namespace: string;mentions?: MentionsOptions;+ tags?: TagsOptions;/** Snippets (`;` menu) follow mentions by default; pass false to opt out. */snippets?: false;emojis?: EmojisOptions;@@ -163,6 +173,7 @@ export interface EditorInternals {markdownState: () => string;actionsMenuOps: ReturnType<typeof createMenuOperations> | undefined;mentionsMenuOps: ReturnType<typeof createMenuOperations> | undefined;+ tagsMenuOps: ReturnType<typeof createMenuOperations> | undefined;emojisMenuOps: ReturnType<typeof createMenuOperations> | undefined;snippetsMenuOps: ReturnType<typeof createMenuOperations> | undefined;accessoryStore: ReturnType<typeof createAccessoryStore>[0] | undefined;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 324f0121a7..0f9ab8da52 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -27,6 +27,7 @@ import {type PasteNode,type SnapshotNode,SupportedNodeTypes,+ type TagMentionNode,type ThemeMentionNode,type UnknownMentionNode,type UserMentionNode,@@ -84,6 +85,7 @@ import { MarkdownImage as ImageDecorator } from '../decorator/MarkdownImage';import { MarkdownVideo as VideoDecorator } from '../decorator/MarkdownVideo';import { PasteNode as PasteNodeDecorator } from '../decorator/PasteNode';import { Snapshot as SnapshotDecorator } from '../decorator/Snapshot';+import { TagMention as TagMentionDecorator } from '../decorator/TagMention';import { ThemeMention as ThemeMentionDecorator } from '../decorator/ThemeMention';import { UnknownMention as UnknownMentionDecorator } from '../decorator/UnknownMention';import { UserMention as UserMentionDecorator } from '../decorator/UserMention';@@ -354,6 +356,20 @@ const ThemeMention: RenderableEntity<ThemeMentionNode> = {),};+const TagMention: RenderableEntity<TagMentionNode> = {+ guard: (node: LexicalNode): node is TagMentionNode =>+ node.__type === 'tag-mention',+ render: (props) => (+ <span>+ {TagMentionDecorator({+ ...props.node.exportComponentProps(),+ key: props.node.getKey(),+ theme: props.theme,+ })}+ </span>+ ),+};+const Watermark: RenderableEntity<WatermarkNode> = {guard: (node: LexicalNode): node is WatermarkNode =>node.__type === 'watermark',@@ -780,6 +796,7 @@ const InlineEntities: Array<RenderableEntity> = [HorizontalRule,Equation,ThemeMention,+ TagMention,UnknownMention,Watermark,Paste,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/TagMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/TagMention.tsxnew file mode 100644index 0000000000..df5241181b--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/TagMention.tsx@@ -0,0 +1,137 @@+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';+import {+ $isTagMentionNode,+ type TagMentionDecoratorProps,+} from '@macro-inc/lexical-core';+import { TagDot } from '@property/tags/TagDot';+import { navigateToTag } from '@property/tags/tagNavigation';+import { useTagsQuery } from '@queries/properties/tags';+import {+ $getNodeByKey,+ COMMAND_PRIORITY_NORMAL,+ KEY_ENTER_COMMAND,+} from 'lexical';+import { createEffect, createMemo, useContext } from 'solid-js';+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';+import { autoRegister } from '../../plugins';+import { MentionTooltip } from './MentionTooltip';++function optionLabel(value: unknown): string | undefined {+ if (+ typeof value === 'object' &&+ value !== null &&+ 'type' in value &&+ value.type === 'string' &&+ 'value' in value &&+ typeof value.value === 'string'+ ) {+ return value.value;+ }+ return undefined;+}++export function TagMention(props: TagMentionDecoratorProps) {+ const lexicalWrapper = useContext(LexicalWrapperContext);+ const editor = lexicalWrapper?.editor;+ const selection = () => lexicalWrapper?.selection;+ const tagsQuery = useTagsQuery();+ const split = useSplitLayout();+ const panel = useSplitPanel();++ const isSelectedAsNode = createMemo(() => {+ const sel = selection();+ if (!sel) return false;+ return sel.type === 'node' && sel.nodeKeys.has(props.key);+ });++ const resolvedTag = createMemo(() => {+ for (const set of tagsQuery.data ?? []) {+ for (const option of set.options) {+ if (option.id !== props.optionId) continue;+ return {+ optionId: option.id,+ propertyDefinitionId: option.propertyDefinitionId,+ scope: set.scope,+ name: optionLabel(option.value) ?? props.name,+ color: option.color ?? undefined,+ };+ }+ }+ return props;+ });++ createEffect(() => {+ const tag = resolvedTag();+ if (+ tag.propertyDefinitionId === props.propertyDefinitionId &&+ tag.scope === props.scope &&+ tag.name === props.name &&+ tag.color === props.color+ ) {+ return;+ }++ editor?.update(+ () => {+ const node = $getNodeByKey(props.key);+ if (!$isTagMentionNode(node)) return;+ node.setTagInfo({+ propertyDefinitionId: tag.propertyDefinitionId,+ scope: tag.scope,+ name: tag.name,+ color: tag.color,+ });+ },+ { tag: 'historic', discrete: true }+ );+ });++ const open = () => {+ const tag = resolvedTag();+ navigateToTag(split.openWithSplit, tag, { handle: panel?.handle });+ };++ if (editor) {+ autoRegister(+ editor.registerCommand(+ KEY_ENTER_COMMAND,+ (event) => {+ if (!isSelectedAsNode()) return false;+ event?.preventDefault();+ event?.stopPropagation();+ open();+ return true;+ },+ COMMAND_PRIORITY_NORMAL+ )+ );+ }++ return (+ <span class="relative">+ <span+ data-tag-mention="true"+ data-tag-option-id={props.optionId}+ data-tag-property-definition-id={resolvedTag().propertyDefinitionId}+ data-tag-name={resolvedTag().name}+ data-tag-scope={resolvedTag().scope}+ data-tag-color={resolvedTag().color}+ class="pointer-events-auto p-0.5 cursor-default rounded-xs hover:bg-hover focus:bg-active"+ classList={{ 'bg-active text-ink': isSelectedAsNode() }}+ onClick={(event) => {+ event.stopPropagation();+ open();+ }}+ >+ <span class="relative inline-flex -top-px mr-1">+ <TagDot color={resolvedTag().color} class="size-[0.5em]" />+ </span>+ <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">+ {resolvedTag().name}+ </span>+ </span>+ <MentionTooltip show={isSelectedAsNode()} text="Open" />+ </span>+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TagsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TagsMenu.tsxnew file mode 100644index 0000000000..16ea3883c6--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TagsMenu.tsx@@ -0,0 +1,576 @@+import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';+import clickOutside from '@core/directive/clickOutside';+import PlusIcon from '@phosphor/plus.svg';+import { TagDot } from '@property/tags/TagDot';+import { DEFAULT_TAG_COLOR, type TAG_COLORS } from '@property/tags/tagColors';+import { useAddPropertyOptionMutation } from '@queries/properties/options';+import {+ invalidateTags,+ useEnsureTagSetMutation,+ useTagsQuery,+} from '@queries/properties/tags';+import { useCurrentTeamQuery } from '@queries/team/teams';+import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';+import type { TagScope } from '@service-properties/generated/schemas/tagScope';+import { Surface } from '@ui';+import type { LexicalEditor } from 'lexical';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ type JSX,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';+import { floatWithSelection } from '../../directive/floatWithSelection';+import {+ CLOSE_INLINE_SEARCH_COMMAND,+ REMOVE_INLINE_SEARCH_COMMAND,+} from '../../plugins';+import { INSERT_TAG_MENTION_COMMAND } from '../../plugins/tags';+import type { MenuOperations } from '../../shared/inlineMenu';+import { useMenuKeyboardNavigation } from './useMenuKeyboardNavigation';++type TagMenuItem = {+ optionId: string;+ propertyDefinitionId: string;+ scope: 'user' | 'team';+ name: string;+ color?: string;+};++type CreateStep = 'color' | 'scope';++type PendingTagCreate = {+ scope: TagScope;+ value: string;+ color: string;+};++const TAG_COLOR_OPTIONS = [+ { color: '#E5484D', name: 'Red' },+ { color: '#E54D2E', name: 'Tomato' },+ { color: '#F76B15', name: 'Orange' },+ { color: '#FFB224', name: 'Amber' },+ { color: '#F5D90A', name: 'Yellow' },+ { color: '#46A758', name: 'Green' },+ { color: '#12A594', name: 'Teal' },+ { color: '#0091FF', name: 'Blue' },+ { color: '#3E63DD', name: 'Indigo' },+ { color: '#8E4EC6', name: 'Purple' },+ { color: '#E93D82', name: 'Pink' },+ { color: '#889096', name: 'Gray' },+] as const satisfies readonly {+ color: (typeof TAG_COLORS)[number];+ name: string;+}[];++function optionLabel(value: unknown): string | undefined {+ if (+ typeof value === 'object' &&+ value !== null &&+ 'type' in value &&+ value.type === 'string' &&+ 'value' in value &&+ typeof value.value === 'string'+ ) {+ return value.value;+ }+ return undefined;+}++function nextDisplayOrder(options: PropertyOptionResponse[]): number {+ return (+ options.reduce((max, option) => Math.max(max, option.displayOrder), -1) + 1+ );+}++function ScrollIntoViewOnSelect(props: {+ selected: boolean;+ children: JSX.Element;+}) {+ let ref: HTMLDivElement | undefined;++ createEffect(() => {+ if (props.selected && ref) {+ ref.scrollIntoView({ block: 'nearest' });+ }+ });++ return <div ref={ref}>{props.children}</div>;+}++export function TagsMenu(props: {+ editor: LexicalEditor;+ menu: MenuOperations;+ portalScope?: PortalScope;+ useBlockBoundary?: boolean;+}) {+ const tagsQuery = useTagsQuery();+ const currentTeamQuery = useCurrentTeamQuery();+ const addOption = useAddPropertyOptionMutation();+ const ensureTagSet = useEnsureTagSetMutation();+ const [mountSelection, setMountSelection] = createSignal<Selection | null>();+ const [menuAvailableHeight, setMenuAvailableHeight] = createSignal<+ number | undefined+ >();+ const [selectedIndex, setSelectedIndex] = createSignal(0);+ const [createStep, setCreateStep] = createSignal<CreateStep | null>(null);+ const [createDraftLabel, setCreateDraftLabel] = createSignal('');+ const [selectedColorIndex, setSelectedColorIndex] = createSignal(0);+ const [selectedScopeIndex, setSelectedScopeIndex] = createSignal(0);+ const [pendingCreate, setPendingCreate] =+ createSignal<PendingTagCreate | null>(null);++ const items = createMemo<TagMenuItem[]>(() => {+ const query = props.menu.searchTerm().trim().toLowerCase();+ return (tagsQuery.data ?? [])+ .flatMap((set) =>+ set.options.map((option) => ({+ optionId: option.id,+ propertyDefinitionId: option.propertyDefinitionId,+ scope: set.scope,+ name: optionLabel(option.value) ?? option.id,+ color: option.color ?? undefined,+ }))+ )+ .filter((tag) => !query || tag.name.toLowerCase().includes(query))+ .sort((a, b) => a.name.localeCompare(b.name));+ });++ const allItems = createMemo<TagMenuItem[]>(() =>+ (tagsQuery.data ?? []).flatMap((set) =>+ set.options.map((option) => ({+ optionId: option.id,+ propertyDefinitionId: option.propertyDefinitionId,+ scope: set.scope,+ name: optionLabel(option.value) ?? option.id,+ color: option.color ?? undefined,+ }))+ )+ );+ const createLabel = () => props.menu.searchTerm().trim();+ const exactTagMatchExists = () => {+ const label = createLabel().toLowerCase();+ return (+ !!label && allItems().some((tag) => tag.name.toLowerCase() === label)+ );+ };+ const showCreateRow = () =>+ createLabel().length >= 2 && !exactTagMatchExists();+ const createRowIndex = () => items().length;+ const itemCount = () => items().length + (showCreateRow() ? 1 : 0);+ const teamName = () => currentTeamQuery.data?.team.name?.trim() || 'Team';+ const scopeOptions = createMemo<{ scope: TagScope; label: string }[]>(() => [+ { scope: 'user', label: 'Personal' },+ { scope: 'team', label: `Shared with ${teamName()}` },+ ]);+ const createStepCount = () =>+ createStep() === 'color' ? TAG_COLOR_OPTIONS.length : scopeOptions().length;+ const selectedColor = () =>+ TAG_COLOR_OPTIONS[selectedColorIndex()]?.color ?? DEFAULT_TAG_COLOR;++ createEffect(() => {+ if (props.menu.isOpen()) {+ setMountSelection(document.getSelection());+ setSelectedIndex(0);+ } else {+ setMountSelection(null);+ setCreateStep(null);+ props.menu.setSearchTerm('');+ }+ });++ createEffect(() => {+ const count = itemCount();+ if (selectedIndex() >= count) setSelectedIndex(Math.max(0, count - 1));+ });++ const closeMenu = () => {+ props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);+ props.menu.setIsOpen(false);+ };++ const selectItem = (item: TagMenuItem | undefined) => {+ if (!item) {+ closeMenu();+ return;+ }+ props.editor.dispatchCommand(REMOVE_INLINE_SEARCH_COMMAND, undefined);+ props.editor.dispatchCommand(INSERT_TAG_MENTION_COMMAND, item);+ props.menu.setIsOpen(false);+ };++ const beginCreate = () => {+ const label = createLabel();+ if (!showCreateRow() || !label) return;+ setCreateDraftLabel(label);+ setSelectedColorIndex(0);+ setSelectedScopeIndex(0);+ setCreateStep('color');+ };++ const selectCurrent = () => {+ if (showCreateRow() && selectedIndex() === createRowIndex()) {+ beginCreate();+ return;+ }+ selectItem(items()[selectedIndex()]);+ };++ const createTag = async (scope: TagScope) => {+ const value = createDraftLabel().trim();+ if (!value) return;+ if (pendingCreate()) return;++ const creation: PendingTagCreate = {+ scope,+ value,+ color: selectedColor(),+ };+ setPendingCreate(creation);++ try {+ const provisioned = await ensureTagSet.mutateAsync({ scope });+ if (!provisioned.definition) return;++ const created = await addOption.mutateAsync({+ propertyDefinitionId: provisioned.definition.id,+ body: {+ type: 'select_string',+ option: {+ value,+ display_order: nextDisplayOrder(provisioned.options),+ color: creation.color,+ },+ },+ });+ invalidateTags();+ if (+ pendingCreate() !== creation ||+ !props.menu.isOpen() ||+ createStep() !== 'scope' ||+ scopeOptions()[selectedScopeIndex()]?.scope !== scope ||+ createDraftLabel().trim() !== value+ ) {+ return;+ }+ selectItem({+ optionId: created.id,+ propertyDefinitionId: created.property_definition_id,+ scope,+ name: value,+ color: created.color ?? creation.color,+ });+ } catch (error) {+ console.error('Failed to create tag', error);+ } finally {+ if (pendingCreate() === creation) {+ setPendingCreate(null);+ }+ }+ };++ const createStepUp = () => {+ const count = createStepCount();+ if (count === 0) return;+ if (createStep() === 'color') {+ setSelectedColorIndex((prev) => (prev - 1 + count) % count);+ } else {+ setSelectedScopeIndex((prev) => (prev - 1 + count) % count);+ }+ };++ const createStepDown = () => {+ const count = createStepCount();+ if (count === 0) return;+ if (createStep() === 'color') {+ setSelectedColorIndex((prev) => (prev + 1) % count);+ } else {+ setSelectedScopeIndex((prev) => (prev + 1) % count);+ }+ };++ const selectCreateStep = () => {+ if (createStep() === 'color') {+ setCreateStep('scope');+ return;+ }+ const scope = scopeOptions()[selectedScopeIndex()]?.scope;+ if (scope) void createTag(scope);+ };++ useMenuKeyboardNavigation({+ isActive: props.menu.isOpen,+ onUp: () => {+ if (createStep()) {+ createStepUp();+ return;+ }+ const count = itemCount();+ if (count === 0) return;+ setSelectedIndex((prev) => (prev - 1 + count) % count);+ },+ onDown: () => {+ if (createStep()) {+ createStepDown();+ return;+ }+ const count = itemCount();+ if (count === 0) return;+ setSelectedIndex((prev) => (prev + 1) % count);+ },+ onSelect: () => {+ if (createStep()) {+ selectCreateStep();+ } else {+ selectCurrent();+ }+ },+ onClose: closeMenu,+ onSpace: () => {+ if (!createStep() && props.menu.searchTerm() === '') {+ closeMenu();+ return false;+ }+ return !!createStep();+ },+ });++ const focusOut = () => closeMenu();++ onMount(() => {+ document.addEventListener('focusout', focusOut);+ onCleanup(() => document.removeEventListener('focusout', focusOut));+ });++ const contentMaxHeight = () => {+ const h = menuAvailableHeight();+ if (h === undefined) return '16rem';+ return `${Math.min(256, Math.max(0, h - 18))}px`;+ };++ return (+ <Show when={props.menu.isOpen()}>+ <ScopedPortal scope={props.portalScope}>+ <div+ class="w-64 max-w-[calc(100cqw-1rem-2px)] cursor-default select-none z-modal-content menu-open-animation"+ ref={(el) => {+ floatWithSelection(el, () => ({+ selection: mountSelection(),+ reactiveOnContainer: props.editor.getRootElement(),+ useBlockBoundary: props.useBlockBoundary,+ onAvailableHeight: setMenuAvailableHeight,+ }));+ clickOutside(el, () => () => closeMenu());+ }}+ >+ <Surface+ depth={2}+ class="py-1.5 shadow-lg shadow-drop-shadow rounded-xl"+ >+ <Show+ when={createStep()}+ fallback={+ <Show+ when={items().length > 0 || showCreateRow()}+ fallback={+ <div class="px-3 py-1 text-ink-extra-muted">No tags</div>+ }+ >+ <div+ class="overflow-y-auto scrollbar-hidden"+ style={{ 'max-height': contentMaxHeight() }}+ >+ <For each={items()}>+ {(item, index) => (+ <ScrollIntoViewOnSelect+ selected={selectedIndex() === index()}+ >+ <button+ type="button"+ class="w-[calc(100%-0.75rem)] flex items-center gap-2 px-2 py-1.5 mx-1.5 text-left text-sm rounded-lg"+ classList={{+ 'bg-hover': selectedIndex() === index(),+ }}+ onMouseEnter={() => setSelectedIndex(index())}+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ selectItem(item);+ }}+ >+ <TagDot color={item.color} />+ <span class="min-w-0 flex-1 truncate">+ {item.name}+ </span>+ <Show when={item.scope === 'team'}>+ <span class="max-w-20 shrink-0 truncate rounded-full border border-ink/5 px-1.5 py-0.5 text-[10px] leading-none text-ink-extra-muted">+ {teamName()}+ </span>+ </Show>+ </button>+ </ScrollIntoViewOnSelect>+ )}+ </For>+ <Show when={showCreateRow()}>+ <ScrollIntoViewOnSelect+ selected={selectedIndex() === createRowIndex()}+ >+ <button+ type="button"+ class="w-[calc(100%-0.75rem)] flex items-center gap-2 px-2 py-1.5 mx-1.5 text-left text-sm rounded-lg"+ classList={{+ 'bg-hover': selectedIndex() === createRowIndex(),+ }}+ onMouseEnter={() =>+ setSelectedIndex(createRowIndex())+ }+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ beginCreate();+ }}+ >+ <PlusIcon class="size-3 shrink-0 text-ink-muted" />+ <span class="min-w-0 truncate">+ Create tag "{createLabel()}"+ </span>+ </button>+ </ScrollIntoViewOnSelect>+ </Show>+ </div>+ </Show>+ }+ >+ {(step) => (+ <CreateTagFlow+ step={step()}+ label={createDraftLabel()}+ colorOptions={TAG_COLOR_OPTIONS}+ selectedColorIndex={selectedColorIndex()}+ scopeOptions={scopeOptions()}+ selectedScopeIndex={selectedScopeIndex()}+ pending={addOption.isPending || ensureTagSet.isPending}+ onColorMouseEnter={setSelectedColorIndex}+ onColorSelect={(index) => {+ setSelectedColorIndex(index);+ setCreateStep('scope');+ }}+ onScopeMouseEnter={setSelectedScopeIndex}+ onScopeSelect={(scope) => void createTag(scope)}+ />+ )}+ </Show>+ </Surface>+ </div>+ </ScopedPortal>+ </Show>+ );+}++function CreateTagFlow(props: {+ step: CreateStep;+ label: string;+ colorOptions: typeof TAG_COLOR_OPTIONS;+ selectedColorIndex: number;+ scopeOptions: { scope: TagScope; label: string }[];+ selectedScopeIndex: number;+ pending: boolean;+ onColorMouseEnter: (index: number) => void;+ onColorSelect: (index: number) => void;+ onScopeMouseEnter: (index: number) => void;+ onScopeSelect: (scope: TagScope) => void;+}) {+ return (+ <div class="p-1.5">+ <div class="px-2 pb-1 pt-1 text-xs text-ink-extra-muted">+ Create tag "{props.label}"+ </div>+ <Show+ when={props.step === 'color'}+ fallback={+ <For each={props.scopeOptions}>+ {(option, index) => (+ <ScrollIntoViewOnSelect+ selected={props.selectedScopeIndex === index()}+ >+ <button+ type="button"+ class="w-[calc(100%-0.75rem)] flex items-center gap-2 px-2 py-1.5 mx-1.5 text-left text-sm rounded-lg"+ classList={{+ 'bg-hover': props.selectedScopeIndex === index(),+ }}+ onMouseEnter={() => props.onScopeMouseEnter(index())}+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ props.onScopeSelect(option.scope);+ }}+ >+ <TagDot+ color={+ props.colorOptions[props.selectedColorIndex]?.color ??+ DEFAULT_TAG_COLOR+ }+ />+ <span class="min-w-0 flex-1 truncate">{option.label}</span>+ <Show+ when={props.pending && props.selectedScopeIndex === index()}+ >+ <span class="shrink-0 text-xs text-ink-muted">+ Creating...+ </span>+ </Show>+ </button>+ </ScrollIntoViewOnSelect>+ )}+ </For>+ }+ >+ <For each={props.colorOptions}>+ {(option, index) => (+ <ScrollIntoViewOnSelect+ selected={props.selectedColorIndex === index()}+ >+ <button+ type="button"+ class="w-[calc(100%-0.75rem)] flex items-center gap-2 px-2 py-1.5 mx-1.5 text-left text-sm rounded-lg"+ classList={{+ 'bg-hover': props.selectedColorIndex === index(),+ }}+ onMouseEnter={() => props.onColorMouseEnter(index())}+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ props.onColorSelect(index());+ }}+ >+ <TagDot color={option.color} />+ <span class="min-w-0 flex-1 truncate">{option.name}</span>+ </button>+ </ScrollIntoViewOnSelect>+ )}+ </For>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts b/apps/web/src/lib/core/component/LexicalMarkdown/init.tsindex 5ed2e95d2c..ddc3706679 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts@@ -13,6 +13,7 @@ import {PasteNode as PasteNodeClass,PullRequestMentionNode,SnapshotNode,+ TagMentionNode,ThemeMentionNode,UnknownMentionNode,UserMentionNode,@@ -38,6 +39,7 @@ import { MarkdownVideo } from './component/decorator/MarkdownVideo';import { PasteNode } from './component/decorator/PasteNode';import { PullRequestMention } from './component/decorator/PullRequestMention';import { Snapshot } from './component/decorator/Snapshot';+import { TagMention } from './component/decorator/TagMention';import { ThemeMention } from './component/decorator/ThemeMention';import { UnknownMention } from './component/decorator/UnknownMention';import { UserMention } from './component/decorator/UserMention';@@ -65,6 +67,7 @@ export function initializeLexical() {setDecorator(SnapshotNode, Snapshot);setDecorator(HtmlRenderNode, HtmlRender);setDecorator(ThemeMentionNode, ThemeMention);+ setDecorator(TagMentionNode, TagMention);setDecorator(UnknownMentionNode, UnknownMention);setDecorator(WatermarkNode, Watermark);setDecorator(AwaitNode, Await);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.tsindex 79d580b03d..0bed59b6b0 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts@@ -38,5 +38,6 @@ export * from './single-line';export * from './snippets';export * from './tab-indentation';export * from './tables';+export * from './tags';export * from './text-paste';export * from './wordcount';diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/index.tsnew file mode 100644index 0000000000..ee81ef506c--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/index.ts@@ -0,0 +1 @@+export * from './tagsPlugin';diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/tagsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/tagsPlugin.tsnew file mode 100644index 0000000000..7341034541--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/tagsPlugin.ts@@ -0,0 +1,239 @@+import { $wrapNodeInElement, mergeRegister } from '@lexical/utils';+import {+ $collapseInlineSearch,+ $createInlineSearchNode,+ $createTagMentionNode,+ $handleInlineSearchNodeMutation,+ $handleInlineSearchNodeTransform,+ $isTagMentionNode,+ $removeInlineSearch,+ InlineSearchNode,+ InlineSearchNodesType,+ type PeerIdValidator,+ type TagMentionInfo,+ TagMentionNode,+ validTriggerPosition,+} from '@macro-inc/lexical-core';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $insertNodes,+ $isRangeSelection,+ $isRootOrShadowRoot,+ COMMAND_PRIORITY_HIGH,+ COMMAND_PRIORITY_LOW,+ COMMAND_PRIORITY_NORMAL,+ createCommand,+ KEY_ESCAPE_COMMAND,+ type LexicalCommand,+ type LexicalEditor,+} from 'lexical';+import type { MenuOperations } from '../../shared/inlineMenu';+import { $collapseSelection, $traverseNodes, nodeByKey } from '../../utils';+import {+ CLOSE_INLINE_SEARCH_COMMAND,+ REMOVE_INLINE_SEARCH_COMMAND,+} from '../mentions/mentionsPlugin';++export const INSERT_TAG_MENTION_COMMAND: LexicalCommand<TagMentionInfo> =+ createCommand('INSERT_TAG_MENTION_COMMAND');++const TYPE_HASH_SYMBOL_COMMAND: LexicalCommand<void> = createCommand(+ 'TYPE_HASH_SYMBOL_COMMAND'+);++export type TagMentionLifecycle = TagMentionInfo;++type TagsPluginProps = {+ menu?: MenuOperations;+ insertTags?: boolean;+ onCreateTag?: (tag: TagMentionLifecycle) => void;+ onRemoveTag?: (tag: TagMentionLifecycle) => void;+ setTags?: (tags: ReadonlySet<TagMentionLifecycle>) => void;+ peerIdValidator?: PeerIdValidator;+};++const beforeRegex = /[(['"`\s]$/;+const afterRegex = /^[)\]'"`\s]/;++function tagMentionFromNode(node: TagMentionNode): TagMentionLifecycle {+ return {+ optionId: node.getOptionId(),+ propertyDefinitionId: node.getPropertyDefinitionId(),+ scope: node.getScope(),+ name: node.getName(),+ color: node.getColor(),+ };+}++function registerHashSymbolListener(+ editor: LexicalEditor,+ props: TagsPluginProps+) {+ const listener = (e: KeyboardEvent) => {+ if (e.key === '#') {+ if (props.menu?.isOpen()) {+ editor.update(() => {+ $collapseInlineSearch(props.peerIdValidator);+ });+ props.menu.closeMenu();+ return;+ }+ editor.dispatchCommand(TYPE_HASH_SYMBOL_COMMAND, undefined);+ }+ };++ return editor.registerRootListener((root, prev) => {+ if (root) root.addEventListener('keydown', listener);+ if (prev) prev.removeEventListener('keydown', listener);+ });+}++function registerTagsPlugin(editor: LexicalEditor, props: TagsPluginProps) {+ if (!editor.hasNode(InlineSearchNode)) {+ throw new Error('TagsPlugin: Editor config is missing InlineSearchNode.');+ }++ const insertTags = props.insertTags ?? true;+ if (insertTags && !editor.hasNode(TagMentionNode)) {+ throw new Error('TagsPlugin: Editor config is missing TagMentionNode.');+ }++ const updateTagsSignal = () => {+ if (props.setTags === undefined) return;+ const tags = new Map<string, TagMentionLifecycle>();+ editor.read(() => {+ $traverseNodes($getRoot(), (node) => {+ if ($isTagMentionNode(node)) {+ const tag = tagMentionFromNode(node);+ tags.set(tag.optionId, tag);+ }+ });+ });+ props.setTags(new Set(tags.values()));+ };++ return mergeRegister(+ editor.registerCommand(+ INSERT_TAG_MENTION_COMMAND,+ (payload) => {+ if (!insertTags) {+ editor.update(() => {+ $removeInlineSearch(props.peerIdValidator);+ });+ props.onCreateTag?.(payload);+ return true;+ }++ editor.update(() => {+ const selection = $getSelection();+ const mentionNode = $createTagMentionNode(payload);++ 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+ ),++ registerHashSymbolListener(editor, props),++ editor.registerCommand(+ TYPE_HASH_SYMBOL_COMMAND,+ () => {+ const shouldTrigger = validTriggerPosition(+ editor,+ beforeRegex,+ afterRegex+ );+ if (!shouldTrigger) return false;++ editor.update(() => {+ $insertNodes([$createInlineSearchNode('#')]);+ });+ return true;+ },+ COMMAND_PRIORITY_LOW+ ),++ editor.registerNodeTransform(InlineSearchNode, (node: InlineSearchNode) =>+ $handleInlineSearchNodeTransform(node, InlineSearchNodesType.Tags)+ ),++ editor.registerCommand(+ CLOSE_INLINE_SEARCH_COMMAND,+ () => $collapseInlineSearch(props.peerIdValidator),+ COMMAND_PRIORITY_LOW+ ),++ editor.registerCommand(+ KEY_ESCAPE_COMMAND,+ () => $collapseInlineSearch(props.peerIdValidator),+ COMMAND_PRIORITY_HIGH+ ),++ editor.registerCommand(+ REMOVE_INLINE_SEARCH_COMMAND,+ () => $removeInlineSearch(props.peerIdValidator),+ COMMAND_PRIORITY_HIGH+ ),++ editor.registerMutationListener(+ InlineSearchNode,+ (mutatedNodes, { prevEditorState }) =>+ $handleInlineSearchNodeMutation(+ editor,+ prevEditorState,+ mutatedNodes,+ InlineSearchNodesType.Tags,+ {+ onDestroy: () => props.menu?.closeMenu(),+ onCreate: () => props.menu?.openMenu(),+ onUpdate: (search) => props.menu?.setSearchTerm(search),+ },+ props.peerIdValidator+ )+ ),++ ...(insertTags+ ? [+ editor.registerMutationListener(+ TagMentionNode,+ (mutatedNodes, { prevEditorState }) => {+ for (const [nodeKey, mutation] of mutatedNodes) {+ const node = nodeByKey(+ mutation === 'destroyed'+ ? prevEditorState+ : editor.getEditorState(),+ nodeKey+ ) as TagMentionNode | null;+ if (!node) continue;++ const tag = tagMentionFromNode(node);+ if (mutation === 'created') props.onCreateTag?.(tag);+ if (mutation === 'destroyed') props.onRemoveTag?.(tag);+ }+ updateTagsSignal();+ }+ ),+ ]+ : [])+ );+}++export function tagsPlugin(props: TagsPluginProps) {+ return (editor: LexicalEditor) => registerTagsPlugin(editor, props);+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex 66e6b5ef28..4f96de6e5c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -13,5 +13,6 @@* Version 2.0 - Jun 19, 2026. Added PullRequestMentionNode.* Version 2.1 - Jun 23, 2026. Added PasteNode* Version 2.2 - Jul 13, 2026. Added optional adaptColors display hint to HtmlRenderNode.+ * Version 2.3 - Jul 15, 2026. Added TagMentionNode.*/-export const MARKDOWN_VERSION_COUNTER = 2.2;+export const MARKDOWN_VERSION_COUNTER = 2.3;diff --git a/packages/lexical-core/decoratorRegistry.ts b/packages/lexical-core/decoratorRegistry.tsindex 913aa52c71..0cd549558b 100644--- a/packages/lexical-core/decoratorRegistry.ts+++ b/packages/lexical-core/decoratorRegistry.ts@@ -46,6 +46,10 @@ import type {SnapshotDecoratorProps,SnapshotNode,} from './nodes/SnapshotNode';+import type {+ TagMentionDecoratorProps,+ TagMentionNode,+} from './nodes/TagMentionNode';import type {ThemeMentionDecoratorProps,ThemeMentionNode,@@ -135,6 +139,10 @@ export interface NodeDecoratorMap {klass: typeof ThemeMentionNode;props: ThemeMentionDecoratorProps;};+ TagMentionNode: {+ klass: typeof TagMentionNode;+ props: TagMentionDecoratorProps;+ };WatermarkNode: {klass: typeof WatermarkNode;props: WatermarkDecoratorProps;diff --git a/packages/lexical-core/index.ts b/packages/lexical-core/index.tsindex 5c13500857..6960ac0131 100644--- a/packages/lexical-core/index.ts+++ b/packages/lexical-core/index.ts@@ -26,6 +26,7 @@ export * from './nodes/MediaNode';export * from './nodes/PasteNode';export * from './nodes/PullRequestMentionNode';export * from './nodes/SnapshotNode';+export * from './nodes/TagMentionNode';export * from './nodes/ThemeMentionNode';export * from './nodes/UnknownMentionNode';export * from './nodes/UnlinkedTextNode';diff --git a/packages/lexical-core/node-list.ts b/packages/lexical-core/node-list.tsindex fac029f737..0f7e9cfa88 100644--- a/packages/lexical-core/node-list.ts+++ b/packages/lexical-core/node-list.ts@@ -36,6 +36,7 @@ import { PasteNode } from './nodes/PasteNode';import { PullRequestMentionNode } from './nodes/PullRequestMentionNode';import { SearchMatchNode } from './nodes/SearchMatchNode';import { SnapshotNode } from './nodes/SnapshotNode';+import { TagMentionNode } from './nodes/TagMentionNode';import { ThemeMentionNode } from './nodes/ThemeMentionNode';import { UnknownMentionNode } from './nodes/UnknownMentionNode';import { UnlinkedTextNode } from './nodes/UnlinkedTextNode';@@ -103,6 +104,7 @@ export const SupportedNodeTypes = [ClassedBlockNode,WatermarkNode,ThemeMentionNode,+ TagMentionNode,UnknownMentionNode,AwaitNode,] as const;diff --git a/packages/lexical-core/nodes/InlineSearchNode.ts b/packages/lexical-core/nodes/InlineSearchNode.tsindex 34991c3f17..e7da30f3d7 100644--- a/packages/lexical-core/nodes/InlineSearchNode.ts+++ b/packages/lexical-core/nodes/InlineSearchNode.ts@@ -33,6 +33,7 @@ export enum InlineSearchNodesType {Emojis = ':',Actions = '/',Snippets = ';',+ Tags = '#',}export const SEARCH_NODE_TYPE_VALUES = {@@ -40,6 +41,7 @@ export const SEARCH_NODE_TYPE_VALUES = {[InlineSearchNodesType.Emojis]: '::',[InlineSearchNodesType.Actions]: '//',[InlineSearchNodesType.Snippets]: ';;',+ [InlineSearchNodesType.Tags]: '##',};export function validTriggerPosition(@@ -74,7 +76,7 @@ export function validTriggerPosition(});}-const CLEAN_REGEX = /^[@:\/;]/g; // Matches @, :, /, or ; to clean the search term.+const CLEAN_REGEX = /^[@:\/;#]/g; // Matches menu triggers to clean the search term.export class InlineSearchNode extends TextNode {static getType() {diff --git a/packages/lexical-core/nodes/TagMentionNode.ts b/packages/lexical-core/nodes/TagMentionNode.tsnew file mode 100644index 0000000000..b734410e55--- /dev/null+++ b/packages/lexical-core/nodes/TagMentionNode.ts@@ -0,0 +1,249 @@+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 TagMentionInfo = {+ optionId: string;+ propertyDefinitionId: string;+ scope: 'user' | 'team';+ name: string;+ color?: string;+};++export type SerializedTagMentionNode = Spread<+ TagMentionInfo,+ SerializedLexicalNode+>;++export type TagMentionDecoratorProps = TagMentionInfo & {+ key: NodeKey;+ theme: EditorThemeClasses;+};++export class TagMentionNode extends DecoratorNode<+ DecoratorComponent<TagMentionDecoratorProps> | undefined+> {+ __optionId: string;+ __propertyDefinitionId: string;+ __scope: 'user' | 'team';+ __name: string;+ __color: string | undefined;++ static getType() {+ return 'tag-mention';+ }++ isInline(): boolean {+ return true;+ }++ isKeyboardSelectable(): boolean {+ return true;+ }++ static clone(node: TagMentionNode) {+ return new TagMentionNode(+ node.__optionId,+ node.__propertyDefinitionId,+ node.__scope,+ node.__name,+ node.__color,+ node.__key+ );+ }++ constructor(+ optionId: string,+ propertyDefinitionId: string,+ scope: 'user' | 'team',+ name: string,+ color?: string,+ key?: NodeKey+ ) {+ super(key);+ this.__optionId = optionId;+ this.__propertyDefinitionId = propertyDefinitionId;+ this.__scope = scope;+ this.__name = name;+ this.__color = color;+ }++ static importJSON(serializedNode: SerializedTagMentionNode) {+ const node = $createTagMentionNode({+ optionId: serializedNode.optionId,+ propertyDefinitionId: serializedNode.propertyDefinitionId,+ scope: serializedNode.scope,+ name: serializedNode.name,+ color: serializedNode.color,+ });+ $applyIdFromSerialized(node, serializedNode);+ return node;+ }++ exportJSON(): SerializedTagMentionNode {+ return {+ ...super.exportJSON(),+ optionId: this.__optionId,+ propertyDefinitionId: this.__propertyDefinitionId,+ scope: this.__scope,+ name: this.__name,+ color: this.__color,+ type: TagMentionNode.getType(),+ version: VERSION,+ };+ }++ exportComponentProps(): TagMentionInfo {+ return {+ optionId: this.__optionId,+ propertyDefinitionId: this.__propertyDefinitionId,+ scope: this.__scope,+ name: this.__name,+ color: this.__color,+ };+ }++ createDOM(_config: EditorConfig): HTMLElement {+ const span = document.createElement('span');+ span.setAttribute('data-tag-mention', 'true');+ return span;+ }++ updateDOM(_prevNode: TagMentionNode, _dom: HTMLElement): boolean {+ return false;+ }++ static importDOM(): DOMConversionMap<HTMLElement> | null {+ const convert = (domNode: HTMLElement) => {+ const optionId = domNode.getAttribute('data-tag-option-id');+ const propertyDefinitionId = domNode.getAttribute(+ 'data-tag-property-definition-id'+ );+ const name = domNode.getAttribute('data-tag-name') || '';+ const scope = domNode.getAttribute('data-tag-scope');+ const color = domNode.getAttribute('data-tag-color') || undefined;++ if (+ optionId &&+ propertyDefinitionId &&+ (scope === 'user' || scope === 'team')+ ) {+ return {+ node: $createTagMentionNode({+ optionId,+ propertyDefinitionId,+ scope,+ name,+ color,+ }),+ };+ }++ return null;+ };++ const wrapInCheck = (conversion: DOMConversion) => {+ return (node: HTMLElement) =>+ node.hasAttribute('data-tag-mention') ? conversion : null;+ };++ return {+ span: wrapInCheck({ conversion: convert, priority: 1 }),+ };+ }++ exportDOM() {+ const element = document.createElement('span');+ element.setAttribute('data-tag-mention', 'true');+ element.setAttribute('data-tag-option-id', this.__optionId);+ element.setAttribute(+ 'data-tag-property-definition-id',+ this.__propertyDefinitionId+ );+ element.setAttribute('data-tag-name', this.__name);+ element.setAttribute('data-tag-scope', this.__scope);+ if (this.__color) element.setAttribute('data-tag-color', this.__color);+ element.textContent = this.__name;+ return { element };+ }++ getTextContent(): string {+ return this.__name;+ }++ getOptionId(): string {+ return this.__optionId;+ }++ getPropertyDefinitionId(): string {+ return this.__propertyDefinitionId;+ }++ getScope(): 'user' | 'team' {+ return this.__scope;+ }++ getName(): string {+ return this.__name;+ }++ getColor(): string | undefined {+ return this.__color;+ }++ setTagInfo(info: Omit<TagMentionInfo, 'optionId'>) {+ const writable = this.getWritable();+ writable.__propertyDefinitionId = info.propertyDefinitionId;+ writable.__scope = info.scope;+ writable.__name = info.name;+ writable.__color = info.color;+ return writable;+ }++ decorate(_: LexicalEditor, config: EditorConfig) {+ const decorator = getDecorator<TagMentionDecoratorProps>(TagMentionNode);+ if (decorator) {+ return () =>+ decorator({+ optionId: this.__optionId,+ propertyDefinitionId: this.__propertyDefinitionId,+ scope: this.__scope,+ name: this.__name,+ color: this.__color,+ key: this.getKey(),+ theme: config.theme,+ });+ }+ }+}++export function $createTagMentionNode(params: TagMentionInfo): TagMentionNode {+ const node = new TagMentionNode(+ params.optionId,+ params.propertyDefinitionId,+ params.scope,+ params.name,+ params.color+ );+ return $applyNodeReplacement(node);+}++export function $isTagMentionNode(+ node: TagMentionNode | LexicalNode | null | undefined+): node is TagMentionNode {+ return node instanceof TagMentionNode;+}diff --git a/packages/lexical-core/tests/mentions.test.ts b/packages/lexical-core/tests/mentions.test.tsindex b022e3e2a7..6cd77e10bb 100644--- a/packages/lexical-core/tests/mentions.test.ts+++ b/packages/lexical-core/tests/mentions.test.ts@@ -8,6 +8,7 @@ import {parseGroupMentions,parseLinks,parsePullRequestMentions,+ parseTagMentions,parseUserMentions,} from '../utils/parsers';@@ -176,6 +177,18 @@ describe('parseGroupMentions', () => {});});+describe('parseTagMentions', () => {+ it('extracts #name from a tag mention', () => {+ const input =+ '<m-tag>{"optionId":"tag-1","propertyDefinitionId":"prop-1","scope":"team","name":"Launch","color":"#0091FF"}</m-tag>';+ expect(parseTagMentions(input)).toBe('#Launch');+ });++ it('returns empty string for invalid JSON', () => {+ expect(parseTagMentions('<m-tag>invalid</m-tag>')).toBe('');+ });+});+describe('markdownToPlainText', () => {it('converts mixed content to plain text', () => {const input =@@ -207,6 +220,12 @@ describe('markdownToPlainText', () => {expect(markdownToPlainText(input)).toBe('See macro/macro#123.');});+ it('handles text with tag mentions', () => {+ const input =+ 'Ship <m-tag>{"optionId":"tag-1","propertyDefinitionId":"prop-1","scope":"team","name":"Launch"}</m-tag>.';+ expect(markdownToPlainText(input)).toBe('Ship #Launch.');+ });+it('returns original text when no mentions present', () => {const input = 'Just plain text here.';expect(markdownToPlainText(input)).toBe('Just plain text here.');@@ -252,6 +271,12 @@ describe('markdownToEmbeddingText', () => {);});+ it('keeps tag names', () => {+ const input =+ 'Ship <m-tag>{"optionId":"tag-1","propertyDefinitionId":"prop-1","scope":"team","name":"Launch"}</m-tag>.';+ expect(markdownToEmbeddingText(input)).toBe('Ship #Launch.');+ });+it('keeps link urls', () => {const input ='See <m-link>{"url":"https://example.com","text":"this link"}</m-link>.';diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.tsindex 79dcb2a170..27b69ba264 100644--- a/packages/lexical-core/transformers/index.ts+++ b/packages/lexical-core/transformers/index.ts@@ -17,6 +17,7 @@ import {E_DOCUMENT_MENTION,E_GROUP_MENTION,E_PR_MENTION,+ E_TAG_MENTION,E_USER_MENTION,I_CONTACT_MENTION,I_DATE_MENTION,@@ -24,6 +25,7 @@ import {I_DOCUMENT_MENTION,I_GROUP_MENTION,I_PR_MENTION,+ I_TAG_MENTION,I_THEME_MENTION,I_USER_MENTION,} from './mentions';@@ -76,6 +78,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [I_MACRO_QUOTE,I_EQUATION_NODE,I_THEME_MENTION,+ I_TAG_MENTION,I_WATERMARK,...CUSTOM_TRANSFORMERS,UNKNOWN_MENTION, // Must be last to act as fallback for unrecognized XML tags@@ -103,6 +106,7 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [E_PR_MENTION,E_CONTACT_MENTION,E_DATE_MENTION,+ E_TAG_MENTION,// order mattersE_MULTILINE_BLOCK_EQUATION_NODE,E_BLOCK_EQUATION_NODE,@@ -153,8 +157,10 @@ export const ALL_TRANSFORMERS: Transformer[] = [I_MACRO_QUOTE,I_EQUATION_NODE,I_THEME_MENTION,+ I_TAG_MENTION,I_WATERMARK,E_WATERMARK,+ E_TAG_MENTION,// order mattersE_MULTILINE_BLOCK_EQUATION_NODE,E_BLOCK_EQUATION_NODE,diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.tsindex 101e2cf42e..d264bc9ce3 100644--- a/packages/lexical-core/transformers/mentions.ts+++ b/packages/lexical-core/transformers/mentions.ts@@ -9,6 +9,7 @@ import { DocumentCardNode } from '../nodes/DocumentCardNode';import { DocumentMentionNode } from '../nodes/DocumentMentionNode';import { GroupMentionNode } from '../nodes/GroupMentionNode';import { PullRequestMentionNode } from '../nodes/PullRequestMentionNode';+import { TagMentionNode } from '../nodes/TagMentionNode';import { ThemeMentionNode } from '../nodes/ThemeMentionNode';import { UserMentionNode } from '../nodes/UserMentionNode';import {@@ -483,6 +484,72 @@ export const I_THEME_MENTION: TextMatchTransformer = {},};+// Internal Tag Mentions+export const I_TAG_MENTION: TextMatchTransformer = {+ dependencies: [TagMentionNode, UnknownMentionNode],+ type: 'text-match',+ regExp: /<m-tag>(.*?)<\/m-tag>/,+ importRegExp: /<m-tag>(.*?)<\/m-tag>/,+ export: (node) => {+ if (!(node instanceof TagMentionNode)) return null;+ const data = JSON.stringify({+ optionId: node.getOptionId(),+ propertyDefinitionId: node.getPropertyDefinitionId(),+ scope: node.getScope(),+ name: node.getName(),+ color: node.getColor(),+ });+ return `<m-tag>${data}</m-tag>`;+ },+ replace: (node: TextNode, match: RegExpMatchArray) => {+ try {+ const data = JSON.parse(match[1]);+ for (const field of [+ 'optionId',+ 'propertyDefinitionId',+ 'scope',+ 'name',+ ]) {+ if (!(field in data)) throw new Error(`Missing field ${field}`);+ }+ if (data.scope !== 'user' && data.scope !== 'team') {+ throw new Error('Invalid tag scope');+ }+ const tagMentionNode = new TagMentionNode(+ data.optionId,+ data.propertyDefinitionId,+ data.scope,+ data.name,+ typeof data.color === 'string' ? data.color : undefined+ );+ node.replace(tagMentionNode);+ } catch (e) {+ console.error('Error in I_TAG_MENTION replace:', e);+ replaceTextWithUnknownMention(node, 'Unknown Tag');+ }+ },+};++// External Tag Mentions+export const E_TAG_MENTION: ElementTransformer = {+ dependencies: [TagMentionNode],+ type: 'element',+ regExp: /$^/,+ export: (node) => {+ if (!(node instanceof TagMentionNode)) return null;+ const name = node.getName();+ return name ? `#${name}` : null;+ },+ replace: (+ _parentNode: ElementNode,+ _children: Array<LexicalNode>,+ _match: Array<string>,+ _isImport: boolean+ ) => {+ return false;+ },+};+// External Document Cardsexport const E_DOCUMENT_CARD: ElementTransformer = {dependencies: [DocumentCardNode],diff --git a/packages/lexical-core/transformers/xml/codecs.ts b/packages/lexical-core/transformers/xml/codecs.tsindex c137abdfcc..839d61e01f 100644--- a/packages/lexical-core/transformers/xml/codecs.ts+++ b/packages/lexical-core/transformers/xml/codecs.ts@@ -88,6 +88,7 @@ const KNOWN_TYPES: Record<KnownNode['type'], 1> = {'contact-mention': 1,'group-mention': 1,'pr-mention': 1,+ 'tag-mention': 1,'theme-mention': 1,'unknown-mention': 1,};@@ -361,6 +362,19 @@ export function serializeNode(node: SerNode): FxpNode {.with({ type: 'theme-mention' }, (n) =>el('theme-mention', [], nodeAttrs(n, { ...(n.name && { name: n.name }) })))+ .with({ type: 'tag-mention' }, (n) =>+ el(+ 'tag-mention',+ [],+ nodeAttrs(n, {+ optionId: n.optionId,+ propertyDefinitionId: n.propertyDefinitionId,+ scope: n.scope,+ name: n.name,+ ...(n.color && { color: n.color }),+ })+ )+ ).with({ type: 'unknown-mention' }, (n) =>el('unknown-mention',diff --git a/packages/lexical-core/transformers/xml/nodes.ts b/packages/lexical-core/transformers/xml/nodes.tsindex d90e94d754..668c398e36 100644--- a/packages/lexical-core/transformers/xml/nodes.ts+++ b/packages/lexical-core/transformers/xml/nodes.ts@@ -202,6 +202,16 @@ export type ThemeMentionNode = Id & {name: string;};+export type TagMentionNode = Id & {+ type: 'tag-mention';+ version: number;+ optionId: string;+ propertyDefinitionId: string;+ scope: 'user' | 'team';+ name: string;+ color?: string;+};+export type UnknownMentionNode = Id & {type: 'unknown-mention';version: number;@@ -236,6 +246,7 @@ export type KnownNode =| ContactMentionNode| GroupMentionNode| PullRequestMentionNode+ | TagMentionNode| ThemeMentionNode| UnknownMentionNode;diff --git a/packages/lexical-core/utils/mentions.ts b/packages/lexical-core/utils/mentions.tsindex 4d57ec78ab..daae8ce19a 100644--- a/packages/lexical-core/utils/mentions.ts+++ b/packages/lexical-core/utils/mentions.ts@@ -24,6 +24,7 @@ import {type PullRequestMentionInfo,type PullRequestMentionNode,} from '../nodes/PullRequestMentionNode';+import type { TagMentionInfo } from '../nodes/TagMentionNode';import {$isUserMentionNode,type UserMentionInfo,@@ -144,7 +145,8 @@ export type MentionInfo =| (DocumentMentionInfo & { type: 'document' })| (PullRequestMentionInfo & { type: 'pr' })| (ContactMentionInfo & { type: 'contact' })- | (DateMentionInfo & { type: 'date' });+ | (DateMentionInfo & { type: 'date' })+ | (TagMentionInfo & { type: 'tag' });export function buildMentionMarkdownString(info: MentionInfo): string {switch (info.type) {@@ -158,6 +160,8 @@ export function buildMentionMarkdownString(info: MentionInfo): string {return wrapXml('m-contact-mention', dropKey(info, 'type'));case 'date':return wrapXml('m-date-mention', dropKey(info, 'type'));+ case 'tag':+ return wrapXml('m-tag', dropKey(info, 'type'));}}@@ -170,5 +174,6 @@ export {parseGroupMentions,parseLinks,parsePullRequestMentions,+ parseTagMentions,parseUserMentions,} from './parsers';diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.tsindex 51ee7f9f2f..ed2585d5f0 100644--- a/packages/lexical-core/utils/parsers.ts+++ b/packages/lexical-core/utils/parsers.ts@@ -59,6 +59,17 @@ export function parsePullRequestMentions(text: string): string {});}+export function parseTagMentions(text: string): string {+ return text.replace(/<m-tag>(.*?)<\/m-tag>/g, (_, json) => {+ try {+ const data = JSON.parse(json);+ return data.name ? `#${data.name}` : '';+ } catch {+ return '';+ }+ });+}+export function parseLinks(text: string): string {return text.replace(/<m-link>(.*?)<\/m-link>/g, (_, json) => {try {@@ -131,11 +142,13 @@ export function markdownToPlainText(markdown: string): string {return parseLinks(parseDocumentCards(parseSnapshots(- parsePullRequestMentions(- parseDocumentMentions(- parseGroupMentions(- parseDateMentions(- parseContactMentions(parseUserMentions(markdown))+ parseTagMentions(+ parsePullRequestMentions(+ parseDocumentMentions(+ parseGroupMentions(+ parseDateMentions(+ parseContactMentions(parseUserMentions(markdown))+ ))))@@ -312,6 +325,9 @@ export function markdownToEmbeddingText(markdown: string): string {'m-group-mention',(data) => `@${data.groupAlias || ''}`);+ text = replaceJsonTag(text, 'm-tag', (data) =>+ data.name ? `#${data.name}` : ''+ );text = replaceJsonTag(text, 'm-theme-mention', (data) => data.name || '');text = replaceJsonTag(text, 'm-await', (data) => data.text || '');text = replaceJsonTag(text, 'm-watermark', () => '');