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): follow up menu to tagging document on markdown tag insert, fix: tag overlay editor (#5382)
Seamus26a717594cb9
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsxindex dbbe14b5aa..7b590a6e1e 100644--- a/apps/web/src/features/block-md/component/ComposeTask.tsx+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx@@ -970,6 +970,8 @@ export function ComposeTask(props: ComposeTaskProps) {const editorConfig = buildConfig('markdown').withMentions().withTags({+ applyTargetLabel: 'Task',+ isApplied: (tag) => composerTags.isApplied(tag.optionId),onCreate: (tag) => {void composerTags.applyTag(tag.scope, tag.optionId);},diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsxindex 726338eb3c..5b61b13aae 100644--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx@@ -234,6 +234,8 @@ export function MarkdownEditor(props: {blockId,blockName === 'task' ? EntityType.TASK : EntityType.DOCUMENT);+ const tagApplyTargetLabel = () =>+ blockName === 'task' ? 'Task' : 'Document';const mdDocumentName = useBlockDocumentName('');@@ -557,10 +559,6 @@ export function MarkdownEditor(props: {tagsPlugin({menu: tagsMenuOperations,peerIdValidator: peerIdValidator(),- onCreateTag: (tag) => {- if (!canEdit()) return;- void documentTags.applyTag(tag.scope, tag.optionId);- },})).use(@@ -1096,6 +1094,12 @@ export function MarkdownEditor(props: {editor={editor}menu={tagsMenuOperations}useBlockBoundary={true}+ applyTargetLabel={tagApplyTargetLabel()}+ isApplied={(tag) => documentTags.isApplied(tag.optionId)}+ onApplyTag={(tag) => {+ if (!canEdit()) return;+ void documentTags.applyTag(tag.scope, tag.optionId);+ }}/><SnippetsMenudiff --git a/apps/web/src/features/block-md/component/TitleEditor.tsx b/apps/web/src/features/block-md/component/TitleEditor.tsxindex 48af0a068d..0bee432dbb 100644--- a/apps/web/src/features/block-md/component/TitleEditor.tsx+++ b/apps/web/src/features/block-md/component/TitleEditor.tsx@@ -178,7 +178,11 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {};const scheduleRename = (newName: string, oldName: string) => {- if (newName === oldName) return;+ if (newName === oldName) {+ pendingRename = undefined;+ debouncedFlushRename.clear();+ return;+ }pendingRename = { newName, oldName };debouncedFlushRename();};@@ -296,8 +300,8 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {);createEffect(() => {- if (inlineMenuOpen()) return;const currentState = state();+ if (untrack(inlineMenuOpen)) return;if (!untrack(initialized)) {setInitialized(true);return;@@ -306,11 +310,14 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {if (nextName !== untrack(mdDocumentName)) {setOptimisticName(nextName);}- if (nextName !== (untrack(persistedDocumentName) ?? '')) {+ const persistedName = untrack(persistedDocumentName) ?? '';+ if (nextName !== persistedName) {selfChangedTitle = true;if (canEdit()) {- scheduleRename(nextName, untrack(persistedDocumentName) ?? '');+ scheduleRename(nextName, persistedName);}+ } else {+ scheduleRename(nextName, persistedName);}});diff --git a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts b/apps/web/src/features/next-soup/actions/use-block-entity-commands.tsindex 02bd4387bc..ec807633a1 100644--- a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts+++ b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts@@ -1,5 +1,8 @@import { useMaybeSoup } from '@app/features/next-soup/soup-context';-import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';+import {+ openEntityInSplitFromUnifiedList,+ restoreSoupFocus,+} from '@app/features/next-soup/utils';import { useAllProperties } from '@app/features/property/editor/hooks/useAllProperties';import { openPropertyEditor } from '@app/features/property/editor/state/propertyEditor';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';@@ -77,7 +80,11 @@ export const useBlockEntityCommands = () => {) => {const entity = getEntity();if (entity) {- openPropertyEditor([entity], mode, property);+ openPropertyEditor([entity], mode, property, {+ restoreFocus: () => {+ if (soup) return restoreSoupFocus(entity.id);+ },+ });}};const canAssignTags = (entity: EntityData) => {@@ -355,7 +362,11 @@ export const useBlockEntityCommands = () => {keyDownHandler: () => {const entity = getEntity();if (!entity) return false;- openPropertyEditor([entity], 'tag');+ openPropertyEditor([entity], 'tag', undefined, {+ restoreFocus: () => {+ if (soup) return restoreSoupFocus(entity.id);+ },+ });return true;},condition: () => {diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.tsindex 3b7c7268f9..1ac9da933a 100644--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts@@ -1,6 +1,9 @@import { isListViewID } from '@app/constants/list-views';import { canExecuteMarkDoneOnView } from '@app/features/next-soup/actions/make-mark-done-action';-import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';+import {+ openEntityInSplitFromUnifiedList,+ restoreSoupFocus,+} from '@app/features/next-soup/utils';import { useAllProperties } from '@app/features/property/editor/hooks/useAllProperties';import { openPropertyEditor } from '@app/features/property/editor/state/propertyEditor';import { isShareableEntityType } from '@app/features/sharing/global-share-modal/GlobalShareModal';@@ -139,7 +142,9 @@ export const useEntityActionHotkeys = () => {const entities = getEntitiesForAction();if (entities.length > 0) {- openPropertyEditor(entities, mode, property);+ openPropertyEditor(entities, mode, property, {+ restoreFocus: () => restoreSoupFocus(entities[0]?.id),+ });}};const canAssignTags = (entity: EntityData) => {@@ -526,7 +531,9 @@ export const useEntityActionHotkeys = (keyDownHandler: () => {const entities = getEntitiesForAction();if (entities.length === 0) return false;- openPropertyEditor(entities, 'tag');+ openPropertyEditor(entities, 'tag', undefined, {+ restoreFocus: () => restoreSoupFocus(entities[0]?.id),+ });return true;},condition: () => {diff --git a/apps/web/src/features/property/editor/PropertyEditorModal.tsx b/apps/web/src/features/property/editor/PropertyEditorModal.tsxindex bf8491203b..2680cb05b5 100644--- a/apps/web/src/features/property/editor/PropertyEditorModal.tsx+++ b/apps/web/src/features/property/editor/PropertyEditorModal.tsx@@ -20,6 +20,7 @@ import { SYSTEM_PROPERTY_IDS } from '@property/constants';import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';import { usePropertySelection } from '@property/hooks';import { usePropertyEntityDisplay } from '@property/hooks/usePropertyEntityDisplay';+import { useDocTags } from '@property/tags';import { TagDot } from '@property/tags/TagDot';import {TagEditorDialog,@@ -36,13 +37,13 @@ import {toPropertyApiValue,} from '@property/utils';import {- useAddEntityPropertyOptionMutation,+ useBulkUpdateEntityPropertyOptionsMutation,useEntityPropertiesQuery,- useRemoveEntityPropertyOptionMutation,} from '@queries/properties/entity';import { useTagsQuery } from '@queries/properties/tags';import { useCurrentTeamQuery } from '@queries/team/teams';import type { EntityReference } from '@service-properties/generated/schemas/entityReference';+import type { EntityType } from '@service-properties/generated/schemas/entityType';import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';import type { TagScope } from '@service-properties/generated/schemas/tagScope';@@ -117,6 +118,7 @@ type TagOptionItem = {};type EntityTagIdsByDefinition = Map<string, Map<string, string[]>>;+type DocTags = ReturnType<typeof useDocTags>;function tagOptionLabel(option: PropertyOptionResponse): string {return option.value.type === 'string' ? option.value.value : '';@@ -176,6 +178,22 @@ function getTagIds(return byEntity.get(entityId)?.get(definitionId) ?? [];}+function docTagIdsByDefinition(+ entityId: string,+ docTags: DocTags+): EntityTagIdsByDefinition {+ const byDefinition = new Map<string, string[]>();+ for (const tag of docTags.appliedTags()) {+ const current = byDefinition.get(tag.propertyDefinitionId) ?? [];+ byDefinition.set(tag.propertyDefinitionId, [...current, tag.optionId]);+ }+ return new Map([[entityId, byDefinition]]);+}++function tagAssignmentEntityType(entity: EntityData): EntityType {+ return getEntityType({ kind: 'entity', id: entity.id, data: entity });+}+function canAssignTags(entity: EntityData): boolean {try {macroEntityToPropertyEntityType(entity);@@ -515,59 +533,69 @@ function TagAssignmentEditor(props: {}) {const tagsQuery = useTagsQuery();const currentTeamQuery = useCurrentTeamQuery();- const addOption = useAddEntityPropertyOptionMutation();- const removeOption = useRemoveEntityPropertyOptionMutation();+ // Multi-entity tag edits keep their optimistic state in this editor. The+ // mutation variables still carry each entity id for the API and invalidation.+ const tagAssignmentMutationScope = `property-editor-tags:${props.entities+ .map((entity) => entity.id)+ .sort()+ .join(':')}`;+ const updateTagOptions = useBulkUpdateEntityPropertyOptionsMutation(+ tagAssignmentMutationScope+ );const [tagEditorMode, setTagEditorMode] =createSignal<TagEditorDialogMode | null>(null);const [tagEditorOpen, setTagEditorOpen] = createControlledOpenSignal(false, {id: 'property-tag-edit',});- const singleEntity = () =>+ const singleEntityForDocTags =props.entities.length === 1 ? props.entities[0] : undefined;- const entityPropertiesQuery = useEntityPropertiesQuery(- () => {- const entity = singleEntity();- return entity ? macroEntityToPropertyEntityType(entity) : 'DOCUMENT';- },- () => singleEntity()?.id ?? '',- false- );- const currentEntityTagIds = () =>- entityTagIdsByDefinition(- props.entities,- singleEntity() && entityPropertiesQuery.data- ? {- entityId: singleEntity()!.id,- properties: entityPropertiesQuery.data,- }- : undefined- );+ const singleDocTags = singleEntityForDocTags+ ? useDocTags(+ singleEntityForDocTags.id,+ tagAssignmentEntityType(singleEntityForDocTags)+ )+ : undefined;+ const singleDocTagsSource = () =>+ props.entities.length === 1 &&+ props.entities[0]?.id === singleEntityForDocTags?.id+ ? singleDocTags+ : undefined;+ const currentEntityTagIds = () => {+ const docTags = singleDocTagsSource();+ if (docTags && singleEntityForDocTags) {+ return docTagIdsByDefinition(singleEntityForDocTags.id, docTags);+ }+ return entityTagIdsByDefinition(props.entities);+ };const initialEntityTagIds = currentEntityTagIds();const [orderedTagIds, setOrderedTagIds] =createSignal<EntityTagIdsByDefinition>(initialEntityTagIds);const [localTagIds, setLocalTagIds] =createSignal<EntityTagIdsByDefinition>(initialEntityTagIds);- const [hasEditedTags, setHasEditedTags] = createSignal(false);+ const [openOrderFrozen, setOpenOrderFrozen] = createSignal(false);let syncedEntityIds = props.entities.map((entity) => entity.id).join('\0');createEffect(() => {props.setPlaceholder('Change or add tags...');});+ createEffect(() => {+ const docTags = singleDocTagsSource();+ if (!docTags || openOrderFrozen()) return;++ const nextTagIds = currentEntityTagIds();+ setOrderedTagIds(nextTagIds);+ setLocalTagIds(nextTagIds);+ });+createEffect(on(- () => ({- entityIds: props.entities.map((entity) => entity.id).join('\0'),- properties: entityPropertiesQuery.data,- }),- ({ entityIds }) => {- const entityIdsChanged = entityIds !== syncedEntityIds;- if (entityIdsChanged) {- syncedEntityIds = entityIds;- setHasEditedTags(false);- }- if (hasEditedTags() && !entityIdsChanged) return;+ () => props.entities.map((entity) => entity.id).join('\0'),+ (entityIds) => {+ if (entityIds === syncedEntityIds) return;+ syncedEntityIds = entityIds;+ setOpenOrderFrozen(false);const nextTagIds = currentEntityTagIds();setOrderedTagIds(nextTagIds);setLocalTagIds(nextTagIds);@@ -599,6 +627,9 @@ function TagAssignmentEditor(props: {});const isFullyApplied = (item: TagOptionItem) => {+ const docTags = singleDocTagsSource();+ if (docTags) return docTags.isApplied(item.option.id);+if (props.entities.length === 0) return false;return props.entities.every((entity) =>getTagIds(localTagIds(), entity.id, item.definition.id).includes(@@ -642,15 +673,15 @@ function TagAssignmentEditor(props: {const showCreateRow = () =>createLabel().length > 0 && !exactTagMatchExists();const hasSearch = () => createLabel().length > 0;- const hasAnyAppliedTags = () => {- for (const byDefinition of localTagIds().values()) {+ const hadAnyAppliedTagsWhenOpened = () => {+ for (const byDefinition of orderedTagIds().values()) {for (const optionIds of byDefinition.values()) {if (optionIds.length > 0) return true;}}return false;};- const showClearAllRow = () => hasAnyAppliedTags();+ const showClearAllRow = () => hadAnyAppliedTagsWhenOpened();const showClearAllAtTop = () => showClearAllRow() && !hasSearch();const showClearAllAtBottom = () => showClearAllRow() && hasSearch();const itemRowIndex = (index: number) => index + (showClearAllAtTop() ? 1 : 0);@@ -705,14 +736,34 @@ function TagAssignmentEditor(props: {) => {const remove = isFullyApplied(item);const shouldClose = !event?.shiftKey;+ const docTags = singleDocTagsSource();+ setOpenOrderFrozen(true);++ if (docTags) {+ const selectedIds = new Set(+ docTags.appliedTags().map((tag) => tag.optionId)+ );+ if (remove) selectedIds.delete(item.option.id);+ else selectedIds.add(item.option.id);++ const update = docTags.setTagSelection(selectedIds);+ if (shouldClose) closePropertyEditor();++ try {+ await update;+ } catch (error) {+ console.error('Failed to update tags', error);+ }+ return;+ }+const previousTagIds = localTagIds();- setHasEditedTags(true);updateLocalOption(item, remove);try {const update = Promise.all(props.entities.map(async (entity) => {- const entityType = macroEntityToPropertyEntityType(entity);+ const entityType = tagAssignmentEntityType(entity);const current = getTagIds(previousTagIds,entity.id,@@ -723,17 +774,20 @@ function TagAssignmentEditor(props: {if (remove && !hasOption) return;if (!remove && hasOption) return;- const optimisticOptionIds = remove+ const nextOptionIds = remove? current.filter((id) => id !== item.option.id): [...current, item.option.id];- const mutation = remove ? removeOption : addOption;- await mutation.mutateAsync({+ await updateTagOptions.mutateAsync({entityId: entity.id,entityType,- property: tagDefinitionDomain(item.definition),- optionId: item.option.id,- optimisticOptionIds,+ properties: [+ {+ property: tagDefinitionDomain(item.definition),+ currentOptionIds: current,+ nextOptionIds,+ },+ ],});}));@@ -776,8 +830,22 @@ function TagAssignmentEditor(props: {if (!showClearAllRow()) return;const shouldClose = !event?.shiftKey;+ const docTags = singleDocTagsSource();+ setOpenOrderFrozen(true);++ if (docTags) {+ const update = docTags.setTagSelection(new Set());+ if (shouldClose) closePropertyEditor();++ try {+ await update;+ } catch (error) {+ console.error('Failed to clear tags', error);+ }+ return;+ }+const previousTagIds = localTagIds();- setHasEditedTags(true);setLocalTagIds(new Map(props.entities.map((entity) => [entity.id, new Map<string, string[]>()])@@ -785,26 +853,34 @@ function TagAssignmentEditor(props: {);try {- const updates: Promise<void>[] = [];+ const updates: Promise<unknown>[] = [];for (const entity of props.entities) {- const entityType = macroEntityToPropertyEntityType(entity);+ const entityType = tagAssignmentEntityType(entity);const byDefinition = previousTagIds.get(entity.id) ?? new Map();-- for (const [definitionId, optionIds] of byDefinition) {- const definition = tagDefinitionsById().get(definitionId);- if (!definition) continue;-- for (const optionId of optionIds) {- updates.push(- removeOption.mutateAsync({- entityId: entity.id,- entityType,+ const properties = [...byDefinition].flatMap(+ ([definitionId, optionIds]) => {+ if (optionIds.length === 0) return [];+ const definition = tagDefinitionsById().get(definitionId);+ if (!definition) return [];++ return [+ {property: tagDefinitionDomain(definition),- optionId,- optimisticOptionIds: [],- })- );+ currentOptionIds: optionIds,+ nextOptionIds: [],+ },+ ];}+ );++ if (properties.length > 0) {+ updates.push(+ updateTagOptions.mutateAsync({+ entityId: entity.id,+ entityType,+ properties,+ })+ );}}@@ -819,11 +895,24 @@ function TagAssignmentEditor(props: {};const applyCreatedTag = async (+ scope: TagScope,definition: PropertyDefinitionDetailResponse,optionId: string) => {+ const docTags = singleDocTagsSource();+ setOpenOrderFrozen(true);++ if (docTags) {+ try {+ await docTags.applyTag(scope, optionId);+ closePropertyEditor();+ } catch (error) {+ console.error('Failed to apply created tag', error);+ }+ return;+ }+const previousTagIds = localTagIds();- setHasEditedTags(true);setLocalTagIds((prev) => {const next = new Map(prev);for (const entity of props.entities) {@@ -841,16 +930,20 @@ function TagAssignmentEditor(props: {try {await Promise.all(props.entities.map(async (entity) => {- const entityType = macroEntityToPropertyEntityType(entity);+ const entityType = tagAssignmentEntityType(entity);const current = getTagIds(previousTagIds, entity.id, definition.id);if (current.includes(optionId)) return;- await addOption.mutateAsync({+ await updateTagOptions.mutateAsync({entityId: entity.id,entityType,- property: tagDefinitionDomain(definition),- optionId,- optimisticOptionIds: [...current, optionId],+ properties: [+ {+ property: tagDefinitionDomain(definition),+ currentOptionIds: current,+ nextOptionIds: [...current, optionId],+ },+ ],});}));@@ -1015,7 +1108,11 @@ function TagAssignmentEditor(props: {onCreateSuccess={async (result) => {const definition = result.tagSet.definition;if (!definition) return;- await applyCreatedTag(definition, result.option.id);+ await applyCreatedTag(+ result.tagSet.scope,+ definition,+ result.option.id+ );}}onClose={() => {setTagEditorOpen(false, false);diff --git a/apps/web/src/features/property/editor/state/propertyEditor.ts b/apps/web/src/features/property/editor/state/propertyEditor.tsindex 1f6d360cdc..e3e43c9113 100644--- a/apps/web/src/features/property/editor/state/propertyEditor.ts+++ b/apps/web/src/features/property/editor/state/propertyEditor.ts@@ -14,22 +14,29 @@ interface PropertyEditorState {targetProperty?: Property | PropertyDefinitionDomain;}+type PropertyEditorOpenOptions = {+ restoreFocus?: () => void | Promise<void>;+};+const [state, setState] = createStore<PropertyEditorState>({mode: 'selector',selectedEntities: [],targetProperty: undefined,});+let restoreFocusAfterClose: PropertyEditorOpenOptions['restoreFocus'];+export function openPropertyEditor(entities: EntityData[],mode: PropertyEditorMode = 'selector',- targetProperty?: Property | PropertyDefinitionDomain+ targetProperty?: Property | PropertyDefinitionDomain,+ options?: PropertyEditorOpenOptions) {if (!entities || entities.length === 0) {console.warn('Cannot open property editor without entities');return;}- setPropertyEditorOpen(true);+ restoreFocusAfterClose = options?.restoreFocus;setState(reconcile({mode,@@ -37,9 +44,12 @@ export function openPropertyEditor(targetProperty,}));+ setPropertyEditorOpen(true);}export function closePropertyEditor() {+ const restoreFocus = restoreFocusAfterClose;+ restoreFocusAfterClose = undefined;setPropertyEditorOpen(false);setState(reconcile({@@ -49,10 +59,13 @@ export function closePropertyEditor() {targetPropertyDefinition: undefined,}));+ void restoreFocus?.();}export function togglePropertyEditor(force?: boolean) {- setPropertyEditorOpen(force ?? !propertyEditorOpen());+ const next = force ?? !propertyEditorOpen();+ if (next) setPropertyEditorOpen(true);+ else closePropertyEditor();}export function setPropertyEditorMode(mode: PropertyEditorMode) {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsxindex ed8587e73f..27ffaace18 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx@@ -275,6 +275,9 @@ export const MarkdownShell: Component<menu={menu()}useBlockBoundary={false}portalScope={props.portalScope}+ applyTargetLabel={builderConfig.tags?.applyTargetLabel}+ isApplied={builderConfig.tags?.isApplied}+ onApplyTag={builderConfig.tags?.onCreate}/>)}</Show>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.tsindex cb969da243..adfb2ed3b8 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts@@ -170,7 +170,9 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {tagsPlugin({menu: tagsMenuOps,insertTags: config.tags.insertTags,- onCreateTag: config.tags.onCreate,+ onCreateTag: config.tags.applyTargetLabel+ ? undefined+ : config.tags.onCreate,onRemoveTag: config.tags.onRemove,setTags: config.tags.setTags,})diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.tsindex 0f0959cab2..5e7336ea52 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts@@ -50,6 +50,9 @@ export interface MentionsOptions {export interface TagsOptions {/** Insert inline tag mentions into the editor document. Defaults to true. */insertTags?: boolean;+ /** When set, selecting a tag opens a one-row prompt to apply it to this entity label. */+ applyTargetLabel?: string;+ isApplied?: (tag: TagMentionLifecycle) => boolean;onCreate?: (tag: TagMentionLifecycle) => void;onRemove?: (tag: TagMentionLifecycle) => void;setTags?: (tags: ReadonlySet<TagMentionLifecycle>) => void;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsxindex 398fac9063..4087d3e1a6 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsx@@ -28,8 +28,11 @@ import { useMenuKeyboardNavigation } from './useMenuKeyboardNavigation';false && clickOutside;false && floatWithSelection;-// py-2 on the menu container = 8px top + 8px bottom-const MENU_DECORATION_HEIGHT = 16;+// py-1.5 on the menu container = 6px top + 6px bottom+const MENU_DECORATION_HEIGHT = 12;+const EMOJI_ITEM_HEIGHT = 32;+const MAX_EMOJI_LIST_ITEMS = 7;+const MAX_EMOJI_LIST_HEIGHT = MAX_EMOJI_LIST_ITEMS * EMOJI_ITEM_HEIGHT;type EmojiMenuProps = {menu: MenuOperations;@@ -90,8 +93,22 @@ export function EmojiMenu(props: EmojiMenuProps) {>(undefined);const contentMaxHeight = () => {const h = menuAvailableHeight();- if (h === undefined) return undefined;- return Math.min(200, Math.max(0, h - MENU_DECORATION_HEIGHT));+ if (h === undefined) return MAX_EMOJI_LIST_HEIGHT;+ const availableContentHeight = Math.max(0, h - MENU_DECORATION_HEIGHT);+ const visibleItemCount = Math.floor(+ availableContentHeight / EMOJI_ITEM_HEIGHT+ );+ return Math.min(+ MAX_EMOJI_LIST_HEIGHT,+ visibleItemCount * EMOJI_ITEM_HEIGHT+ );+ };+ const contentHeight = () => {+ const itemCount = emojiOptions().length;+ if (itemCount === 0) return 0;+ const itemHeight = itemCount * EMOJI_ITEM_HEIGHT;+ if (contentMaxHeight() < EMOJI_ITEM_HEIGHT) return EMOJI_ITEM_HEIGHT;+ return Math.min(contentMaxHeight(), itemHeight);};const { isKeypressActive } = useIsKeyPressActive();@@ -271,12 +288,10 @@ export function EmojiMenu(props: EmojiMenuProps) {<VListdata={emojiOptions()}ref={setVirtualHandle}+ itemSize={EMOJI_ITEM_HEIGHT}class="scrollbar-hidden"style={{- height:- contentMaxHeight() !== undefined- ? `${contentMaxHeight()}px`- : '200px',+ height: `${contentHeight()}px`,'max-height': '100%',width: '100%',}}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/InlineFollowupMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/InlineFollowupMenu.tsxnew file mode 100644index 0000000000..5d88001b1f--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/InlineFollowupMenu.tsx@@ -0,0 +1,158 @@+import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';+import clickOutside from '@core/directive/clickOutside';+import { Hotkey, Surface } from '@ui';+import type { LexicalEditor } from 'lexical';+import {+ createEffect,+ For,+ type JSX,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';+import { floatWithSelection } from '../../directive/floatWithSelection';++export type InlineFollowupMenuOption = {+ id: string;+ label: JSX.Element;+ hotkey?: string;+ onSelect: () => void;+};++export function InlineFollowupMenu(props: {+ editor: LexicalEditor;+ open: boolean;+ selection?: Selection | null;+ options: readonly InlineFollowupMenuOption[];+ portalScope?: PortalScope;+ useBlockBoundary?: boolean;+ selectedIndex?: number;+ onSelectedIndexChange?: (index: number) => void;+ onClose: () => void;+}) {+ const selectedIndex = () => props.selectedIndex ?? 0;++ const boundedIndex = () => {+ const count = props.options.length;+ if (count === 0) return 0;+ return Math.min(Math.max(selectedIndex(), 0), count - 1);+ };++ createEffect(() => {+ if (!props.open) return;+ const bounded = boundedIndex();+ if (bounded !== selectedIndex()) {+ props.onSelectedIndexChange?.(bounded);+ }+ });++ const moveSelection = (delta: number) => {+ const count = props.options.length;+ if (count <= 1) return;+ props.onSelectedIndexChange?.((boundedIndex() + delta + count) % count);+ };++ const selectCurrent = () => {+ props.options[boundedIndex()]?.onSelect();+ };++ const isReservedNavigationKey = (event: KeyboardEvent) => {+ if (event.key.startsWith('Arrow')) return true;+ return (+ (event.ctrlKey || event.metaKey) &&+ (event.key === 'j' || event.key === 'k')+ );+ };++ const isTypingKey = (event: KeyboardEvent) =>+ event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;++ const keyDown = (event: KeyboardEvent) => {+ if (!props.open) return;++ if (event.key === 'Enter') {+ event.preventDefault();+ event.stopPropagation();+ selectCurrent();+ return;+ }++ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ props.onClose();+ return;+ }++ if (isReservedNavigationKey(event)) {+ event.preventDefault();+ event.stopPropagation();+ if (event.key === 'ArrowUp' || event.key === 'k') moveSelection(-1);+ if (event.key === 'ArrowDown' || event.key === 'j') moveSelection(1);+ return;+ }++ if (!isTypingKey(event)) {+ return;+ }++ props.onClose();+ };++ onMount(() => {+ document.addEventListener('keydown', keyDown, { capture: true });+ onCleanup(() => {+ document.removeEventListener('keydown', keyDown, { capture: true });+ });+ });++ return (+ <Show when={props.open}>+ <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: props.selection,+ reactiveOnContainer: props.editor.getRootElement(),+ useBlockBoundary: props.useBlockBoundary,+ }));+ clickOutside(el, () => () => props.onClose());+ }}+ >+ <Surface+ depth={2}+ class="py-1.5 shadow-lg shadow-drop-shadow rounded-xl"+ >+ <For each={props.options}>+ {(option, 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': boundedIndex() === index(),+ }}+ onMouseEnter={() => props.onSelectedIndexChange?.(index())}+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ option.onSelect();+ }}+ >+ <span class="min-w-0 flex-1 truncate">{option.label}</span>+ <Show when={option.hotkey}>+ {(hotkey) => <Hotkey shortcut={hotkey()} theme="subtle" />}+ </Show>+ </button>+ )}+ </For>+ </Surface>+ </div>+ </ScopedPortal>+ </Show>+ );+}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.tsxindex 33badd26c9..03ed0ce670 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TagsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TagsMenu.tsx@@ -29,8 +29,10 @@ import {CLOSE_INLINE_SEARCH_COMMAND,REMOVE_INLINE_SEARCH_COMMAND,} from '../../plugins';+import type { TagMentionLifecycle } from '../../plugins/tags';import { INSERT_TAG_MENTION_COMMAND } from '../../plugins/tags';import type { MenuOperations } from '../../shared/inlineMenu';+import { InlineFollowupMenu } from './InlineFollowupMenu';import { useMenuKeyboardNavigation } from './useMenuKeyboardNavigation';type TagMenuItem = {@@ -67,6 +69,8 @@ const TAG_COLOR_OPTIONS = [name: string;}[];+const FOLLOWUP_MENU_OPEN_DELAY_MS = 40;+function optionLabel(value: unknown): string | undefined {if (typeof value === 'object' &&@@ -107,6 +111,9 @@ export function TagsMenu(props: {menu: MenuOperations;portalScope?: PortalScope;useBlockBoundary?: boolean;+ applyTargetLabel?: string;+ isApplied?: (tag: TagMentionLifecycle) => boolean;+ onApplyTag?: (tag: TagMentionLifecycle) => void;}) {const tagsQuery = useTagsQuery();const currentTeamQuery = useCurrentTeamQuery();@@ -123,6 +130,13 @@ export function TagsMenu(props: {const [selectedScopeIndex, setSelectedScopeIndex] = createSignal(0);const [pendingCreate, setPendingCreate] =createSignal<PendingTagCreate | null>(null);+ const [pendingApplyTag, setPendingApplyTag] =+ createSignal<TagMentionLifecycle | null>(null);+ const [applyPromptSelection, setApplyPromptSelection] =+ createSignal<Selection | null>(null);+ const [applyPromptSelectedIndex, setApplyPromptSelectedIndex] =+ createSignal(0);+ let applyPromptOpenTimeout: ReturnType<typeof setTimeout> | undefined;const items = createMemo<TagMenuItem[]>(() => {const query = props.menu.searchTerm().trim().toLowerCase();@@ -175,7 +189,7 @@ export function TagsMenu(props: {createEffect(() => {if (props.menu.isOpen()) {setMountSelection(document.getSelection());- setSelectedIndex(0);+ if (!pendingApplyTag()) setSelectedIndex(0);} else {setMountSelection(null);setCreateStep(null);@@ -189,7 +203,13 @@ export function TagsMenu(props: {});const closeMenu = () => {+ if (applyPromptOpenTimeout) {+ clearTimeout(applyPromptOpenTimeout);+ applyPromptOpenTimeout = undefined;+ }props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);+ setPendingApplyTag(null);+ setApplyPromptSelection(null);props.menu.setIsOpen(false);};@@ -200,9 +220,32 @@ export function TagsMenu(props: {}props.editor.dispatchCommand(REMOVE_INLINE_SEARCH_COMMAND, undefined);props.editor.dispatchCommand(INSERT_TAG_MENTION_COMMAND, item);+ setCreateStep(null);+ props.menu.setSearchTerm('');++ const alreadyApplied = props.isApplied?.(item) ?? false;+ if (props.applyTargetLabel && props.onApplyTag && !alreadyApplied) {+ props.menu.setIsOpen(false);+ if (applyPromptOpenTimeout) clearTimeout(applyPromptOpenTimeout);+ applyPromptOpenTimeout = setTimeout(() => {+ applyPromptOpenTimeout = undefined;+ setApplyPromptSelection(document.getSelection());+ setPendingApplyTag(item);+ setApplyPromptSelectedIndex(0);+ }, FOLLOWUP_MENU_OPEN_DELAY_MS);+ return;+ }+props.menu.setIsOpen(false);};+ const applyPendingTag = () => {+ const tag = pendingApplyTag();+ if (!tag) return;+ props.onApplyTag?.(tag);+ closeMenu();+ };+const beginCreate = () => {const label = createLabel();if (!showCreateRow() || !label) return;@@ -339,11 +382,20 @@ export function TagsMenu(props: {},});- const focusOut = () => closeMenu();+ const focusOut = () => {+ if (applyPromptOpenTimeout) {+ return;+ }+ if (pendingApplyTag()) return;+ closeMenu();+ };onMount(() => {document.addEventListener('focusout', focusOut);- onCleanup(() => document.removeEventListener('focusout', focusOut));+ onCleanup(() => {+ if (applyPromptOpenTimeout) clearTimeout(applyPromptOpenTimeout);+ document.removeEventListener('focusout', focusOut);+ });});const contentMaxHeight = () => {@@ -353,129 +405,175 @@ export function TagsMenu(props: {};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={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());+ }}>- <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() }}+ <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>+ }>- <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>- }+ <TagMenuItems+ items={items()}+ selectedIndex={selectedIndex()}+ createRowIndex={createRowIndex()}+ showCreateRow={showCreateRow()}+ createLabel={createLabel()}+ teamName={teamName()}+ contentMaxHeight={contentMaxHeight()}+ onItemMouseEnter={setSelectedIndex}+ onItemSelect={selectItem}+ onCreateMouseEnter={() =>+ setSelectedIndex(createRowIndex())+ }+ onCreateSelect={beginCreate}+ />+ </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>+ <InlineFollowupMenu+ editor={props.editor}+ open={pendingApplyTag() !== null}+ selection={applyPromptSelection()}+ portalScope={props.portalScope}+ useBlockBoundary={props.useBlockBoundary}+ selectedIndex={applyPromptSelectedIndex()}+ onSelectedIndexChange={setApplyPromptSelectedIndex}+ onClose={closeMenu}+ options={[+ {+ id: 'apply-tag',+ label: <>Add tag to {props.applyTargetLabel ?? ''}</>,+ hotkey: 'enter',+ onSelect: applyPendingTag,+ },+ ]}+ />+ </>+ );+}++function TagMenuItems(props: {+ items: TagMenuItem[];+ selectedIndex: number;+ createRowIndex: number;+ showCreateRow: boolean;+ createLabel: string;+ teamName: string;+ contentMaxHeight: string;+ onItemMouseEnter: (index: number) => void;+ onItemSelect: (item: TagMenuItem) => void;+ onCreateMouseEnter: () => void;+ onCreateSelect: () => void;+}) {+ return (+ <div+ class="overflow-y-auto scrollbar-hidden"+ style={{ 'max-height': props.contentMaxHeight }}+ >+ <For each={props.items}>+ {(item, index) => (+ <ScrollIntoViewOnSelect selected={props.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': props.selectedIndex === index(),+ }}+ onMouseEnter={() => props.onItemMouseEnter(index())}+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ props.onItemSelect(item);+ }}>- {(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>+ <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">+ {props.teamName}+ </span>+ </Show>+ </button>+ </ScrollIntoViewOnSelect>+ )}+ </For>+ <Show when={props.showCreateRow}>+ <ScrollIntoViewOnSelect+ selected={props.selectedIndex === props.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': props.selectedIndex === props.createRowIndex,+ }}+ onMouseEnter={props.onCreateMouseEnter}+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ props.onCreateSelect();+ }}+ >+ <PlusIcon class="size-3 shrink-0 text-ink-muted" />+ <span class="min-w-0 truncate">+ Create tag "{props.createLabel}"+ </span>+ </button>+ </ScrollIntoViewOnSelect>+ </Show>+ </div>);}