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(tags): tagg settings page, tag editor (#4996)
Seamus1ad399a097b0
diff --git a/apps/web/src/components/ui/components/Dialog.tsx b/apps/web/src/components/ui/components/Dialog.tsxindex e86016de7a..28ea9bb3b7 100644--- a/apps/web/src/components/ui/components/Dialog.tsx+++ b/apps/web/src/components/ui/components/Dialog.tsx@@ -68,7 +68,7 @@ export function Dialog(props: DialogProps) {<KobalteDialog.Portal><KobalteDialog.Overlayclass={cn(- 'hidden fixed inset-0 z-modal bg-modal-overlay',+ 'invisible fixed inset-0 z-modal bg-modal-overlay',animateOnOpen() && 'dialog-overlay-open-animation',Boolean(props.visibleScrim) && 'visible')}diff --git a/apps/web/src/features/property/editor/PropertyEditorModal.tsx b/apps/web/src/features/property/editor/PropertyEditorModal.tsxindex 7e2e145044..bf8491203b 100644--- a/apps/web/src/features/property/editor/PropertyEditorModal.tsx+++ b/apps/web/src/features/property/editor/PropertyEditorModal.tsx@@ -2,6 +2,7 @@ import { toast } from '@core/component/Toast/Toast';import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';import type { IUser } from '@core/user';import { idToDisplayName, idToEmail } from '@core/user/util';+import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';import { useDateSearch } from '@core/util/dateSearch/useDateSearch';import { fuzzyFilter } from '@core/util/fuzzy';import {@@ -9,6 +10,8 @@ import {useListKeyBindings,} from '@core/util/useListKeyBindings';import { type EntityData, InlineEntity } from '@entity';+import CircleDashedEmpty from '@phosphor/circle-dashed.svg';+import PencilIcon from '@phosphor/pencil-simple.svg';import PropertiesIcon from '@phosphor/sliders-horizontal.svg';import TagIcon from '@phosphor/tag-simple.svg';import { type CombinedEntity, getEntityName, getEntityType } from '@property';@@ -18,6 +21,10 @@ import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';import { usePropertySelection } from '@property/hooks';import { usePropertyEntityDisplay } from '@property/hooks/usePropertyEntityDisplay';import { TagDot } from '@property/tags/TagDot';+import {+ TagEditorDialog,+ type TagEditorDialogMode,+} from '@property/tags/TagEditorDialog';import type {Property,PropertyApiValues,@@ -81,6 +88,7 @@ import {function ListItem(props: {id: string;isSelected: boolean;+ as?: 'button' | 'div';disabled?: boolean;onClick: (event: MouseEvent) => void;onMouseEnter: () => void;@@ -89,6 +97,7 @@ function ListItem(props: {}) {return (<CommandMenuListItem+ as={props.as}id={props.id}selected={props.isSelected}disabled={props.disabled}@@ -508,6 +517,11 @@ function TagAssignmentEditor(props: {const currentTeamQuery = useCurrentTeamQuery();const addOption = useAddEntityPropertyOptionMutation();const removeOption = useRemoveEntityPropertyOptionMutation();+ const [tagEditorMode, setTagEditorMode] =+ createSignal<TagEditorDialogMode | null>(null);+ const [tagEditorOpen, setTagEditorOpen] = createControlledOpenSignal(false, {+ id: 'property-tag-edit',+ });const singleEntity = () =>props.entities.length === 1 ? props.entities[0] : undefined;const entityPropertiesQuery = useEntityPropertiesQuery(@@ -576,6 +590,13 @@ function TagAssignmentEditor(props: {}return items;});+ const tagDefinitionsById = createMemo(() => {+ const definitions = new Map<string, PropertyDefinitionDetailResponse>();+ for (const item of tagItems()) {+ definitions.set(item.definition.id, item.definition);+ }+ return definitions;+ });const isFullyApplied = (item: TagOptionItem) => {if (props.entities.length === 0) return false;@@ -608,6 +629,41 @@ function TagAssignmentEditor(props: {return [...applied, ...remaining];});+ const createLabel = () => props.searchValue().trim();+ const exactTagMatchExists = () => {+ const label = createLabel().toLowerCase();+ return (+ !!label &&+ tagItems().some(+ (item) => tagOptionLabel(item.option).toLowerCase() === label+ )+ );+ };+ const showCreateRow = () =>+ createLabel().length > 0 && !exactTagMatchExists();+ const hasSearch = () => createLabel().length > 0;+ const hasAnyAppliedTags = () => {+ for (const byDefinition of localTagIds().values()) {+ for (const optionIds of byDefinition.values()) {+ if (optionIds.length > 0) return true;+ }+ }+ return false;+ };+ const showClearAllRow = () => hasAnyAppliedTags();+ const showClearAllAtTop = () => showClearAllRow() && !hasSearch();+ const showClearAllAtBottom = () => showClearAllRow() && hasSearch();+ const itemRowIndex = (index: number) => index + (showClearAllAtTop() ? 1 : 0);+ const createRowIndex = () =>+ filteredItems().length + (showClearAllAtTop() ? 1 : 0);+ const clearAllRowIndex = () =>+ showClearAllAtTop()+ ? 0+ : filteredItems().length + (showCreateRow() ? 1 : 0);+ const rowCount = () =>+ filteredItems().length ++ (showClearAllRow() ? 1 : 0) ++ (showCreateRow() ? 1 : 0);const selectedGroupSize = createMemo(() => filteredItems().filter(wasFullyAppliedWhenOpened).length);@@ -692,24 +748,160 @@ function TagAssignmentEditor(props: {}};+ const openCreateTag = () => {+ const label = createLabel();+ if (!showCreateRow() || !label) return;++ setTagEditorMode({+ type: 'create',+ initialScope: currentTeamQuery.data?.team ? 'team' : 'user',+ initialLabel: label,+ });+ setTagEditorOpen(true, false);+ };++ const openEditTag = (item: TagOptionItem) => {+ setTagEditorMode({+ type: 'edit',+ tag: {+ scope: item.scope,+ propertyDefinitionId: item.definition.id,+ option: item.option,+ },+ });+ setTagEditorOpen(true, false);+ };++ const clearAllTags = async (event?: KeyboardEvent | MouseEvent) => {+ if (!showClearAllRow()) return;++ const shouldClose = !event?.shiftKey;+ const previousTagIds = localTagIds();+ setHasEditedTags(true);+ setLocalTagIds(+ new Map(+ props.entities.map((entity) => [entity.id, new Map<string, string[]>()])+ )+ );++ try {+ const updates: Promise<void>[] = [];+ for (const entity of props.entities) {+ const entityType = macroEntityToPropertyEntityType(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,+ property: tagDefinitionDomain(definition),+ optionId,+ optimisticOptionIds: [],+ })+ );+ }+ }+ }++ if (shouldClose) closePropertyEditor();+ await Promise.all(updates);+ } catch (error) {+ if (!shouldClose) {+ setLocalTagIds(previousTagIds);+ }+ console.error('Failed to clear tags', error);+ }+ };++ const applyCreatedTag = async (+ definition: PropertyDefinitionDetailResponse,+ optionId: string+ ) => {+ const previousTagIds = localTagIds();+ setHasEditedTags(true);+ setLocalTagIds((prev) => {+ const next = new Map(prev);+ for (const entity of props.entities) {+ const byDefinition = new Map(next.get(entity.id) ?? []);+ const current = byDefinition.get(definition.id) ?? [];+ byDefinition.set(+ definition.id,+ current.includes(optionId) ? current : [...current, optionId]+ );+ next.set(entity.id, byDefinition);+ }+ return next;+ });++ try {+ await Promise.all(+ props.entities.map(async (entity) => {+ const entityType = macroEntityToPropertyEntityType(entity);+ const current = getTagIds(previousTagIds, entity.id, definition.id);+ if (current.includes(optionId)) return;++ await addOption.mutateAsync({+ entityId: entity.id,+ entityType,+ property: tagDefinitionDomain(definition),+ optionId,+ optimisticOptionIds: [...current, optionId],+ });+ })+ );+ closePropertyEditor();+ } catch (error) {+ setLocalTagIds(previousTagIds);+ console.error('Failed to apply created tag', error);+ }+ };+props.setKeybindings({next: () => {- const len = filteredItems().length;+ const len = rowCount();if (len === 0) return;props.setSelectedIndex((prev) => (prev + 1) % len);},previous: () => {- const len = filteredItems().length;+ const len = rowCount();if (len === 0) return;props.setSelectedIndex((prev) => (prev - 1 + len) % len);},select: (event) => {- const item = filteredItems()[props.selectedIndex()];+ if (showClearAllRow() && props.selectedIndex() === clearAllRowIndex()) {+ void clearAllTags(event);+ return;+ }++ if (showCreateRow() && props.selectedIndex() === createRowIndex()) {+ openCreateTag();+ return;+ }++ const item =+ filteredItems()[props.selectedIndex() - (showClearAllAtTop() ? 1 : 0)];if (item) void toggleTag(item, event);},});const selector = createSelector(props.selectedIndex);+ const renderClearAllRow = () => (+ <ListItem+ id={`tag-assignment-option-${clearAllRowIndex()}`}+ isSelected={selector(clearAllRowIndex())}+ onClick={(event) => void clearAllTags(event)}+ onMouseEnter={() => props.setSelectedIndexFromMouse(clearAllRowIndex())}+ class="scroll-m-2"+ >+ <CircleDashedEmpty class="size-4 text-ink-muted opacity-50" />+ <span class="min-w-0 flex-1 truncate text-ink-muted">Clear all tags</span>+ </ListItem>+ );return (<Show@@ -717,7 +909,7 @@ function TagAssignmentEditor(props: {fallback={<CommandMenuEmptyState>Loading tags...</CommandMenuEmptyState>}><Show- when={filteredItems().length > 0}+ when={rowCount() > 0}fallback={<CommandMenuEmptyState>{(tagsQuery.data ?? []).length === 0@@ -727,6 +919,7 @@ function TagAssignmentEditor(props: {}><div class="max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden p-2">+ <Show when={showClearAllAtTop()}>{renderClearAllRow()}</Show><For each={filteredItems()}>{(item, index) => (<>@@ -738,10 +931,13 @@ function TagAssignmentEditor(props: {<div class="mx-2 my-1 h-px bg-edge-muted/50" /></Show><ListItem- id={`tag-assignment-option-${index()}`}- isSelected={selector(index())}+ as="div"+ id={`tag-assignment-option-${itemRowIndex(index())}`}+ isSelected={selector(itemRowIndex(index()))}onClick={(event) => void toggleTag(item, event)}- onMouseEnter={() => props.setSelectedIndexFromMouse(index())}+ onMouseEnter={() =>+ props.setSelectedIndexFromMouse(itemRowIndex(index()))+ }class="scroll-m-2"><OptionCheckBox checked={isFullyApplied(item)} multiselect />@@ -754,12 +950,78 @@ function TagAssignmentEditor(props: {{teamName()}</span></Show>+ <button+ type="button"+ aria-label={`Edit ${tagOptionLabel(item.option)}`}+ class="ml-1 flex size-5 shrink-0 items-center justify-center rounded text-ink-extra-muted opacity-0 outline-none hover:bg-hover hover:text-ink group-hover:opacity-100 focus-visible:opacity-100"+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ openEditTag(item);+ }}+ >+ <PencilIcon class="size-3.5" />+ </button></ListItem></>)}</For>+ <Show when={showCreateRow()}>+ <Show when={filteredItems().length > 0}>+ <div class="mx-2 my-1 h-px bg-edge-muted/50" />+ </Show>+ <ListItem+ id={`tag-assignment-option-${createRowIndex()}`}+ isSelected={selector(createRowIndex())}+ onClick={openCreateTag}+ onMouseEnter={() =>+ props.setSelectedIndexFromMouse(createRowIndex())+ }+ class="scroll-m-2"+ >+ <TagIcon class="size-4 text-ink-muted opacity-50" />+ <span class="min-w-0 flex-1 truncate">+ Create new tag "{createLabel()}"+ </span>+ </ListItem>+ </Show>+ <Show when={showClearAllAtBottom()}>+ <Show when={filteredItems().length > 0 || showCreateRow()}>+ <div class="mx-2 my-1 h-px bg-edge-muted/50" />+ </Show>+ {renderClearAllRow()}+ </Show></div></Show>+ <TagEditorDialog+ open={tagEditorOpen()}+ mode={tagEditorMode()}+ teamAvailable={Boolean(currentTeamQuery.data?.team)}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ queueMicrotask(() => {+ const selectedRow = document.getElementById(+ `tag-assignment-option-${props.selectedIndex()}`+ );+ if (selectedRow instanceof HTMLElement) {+ selectedRow.focus();+ }+ });+ }}+ onCreateSuccess={async (result) => {+ const definition = result.tagSet.definition;+ if (!definition) return;+ await applyCreatedTag(definition, result.option.id);+ }}+ onClose={() => {+ setTagEditorOpen(false, false);+ setTagEditorMode(null);+ }}+ /></Show>);}diff --git a/apps/web/src/features/property/tags/EntityRowTags.tsx b/apps/web/src/features/property/tags/EntityRowTags.tsxindex e7990a57a2..03f2f59a50 100644--- a/apps/web/src/features/property/tags/EntityRowTags.tsx+++ b/apps/web/src/features/property/tags/EntityRowTags.tsx@@ -1,11 +1,17 @@import CaretDownIcon from '@phosphor/caret-down.svg';import CircleDashedEmpty from '@phosphor/circle-dashed.svg';import FilterIcon from '@phosphor/funnel-simple.svg';+import PencilIcon from '@phosphor/pencil-simple.svg';import { EntityType } from '@service-properties/generated/schemas/entityType';import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';import { cn, HoverCard, Layer } from '@ui';import { createSignal, For, Match, Show, Switch } from 'solid-js';import { TagDot } from './TagDot';+import {+ type EditableTag,+ TagEditorDialog,+ type TagEditorDialogMode,+} from './TagEditorDialog';import { TagPicker } from './TagPicker';import { type ResolvedTag, useDocTags, useSoupDocTags } from './useDocTags';@@ -23,53 +29,126 @@ const chipClass = cn(function HoverTagRow(props: {tag: ResolvedTag;onFilter?: (id: string) => void;+ onEdit: (tag: ResolvedTag) => void;}) {return (- <Show- when={props.onFilter}- fallback={- <span class="flex items-center gap-1.5 whitespace-nowrap px-1.5 py-1 text-ink">- <TagDot color={props.tag.color} />- <span class="min-w-0 truncate">{props.tag.label}</span>- </span>- }- >- {(onFilter) => (- <button- type="button"- class="flex items-center gap-1.5 whitespace-nowrap rounded-md px-1.5 py-1 text-left text-ink hover:bg-hover"- onClick={() => onFilter()(props.tag.optionId)}- >- <TagDot color={props.tag.color} />- <span class="min-w-0 truncate">{props.tag.label}</span>- </button>- )}- </Show>+ <div class="flex items-center gap-1 whitespace-nowrap rounded-md px-1.5 py-1 text-ink hover:bg-hover">+ <Show+ when={props.onFilter}+ fallback={+ <span class="flex min-w-0 flex-1 items-center gap-1.5">+ <TagDot color={props.tag.color} />+ <span class="min-w-0 truncate">{props.tag.label}</span>+ </span>+ }+ >+ {(onFilter) => (+ <button+ type="button"+ class="flex min-w-0 flex-1 items-center gap-1.5 text-left"+ onClick={() => onFilter()(props.tag.optionId)}+ >+ <TagDot color={props.tag.color} />+ <span class="min-w-0 truncate">{props.tag.label}</span>+ </button>+ )}+ </Show>+ <button+ type="button"+ aria-label={`Edit ${props.tag.label}`}+ class="flex size-5 shrink-0 items-center justify-center rounded text-ink-extra-muted hover:bg-hover hover:text-ink"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ props.onEdit(props.tag);+ }}+ >+ <PencilIcon class="size-3.5" />+ </button>+ </div>);}-function TagChip(props: {+function TagHoverContent(props: {tag: ResolvedTag;- docTags: DocTags;onFilterByTag?: (id: string) => void;+ onEdit: (tag: ResolvedTag) => void;}) {- const [pickerOpen, setPickerOpen] = createSignal(false);return (- <Layer depth={2}>- <HoverCard- placement="bottom-start"- disabled={pickerOpen() || !props.onFilterByTag}- content={+ <div class="flex items-center gap-1 rounded-md px-1.5 py-1 text-ink hover:bg-hover">+ <Show+ when={props.onFilterByTag}+ fallback={+ <span class="flex min-w-0 flex-1 items-center gap-1.5">+ <TagDot color={props.tag.color} />+ <span class="min-w-0 truncate">{props.tag.label}</span>+ </span>+ }+ >+ {(onFilterByTag) => (<buttontype="button"- class="flex items-center gap-1.5 whitespace-nowrap rounded-md px-1.5 py-1 text-ink hover:bg-hover"- onClick={() => props.onFilterByTag?.(props.tag.optionId)}+ class="flex min-w-0 flex-1 items-center gap-1.5 whitespace-nowrap text-left"+ onClick={() => onFilterByTag()(props.tag.optionId)}>- <FilterIcon class="size-3.5 text-ink-muted" />+ <FilterIcon class="size-3.5 shrink-0 text-ink-muted" /><span>Filter by <span class="font-medium">{props.tag.label}</span></span></button>+ )}+ </Show>+ <button+ type="button"+ aria-label={`Edit ${props.tag.label}`}+ class="flex size-5 shrink-0 items-center justify-center rounded text-ink-extra-muted hover:bg-hover hover:text-ink"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ props.onEdit(props.tag);+ }}+ >+ <PencilIcon class="size-3.5" />+ </button>+ </div>+ );+}++function editableTagFromResolved(+ docTags: DocTags,+ tag: ResolvedTag+): EditableTag | undefined {+ const set = docTags.tagSets().find((tagSet) => tagSet.scope === tag.scope);+ const option = set?.options.find(+ (candidate) => candidate.id === tag.optionId+ );+ if (!set?.definition || !option) return undefined;++ return {+ scope: tag.scope,+ propertyDefinitionId: set.definition.id,+ option,+ };+}++function TagChip(props: {+ tag: ResolvedTag;+ docTags: DocTags;+ onFilterByTag?: (id: string) => void;+ onEdit: (tag: ResolvedTag) => void;+}) {+ const [pickerOpen, setPickerOpen] = createSignal(false);+ return (+ <Layer depth={2}>+ <HoverCard+ placement="bottom-start"+ disabled={pickerOpen()}+ content={+ <TagHoverContent+ tag={props.tag}+ onFilterByTag={props.onFilterByTag}+ onEdit={props.onEdit}+ />}><TagPicker@@ -90,6 +169,7 @@ function TagOverflow(props: {tags: ResolvedTag[];docTags: DocTags;onFilterByTag?: (id: string) => void;+ onEdit: (tag: ResolvedTag) => void;}) {const [pickerOpen, setPickerOpen] = createSignal(false);const dots = () => props.tags.slice(0, MAX_OVERFLOW_DOTS);@@ -105,7 +185,11 @@ function TagOverflow(props: {<div class="flex flex-col gap-0.5"><For each={props.tags}>{(tag) => (- <HoverTagRow tag={tag} onFilter={props.onFilterByTag} />+ <HoverTagRow+ tag={tag}+ onFilter={props.onFilterByTag}+ onEdit={props.onEdit}+ />)}</For></div>@@ -157,6 +241,15 @@ export function EntityRowTags(props: {const maxVisible = () => props.maxVisible ?? DEFAULT_MAX_VISIBLE;const visible = () => docTags.appliedTags().slice(0, maxVisible());const hidden = () => docTags.appliedTags().slice(maxVisible());+ const [editorMode, setEditorMode] = createSignal<TagEditorDialogMode | null>(+ null+ );++ const openEdit = (tag: ResolvedTag) => {+ const editable = editableTagFromResolved(docTags, tag);+ if (!editable) return;+ setEditorMode({ type: 'edit', tag: editable });+ };return (<Show when={docTags.appliedTags().length > 0}>@@ -170,6 +263,7 @@ export function EntityRowTags(props: {tag={tag}docTags={docTags}onFilterByTag={props.onFilterByTag}+ onEdit={openEdit}/>)}</For>@@ -178,8 +272,17 @@ export function EntityRowTags(props: {tags={hidden()}docTags={docTags}onFilterByTag={props.onFilterByTag}+ onEdit={openEdit}/></Show>+ <TagEditorDialog+ open={editorMode() !== null}+ mode={editorMode()}+ teamAvailable={Boolean(+ docTags.tagSets().some((set) => set.scope === 'team')+ )}+ onClose={() => setEditorMode(null)}+ /></div></Show>);diff --git a/apps/web/src/features/property/tags/TagEditorDialog.tsx b/apps/web/src/features/property/tags/TagEditorDialog.tsxnew file mode 100644index 0000000000..01cea81791--- /dev/null+++ b/apps/web/src/features/property/tags/TagEditorDialog.tsx@@ -0,0 +1,306 @@+import { TabsInset } from '@core/component/TabsInset';+import TagIcon from '@phosphor/tag-simple.svg';+import TrashIcon from '@phosphor/trash.svg';+import XIcon from '@phosphor/x.svg';+import {+ type CreateTagResult,+ useCreateTagMutation,+ useDeletePropertyOptionMutation,+ useUpdatePropertyOptionMutation,+} from '@queries/properties/tags';+import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';+import type { TagScope } from '@service-properties/generated/schemas/tagScope';+import { Button, CommandMenuShell, cn, Dialog, Hotkey, Tooltip } from '@ui';+import type { JSX } from 'solid-js';+import { createEffect, createMemo, createSignal, For, Show } from 'solid-js';+import { TagDot } from './TagDot';+import { DEFAULT_TAG_COLOR, TAG_COLOR_OPTIONS } from './tagColors';++export type EditableTag = {+ scope: TagScope;+ propertyDefinitionId: string;+ option: PropertyOptionResponse;+};++export type TagEditorDialogMode =+ | {+ type: 'create';+ initialScope: TagScope;+ initialLabel?: string;+ }+ | {+ type: 'edit';+ tag: EditableTag;+ };++function optionLabel(option: PropertyOptionResponse): string {+ return option.value.type === 'string' ? option.value.value : '';+}++function initialColor(mode: TagEditorDialogMode): string {+ if (mode.type === 'create') return DEFAULT_TAG_COLOR;+ return mode.tag.option.color ?? DEFAULT_TAG_COLOR;+}++function initialLabel(mode: TagEditorDialogMode): string {+ return mode.type === 'create'+ ? (mode.initialLabel ?? '')+ : optionLabel(mode.tag.option);+}++function initialScope(mode: TagEditorDialogMode): TagScope {+ return mode.type === 'create' ? mode.initialScope : mode.tag.scope;+}++function EditorRow(props: { label: string; children: JSX.Element }) {+ return (+ <div class="flex min-h-12 items-center gap-5 px-4 py-3">+ <div class="w-22 shrink-0 text-xs font-medium text-ink-extra-muted">+ {props.label}+ </div>+ <div class="min-w-0 flex-1">{props.children}</div>+ </div>+ );+}++export function TagEditorDialog(props: {+ open: boolean;+ mode: TagEditorDialogMode | null;+ teamAvailable?: boolean;+ onCloseAutoFocus?: (event: Event) => void;+ onCreateSuccess?: (result: CreateTagResult) => void | Promise<void>;+ onClose: () => void;+}) {+ const [label, setLabel] = createSignal('');+ const [color, setColor] = createSignal(DEFAULT_TAG_COLOR);+ const [scope, setScope] = createSignal<TagScope>('user');+ const createTag = useCreateTagMutation();+ const updateTag = useUpdatePropertyOptionMutation();+ const deleteTag = useDeletePropertyOptionMutation();+ let nameInputRef: HTMLInputElement | undefined;++ createEffect(() => {+ const mode = props.mode;+ if (!props.open || !mode) return;+ setLabel(initialLabel(mode));+ setColor(initialColor(mode));+ setScope(+ mode.type === 'create' &&+ mode.initialScope === 'team' &&+ !props.teamAvailable+ ? 'user'+ : initialScope(mode)+ );++ if (mode.type === 'create') {+ requestAnimationFrame(() => {+ nameInputRef?.focus();+ });+ }+ });++ const title = () =>+ props.mode?.type === 'create' ? 'Create tag' : 'Edit tag';+ const pending = () =>+ createTag.isPending || updateTag.isPending || deleteTag.isPending;+ const trimmedLabel = () => label().trim();++ const dirty = createMemo(() => {+ const mode = props.mode;+ if (!mode) return false;+ if (mode.type === 'create') return trimmedLabel().length > 0;++ return (+ trimmedLabel() !== initialLabel(mode) || color() !== initialColor(mode)+ );+ });++ const canSubmit = () => !!props.mode && trimmedLabel().length > 0 && dirty();++ const close = () => {+ if (pending()) return;+ props.onClose();+ };++ const submit = () => {+ const mode = props.mode;+ const value = trimmedLabel();+ if (!mode || !value || pending()) return;++ if (mode.type === 'create') {+ createTag.mutate(+ { scope: scope(), value, color: color() },+ {+ onSuccess: async (result) => {+ await props.onCreateSuccess?.(result);+ props.onClose();+ },+ }+ );+ return;+ }++ const body: {+ value?: string;+ color?: string;+ } = {};++ if (value !== initialLabel(mode)) body.value = value;+ if (color() !== initialColor(mode)) body.color = color();++ updateTag.mutate(+ {+ propertyDefinitionId: mode.tag.propertyDefinitionId,+ optionId: mode.tag.option.id,+ body,+ },+ { onSuccess: props.onClose }+ );+ };++ const remove = () => {+ const mode = props.mode;+ if (!mode || mode.type !== 'edit' || pending()) return;++ deleteTag.mutate(+ {+ propertyDefinitionId: mode.tag.propertyDefinitionId,+ optionId: mode.tag.option.id,+ },+ { onSuccess: props.onClose }+ );+ };++ const handleKeyDown = (event: KeyboardEvent) => {+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {+ event.preventDefault();+ if (canSubmit()) submit();+ }+ };++ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => !open && close()}+ onCloseAutoFocus={props.onCloseAutoFocus}+ >+ <CommandMenuShell depth={2} class="text-sm" onKeyDown={handleKeyDown}>+ <CommandMenuShell.Header class="my-0 h-13 gap-3 border-b-0 px-4">+ <span class="text-ink-muted">+ <TagIcon class="size-3.5" />+ </span>+ <Dialog.Title+ as="span"+ class="min-w-0 flex-1 truncate text-sm font-semibold text-ink-extra-muted"+ >+ {title()}+ </Dialog.Title>+ <Dialog.CloseButton+ as={Button}+ variant="ghost"+ size="icon-sm"+ disabled={pending()}+ label="Close"+ >+ <XIcon />+ </Dialog.CloseButton>+ </CommandMenuShell.Header>+ <CommandMenuShell.Body>+ <div class="bg-surface">+ <EditorRow label="Name">+ <input+ ref={nameInputRef}+ autofocus={props.mode?.type === 'create'}+ value={label()}+ onInput={(event) => setLabel(event.currentTarget.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && canSubmit()) submit();+ }}+ class="h-9 w-full rounded-md border border-edge-muted bg-surface px-3 text-sm text-ink outline-none placeholder:text-ink/30 focus:border-accent"+ placeholder="Tag name"+ />+ </EditorRow>++ <EditorRow label="Color">+ <div class="flex flex-wrap items-center gap-2">+ <For each={TAG_COLOR_OPTIONS}>+ {(option) => (+ <Tooltip label={option.name}>+ <button+ type="button"+ aria-label={option.name}+ onClick={() => setColor(option.color)}+ class={cn(+ 'flex size-7 items-center justify-center rounded-md border outline-none hover:bg-hover focus-visible:border-accent',+ color() === option.color+ ? 'border-accent bg-accent-bg'+ : 'border-edge-muted'+ )}+ >+ <TagDot color={option.color} class="size-3.5" />+ </button>+ </Tooltip>+ )}+ </For>+ </div>+ </EditorRow>++ <Show when={props.mode?.type === 'create'}>+ <EditorRow label="Sharing">+ <TabsInset+ depth={0}+ list={[+ { value: 'team', label: 'Team' },+ { value: 'user', label: 'Personal' },+ ]}+ value={scope()}+ onChange={(value) => {+ if (value === 'team' && !props.teamAvailable) return;+ if (value === 'team' || value === 'user') {+ setScope(value);+ }+ }}+ />+ </EditorRow>+ </Show>+ </div>+ </CommandMenuShell.Body>+ <CommandMenuShell.Footer class="gap-2 border-t-0 py-3">+ <Show when={props.mode?.type === 'edit'}>+ <Button+ variant="danger"+ size="sm"+ class="rounded-lg"+ disabled={pending()}+ onClick={remove}+ >+ <TrashIcon class="size-4" />+ Delete+ </Button>+ </Show>+ <div class="ml-auto flex items-center gap-2">+ <Button+ variant="ghost"+ size="sm"+ class="rounded-lg"+ disabled={pending()}+ onClick={close}+ >+ Cancel+ </Button>+ <Button+ variant={canSubmit() ? 'active' : 'ghost'}+ depth={3}+ class="gap-3 rounded-lg border-0"+ disabled={!canSubmit() || pending()}+ onClick={submit}+ >+ Save+ <Hotkey shortcut="cmd+enter" theme="current" />+ </Button>+ </div>+ </CommandMenuShell.Footer>+ </CommandMenuShell>+ </Dialog>+ );+}diff --git a/apps/web/src/features/property/tags/TagPicker.tsx b/apps/web/src/features/property/tags/TagPicker.tsxindex ec31205134..f4f9d5e5d0 100644--- a/apps/web/src/features/property/tags/TagPicker.tsx+++ b/apps/web/src/features/property/tags/TagPicker.tsx@@ -1,5 +1,6 @@import { Popover } from '@kobalte/core/popover';import CircleDashedEmpty from '@phosphor/circle-dashed.svg';+import PencilIcon from '@phosphor/pencil-simple.svg';import PlusIcon from '@phosphor/plus.svg';import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';import {@@ -9,6 +10,7 @@ import {} from '@property/editors/selectors/PropertyOptionSelector';import { useAddPropertyOptionMutation } from '@queries/properties/options';import {+ type CreateTagResult,invalidateTags,useEnsureTagSetMutation,} from '@queries/properties/tags';@@ -28,7 +30,12 @@ import {untrack,} from 'solid-js';import { TagDot } from './TagDot';-import { DEFAULT_TAG_COLOR, type TAG_COLORS } from './tagColors';+import {+ type EditableTag,+ TagEditorDialog,+ type TagEditorDialogMode,+} from './TagEditorDialog';+import { DEFAULT_TAG_COLOR, TAG_COLOR_OPTIONS } from './tagColors';import type { ResolvedTag, useDocTags } from './useDocTags';type DocTags = ReturnType<typeof useDocTags>;@@ -39,24 +46,9 @@ type TagOptionItem = {};type CreateStep = 'color' | 'scope';--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;-}[];+type CreateTagSuccessHandler = (+ result: CreateTagResult+) => void | Promise<void>;function optionLabel(option: PropertyOptionResponse): string {return option.value.type === 'string' ? option.value.value : '';@@ -79,6 +71,12 @@ export function TagPicker(props: {onOpenChange?: (open: boolean) => void;}) {const [open, setOpen] = createSignal(false);+ const [editorMode, setEditorMode] = createSignal<TagEditorDialogMode | null>(+ null+ );+ const [createSuccessHandler, setCreateSuccessHandler] =+ createSignal<CreateTagSuccessHandler>();+ const currentTeamQuery = useCurrentTeamQuery();let saveAndClose: (() => Promise<void>) | undefined;const setOpenState = (value: boolean) => {@@ -100,30 +98,53 @@ export function TagPicker(props: {};return (- <Popover- open={open()}- onOpenChange={handleOpenChange}- placement="bottom-start"- gutter={4}- >- <Popover.Trigger- type="button"- class={props.triggerClass}- aria-label={props.triggerLabel}+ <>+ <Popover+ open={open()}+ onOpenChange={handleOpenChange}+ placement="bottom-start"+ gutter={4}>- {props.children}- </Popover.Trigger>- <Show when={open()}>- <TagPickerBody- docTags={props.docTags}- onClose={() => setOpenState(false)}- registerSave={(handler) => {- saveAndClose = handler;- }}- suppressInitialOutsideEvents={false}- />- </Show>- </Popover>+ <Popover.Trigger+ type="button"+ class={props.triggerClass}+ aria-label={props.triggerLabel}+ >+ {props.children}+ </Popover.Trigger>+ <Show when={open()}>+ <TagPickerBody+ docTags={props.docTags}+ onClose={() => setOpenState(false)}+ onOpenCreateEditor={(mode, onCreateSuccess) => {+ setCreateSuccessHandler(() => onCreateSuccess);+ setEditorMode(mode);+ setOpenState(false);+ }}+ onOpenEditEditor={(mode) => {+ setEditorMode(mode);+ setOpenState(false);+ }}+ registerSave={(handler) => {+ saveAndClose = handler;+ }}+ suppressInitialOutsideEvents={false}+ />+ </Show>+ </Popover>+ <TagEditorDialog+ open={editorMode() !== null}+ mode={editorMode()}+ teamAvailable={Boolean(currentTeamQuery.data?.team)}+ onCreateSuccess={async (result) => {+ await createSuccessHandler()?.(result);+ }}+ onClose={() => {+ setEditorMode(null);+ setCreateSuccessHandler(undefined);+ }}+ />+ </>);}@@ -137,6 +158,12 @@ export function TagPickerPopover(props: {onOpenChange: (open: boolean) => void;getAnchorRect: () => { x: number; y: number } | undefined;}) {+ const [editorMode, setEditorMode] = createSignal<TagEditorDialogMode | null>(+ null+ );+ const [createSuccessHandler, setCreateSuccessHandler] =+ createSignal<CreateTagSuccessHandler>();+ const currentTeamQuery = useCurrentTeamQuery();let saveAndClose: (() => Promise<void>) | undefined;const handleOpenChange = (value: boolean) => {@@ -153,30 +180,60 @@ export function TagPickerPopover(props: {};return (- <Popover- open={props.open}- onOpenChange={handleOpenChange}- getAnchorRect={props.getAnchorRect}- placement="bottom-start"- gutter={4}- >- <Show when={props.open}>- <TagPickerBody- docTags={props.docTags}- onClose={() => props.onOpenChange(false)}- registerSave={(handler) => {- saveAndClose = handler;- }}- suppressInitialOutsideEvents- />- </Show>- </Popover>+ <>+ <Popover+ open={props.open}+ onOpenChange={handleOpenChange}+ getAnchorRect={props.getAnchorRect}+ placement="bottom-start"+ gutter={4}+ >+ <Show when={props.open}>+ <TagPickerBody+ docTags={props.docTags}+ onClose={() => props.onOpenChange(false)}+ onOpenCreateEditor={(mode, onCreateSuccess) => {+ setCreateSuccessHandler(() => onCreateSuccess);+ setEditorMode(mode);+ props.onOpenChange(false);+ }}+ onOpenEditEditor={(mode) => {+ setEditorMode(mode);+ props.onOpenChange(false);+ }}+ registerSave={(handler) => {+ saveAndClose = handler;+ }}+ suppressInitialOutsideEvents+ />+ </Show>+ </Popover>+ <TagEditorDialog+ open={editorMode() !== null}+ mode={editorMode()}+ teamAvailable={Boolean(currentTeamQuery.data?.team)}+ onCreateSuccess={async (result) => {+ await createSuccessHandler()?.(result);+ }}+ onClose={() => {+ setEditorMode(null);+ setCreateSuccessHandler(undefined);+ }}+ />+ </>);}function TagPickerBody(props: {docTags: DocTags;onClose: () => void;+ onOpenCreateEditor: (+ mode: Extract<TagEditorDialogMode, { type: 'create' }>,+ onCreateSuccess?: CreateTagSuccessHandler+ ) => void;+ onOpenEditEditor: (+ mode: Extract<TagEditorDialogMode, { type: 'edit' }>+ ) => void;registerSave: (handler: (() => Promise<void>) | undefined) => void;suppressInitialOutsideEvents: boolean;}) {@@ -186,7 +243,7 @@ function TagPickerBody(props: {new Set(props.docTags.appliedTags().map((tag) => tag.optionId)));const [createStep, setCreateStep] = createSignal<CreateStep | null>(null);- const [createDraftLabel, setCreateDraftLabel] = createSignal('');+ const [createDraftLabel] = createSignal('');const [selectedColorIndex, setSelectedColorIndex] = createSignal(0);const [selectedScopeIndex, setSelectedScopeIndex] = createSignal(0);const currentTeamQuery = useCurrentTeamQuery();@@ -327,17 +384,17 @@ function TagPickerBody(props: {);};const showCreateRow = () =>- createLabel().length >= 2 && !exactTagMatchExists();+ createLabel().length > 0 && !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 clearAllRowIndex = () => filteredItems().length;+ const createRowIndex = () =>+ filteredItems().length + (showClearAllRow() ? 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()}` },+ { scope: 'user', label: 'Personal' },]);const selectedColor = () =>TAG_COLOR_OPTIONS[selectedColorIndex()]?.color ?? DEFAULT_TAG_COLOR;@@ -345,12 +402,38 @@ function TagPickerBody(props: {createStep() === 'color' ? TAG_COLOR_OPTIONS.length : scopeOptions().length;const beginCreate = () => {+ void openCreateEditor();+ };++ const editableTagForItem = (item: TagOptionItem): EditableTag => ({+ scope: item.scope,+ propertyDefinitionId: item.option.propertyDefinitionId,+ option: item.option,+ });++ const beginEdit = async (item: TagOptionItem) => {+ if (!(await persistSelection())) return;+ props.onOpenEditEditor({+ type: 'edit',+ tag: editableTagForItem(item),+ });+ };++ const openCreateEditor = async () => {const label = createLabel();if (!showCreateRow() || !label) return;- setCreateDraftLabel(label);- setSelectedColorIndex(0);- setSelectedScopeIndex(0);- setCreateStep('color');+ if (!(await persistSelection())) return;++ props.onOpenCreateEditor(+ {+ type: 'create',+ initialScope: currentTeamQuery.data?.team ? 'team' : 'user',+ initialLabel: label,+ },+ async (result) => {+ await props.docTags.applyTag(result.scope, result.option.id);+ }+ );};const createTag = async (scope: TagScope) => {@@ -431,8 +514,8 @@ function TagPickerBody(props: {const dropdown = useDropdownSearch({itemCount: () =>filteredItems().length +- (showCreateRow() ? 1 : 0) +- (showClearAllRow() ? 1 : 0),+ (showClearAllRow() ? 1 : 0) ++ (showCreateRow() ? 1 : 0),onSelect: (index, event) => {if (showCreateRow() && index === createRowIndex()) {beginCreate();@@ -556,6 +639,7 @@ function TagPickerBody(props: {toggleSelected(item.option.id);if (!event.shiftKey) saveAndClose();}}+ onEdit={() => void beginEdit(item)}onMouseEnter={() => {if (!dropdown.keyboardMode()) {dropdown.setSelectedIndex(itemIndex(item));@@ -589,6 +673,7 @@ function TagPickerBody(props: {toggleSelected(item.option.id);if (!event.shiftKey) saveAndClose();}}+ onEdit={() => void beginEdit(item)}onMouseEnter={() => {if (!dropdown.keyboardMode()) {dropdown.setSelectedIndex(itemIndex(item));@@ -599,21 +684,6 @@ function TagPickerBody(props: {</For>)}</For>- <Show when={showCreateRow()}>- <CreateTagRow- index={createRowIndex()}- label={createLabel()}- selected={- dropdown.selectedIndex() === createRowIndex()- }- onClick={beginCreate}- onMouseEnter={() => {- if (!dropdown.keyboardMode()) {- dropdown.setSelectedIndex(createRowIndex());- }- }}- />- </Show><Show when={showClearAllRow()}><div class="my-1 border-t border-edge-muted" /><div data-tag-index={clearAllRowIndex()}>@@ -642,6 +712,21 @@ function TagPickerBody(props: {</Show></Show></div>+ <Show when={showCreateRow()}>+ <div class="mt-1 border-t border-edge-muted pt-1">+ <CreateTagRow+ index={createRowIndex()}+ label={createLabel()}+ selected={dropdown.selectedIndex() === createRowIndex()}+ onClick={beginCreate}+ onMouseEnter={() => {+ if (!dropdown.keyboardMode()) {+ dropdown.setSelectedIndex(createRowIndex());+ }+ }}+ />+ </div>+ </Show></div></>}@@ -678,6 +763,7 @@ function TagPickerRow(props: {checked: boolean;selected: boolean;onSelect: (event: MouseEvent) => void;+ onEdit: () => void;onMouseEnter: () => void;}) {return (@@ -695,6 +781,22 @@ function TagPickerRow(props: {{props.teamName}</span></Show>+ <button+ type="button"+ aria-label={`Edit ${optionLabel(props.item.option)}`}+ class="ml-1 flex size-5 shrink-0 items-center justify-center rounded text-ink-extra-muted opacity-0 outline-none hover:bg-hover hover:text-ink group-hover:opacity-100 focus-visible:opacity-100"+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ props.onEdit();+ }}+ >+ <PencilIcon class="size-3.5" />+ </button></DropdownSelectableRow></div>);@@ -720,7 +822,9 @@ function CreateTagRow(props: {<div class="size-3 shrink-0 text-ink-muted"><PlusIcon class="size-3" /></div>- <span class="min-w-0 flex-1 truncate">Create tag "{props.label}"</span>+ <span class="min-w-0 flex-1 truncate">+ Create new tag "{props.label}"+ </span></div>);}diff --git a/apps/web/src/features/property/tags/TagsRow.tsx b/apps/web/src/features/property/tags/TagsRow.tsxindex 68d35e8f86..ec303c8452 100644--- a/apps/web/src/features/property/tags/TagsRow.tsx+++ b/apps/web/src/features/property/tags/TagsRow.tsx@@ -3,12 +3,18 @@ import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';import { ContextMenu } from '@kobalte/core/context-menu';import FunnelIcon from '@phosphor/funnel-simple.svg';+import PencilIcon from '@phosphor/pencil-simple.svg';import PlusIcon from '@phosphor/plus.svg';import XIcon from '@phosphor/x.svg';import type { EntityType } from '@service-properties/generated/schemas/entityType';import { cn, Layer } from '@ui';-import { For, Match, Show, Switch } from 'solid-js';+import { createSignal, For, Match, Show, Switch } from 'solid-js';import { TagDot } from './TagDot';+import {+ type EditableTag,+ TagEditorDialog,+ type TagEditorDialogMode,+} from './TagEditorDialog';import { TagPicker } from './TagPicker';import {buildTaggedItemsSplitContent,@@ -27,6 +33,7 @@ function TagChip(props: {tag: ResolvedTag;docTags: ReturnType<typeof useDocTags>;canEdit: boolean;+ onEdit: (tag: ResolvedTag) => void;}) {const split = useSplitLayout();const panel = useSplitPanel();@@ -74,6 +81,11 @@ function TagChip(props: {onClick={viewTaggedItems}/><Show when={props.canEdit}>+ <MenuItem+ icon={PencilIcon}+ text="Edit tag"+ onClick={() => props.onEdit(props.tag)}+ /><MenuItem icon={XIcon} text="Remove tag" onClick={removeTag} /></Show></ContextMenuContent>@@ -83,6 +95,23 @@ function TagChip(props: {);}+function editableTagFromResolved(+ docTags: ReturnType<typeof useDocTags>,+ tag: ResolvedTag+): EditableTag | undefined {+ const set = docTags.tagSets().find((tagSet) => tagSet.scope === tag.scope);+ const option = set?.options.find(+ (candidate) => candidate.id === tag.optionId+ );+ if (!set?.definition || !option) return undefined;++ return {+ scope: tag.scope,+ propertyDefinitionId: set.definition.id,+ option,+ };+}+export function TagsRow(props: {entityId: string;entityType: EntityType;@@ -92,12 +121,26 @@ export function TagsRow(props: {const docTags = useDocTags(props.entityId, props.entityType);const triggerVariant = () => props.triggerVariant ?? 'icon';const hasTags = () => docTags.appliedTags().length > 0;+ const [editorMode, setEditorMode] = createSignal<TagEditorDialogMode | null>(+ null+ );++ const openEdit = (tag: ResolvedTag) => {+ const editable = editableTagFromResolved(docTags, tag);+ if (!editable) return;+ setEditorMode({ type: 'edit', tag: editable });+ };return (<div class="flex flex-wrap items-center gap-1.5"><For each={docTags.appliedTags()}>{(tag) => (- <TagChip tag={tag} docTags={docTags} canEdit={props.canEdit} />+ <TagChip+ tag={tag}+ docTags={docTags}+ canEdit={props.canEdit}+ onEdit={openEdit}+ />)}</For><Show@@ -138,6 +181,14 @@ export function TagsRow(props: {</Match></Switch></Show>+ <TagEditorDialog+ open={editorMode() !== null}+ mode={editorMode()}+ teamAvailable={Boolean(+ docTags.tagSets().some((set) => set.scope === 'team')+ )}+ onClose={() => setEditorMode(null)}+ /></div>);}diff --git a/apps/web/src/features/property/tags/tagColors.ts b/apps/web/src/features/property/tags/tagColors.tsindex 247185e3e7..45e7f1cb56 100644--- a/apps/web/src/features/property/tags/tagColors.ts+++ b/apps/web/src/features/property/tags/tagColors.ts@@ -17,3 +17,21 @@ export const TAG_COLORS = [] as const;export const DEFAULT_TAG_COLOR: string = TAG_COLORS[11];++export const TAG_COLOR_OPTIONS = [+ { color: TAG_COLORS[0], name: 'Red' },+ { color: TAG_COLORS[1], name: 'Tomato' },+ { color: TAG_COLORS[2], name: 'Orange' },+ { color: TAG_COLORS[3], name: 'Amber' },+ { color: TAG_COLORS[4], name: 'Yellow' },+ { color: TAG_COLORS[5], name: 'Green' },+ { color: TAG_COLORS[6], name: 'Teal' },+ { color: TAG_COLORS[7], name: 'Blue' },+ { color: TAG_COLORS[8], name: 'Indigo' },+ { color: TAG_COLORS[9], name: 'Purple' },+ { color: TAG_COLORS[10], name: 'Pink' },+ { color: TAG_COLORS[11], name: 'Gray' },+] as const satisfies readonly {+ color: (typeof TAG_COLORS)[number];+ name: string;+}[];diff --git a/apps/web/src/features/settings/Settings.tsx b/apps/web/src/features/settings/Settings.tsxindex c61a9db89f..d75190d655 100644--- a/apps/web/src/features/settings/Settings.tsx+++ b/apps/web/src/features/settings/Settings.tsx@@ -44,6 +44,7 @@ import { ConnectedAccounts } from './ConnectedAccounts';import { Crm } from './Crm';import { MobileApp } from './MobileApp';import { Shortcuts } from './Shortcuts';+import { Tags } from './Tags';import { Team } from './Team';/** Where the settings panel is mounted, which determines its header chrome. */@@ -397,6 +398,11 @@ export function SettingsPanel(props: SettingsPanelProps) {<Team /></Suspense></Show>+ <Show when={isCurrentTab('Tags')}>+ <Suspense>+ <Tags />+ </Suspense>+ </Show><Show when={isCurrentTab('CRM')}><Suspense><Crm />diff --git a/apps/web/src/features/settings/Tags.tsx b/apps/web/src/features/settings/Tags.tsxnew file mode 100644index 0000000000..bf974b4a5d--- /dev/null+++ b/apps/web/src/features/settings/Tags.tsx@@ -0,0 +1,211 @@+import PencilIcon from '@phosphor/pencil-simple.svg';+import PlusIcon from '@phosphor/plus.svg';+import TrashIcon from '@phosphor/trash.svg';+import { TagDot } from '@property/tags/TagDot';+import {+ type EditableTag,+ TagEditorDialog,+ type TagEditorDialogMode,+} from '@property/tags/TagEditorDialog';+import {+ useDeletePropertyOptionMutation,+ 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 type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { Button, Tooltip } from '@ui';+import { createMemo, createSignal, For, Show } from 'solid-js';+import { SettingsCard, SettingsPage, SettingsSection } from './primitives';++function optionLabel(option: PropertyOptionResponse): string {+ return option.value.type === 'string' ? option.value.value : '';+}++function sortedOptions(set: TagSetResponse | undefined) {+ return [...(set?.options ?? [])].sort(+ (a, b) => a.displayOrder - b.displayOrder+ );+}++function tagForOption(+ scope: TagScope,+ set: TagSetResponse,+ option: PropertyOptionResponse+): EditableTag {+ return {+ scope,+ propertyDefinitionId: set.definition?.id ?? option.propertyDefinitionId,+ option,+ };+}++function EmptyTagRows(props: { scope: TagScope }) {+ return (+ <div class="px-6 py-8 text-center text-sm text-ink-extra-muted">+ No {props.scope === 'team' ? 'team' : 'personal'} tags+ </div>+ );+}++function TagListSection(props: {+ title: string;+ description?: string;+ scope: TagScope;+ set: TagSetResponse | undefined;+ onCreate: (scope: TagScope) => void;+ onEdit: (tag: EditableTag) => void;+ onDelete: (tag: EditableTag) => void;+ deleting?: boolean;+}) {+ const options = createMemo(() => sortedOptions(props.set));+ const editable = () => Boolean(props.set?.definition);++ return (+ <SettingsSection+ title={props.title}+ description={props.description}+ actions={+ <Button+ variant="base"+ size="sm"+ class="rounded-xs"+ onClick={() => props.onCreate(props.scope)}+ >+ <PlusIcon class="size-4" />+ New tag+ </Button>+ }+ >+ <SettingsCard>+ <Show+ when={options().length > 0}+ fallback={<EmptyTagRows scope={props.scope} />}+ >+ <For each={options()}>+ {(option) => (+ <div class="flex min-h-14 items-center gap-3 px-6 py-3">+ <TagDot color={option.color ?? undefined} class="size-3" />+ <div class="min-w-0 flex-1">+ <div class="truncate text-sm font-medium text-ink">+ {optionLabel(option)}+ </div>+ </div>+ <Show when={editable() && props.set}>+ {(set) => {+ const tag = () => tagForOption(props.scope, set(), option);+ return (+ <div class="flex shrink-0 items-center gap-1">+ <Tooltip label="Edit tag">+ <button+ type="button"+ aria-label={`Edit ${optionLabel(option)}`}+ class="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-extra-muted outline-none hover:bg-hover hover:text-ink focus-visible:border focus-visible:border-accent"+ disabled={props.deleting}+ onClick={() => props.onEdit(tag())}+ >+ <PencilIcon class="size-4" />+ </button>+ </Tooltip>+ <Tooltip label="Delete tag">+ <button+ type="button"+ aria-label={`Delete ${optionLabel(option)}`}+ class="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-extra-muted outline-none hover:bg-failure/10 hover:text-failure focus-visible:border focus-visible:border-failure disabled:opacity-30"+ disabled={props.deleting}+ onClick={() => props.onDelete(tag())}+ >+ <TrashIcon class="size-4" />+ </button>+ </Tooltip>+ </div>+ );+ }}+ </Show>+ </div>+ )}+ </For>+ </Show>+ </SettingsCard>+ </SettingsSection>+ );+}++export function Tags() {+ const tagsQuery = useTagsQuery();+ const teamQuery = useCurrentTeamQuery();+ const deleteTag = useDeletePropertyOptionMutation();+ const [editorMode, setEditorMode] = createSignal<TagEditorDialogMode | null>(+ null+ );++ const tagSet = (scope: TagScope) =>+ tagsQuery.data?.find((set) => set.scope === scope);+ const teamName = () => teamQuery.data?.team.name?.trim() || 'Team';+ const hasTeam = () =>+ tagsQuery.data?.some((set) => set.scope === 'team') ||+ Boolean(teamQuery.data?.team);++ const openCreate = (scope: TagScope) => {+ setEditorMode({ type: 'create', initialScope: scope });+ };++ const openEdit = (tag: EditableTag) => {+ setEditorMode({ type: 'edit', tag });+ };++ const removeTag = (tag: EditableTag) => {+ deleteTag.mutate({+ propertyDefinitionId: tag.propertyDefinitionId,+ optionId: tag.option.id,+ });+ };++ return (+ <SettingsPage+ title="Tags"+ description="Manage personal labels and shared team labels."+ actions={+ <Button+ variant="cta"+ size="sm"+ depth={3}+ onClick={() => openCreate('user')}+ >+ <PlusIcon class="size-4" />+ New tag+ </Button>+ }+ >+ <TagListSection+ title="Personal"+ scope="user"+ set={tagSet('user')}+ onCreate={openCreate}+ onEdit={openEdit}+ onDelete={removeTag}+ deleting={deleteTag.isPending}+ />+ <Show when={hasTeam()}>+ <TagListSection+ title="Team"+ description={teamName()}+ scope="team"+ set={tagSet('team')}+ onCreate={openCreate}+ onEdit={openEdit}+ onDelete={removeTag}+ deleting={deleteTag.isPending}+ />+ </Show>++ <TagEditorDialog+ open={editorMode() !== null}+ mode={editorMode()}+ teamAvailable={hasTeam()}+ onClose={() => setEditorMode(null)}+ />+ </SettingsPage>+ );+}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 16ea3883c6..33badd26c9 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@@ -164,8 +164,8 @@ export function TagsMenu(props: {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()}` },+ { scope: 'user', label: 'Personal' },]);const createStepCount = () =>createStep() === 'color' ? TAG_COLOR_OPTIONS.length : scopeOptions().length;diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsxindex f70bdd83cd..151b8507ca 100644--- a/apps/web/src/lib/core/constant/SettingsState.tsx+++ b/apps/web/src/lib/core/constant/SettingsState.tsx@@ -37,6 +37,7 @@ export type SettingsTab =| 'Agent'| 'Bots'| 'Team'+ | 'Tags'| 'CRM'| 'Connected'| 'Email'diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx b/apps/web/src/lib/core/constant/settingsTabsConfig.tsxindex 6ae7b88cca..34d609403b 100644--- a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx@@ -8,6 +8,7 @@ import DeviceMobileIcon from '@phosphor/device-mobile-speaker.svg';import KeyboardIcon from '@phosphor/keyboard.svg';import PlugIcon from '@phosphor/plug.svg';import SwatchesIcon from '@phosphor/swatches.svg';+import TagIcon from '@phosphor/tag-simple.svg';import UserIconPhosphor from '@phosphor/user.svg';import UsersThreeIcon from '@phosphor/users-three.svg';import { type Component, createMemo } from 'solid-js';@@ -59,6 +60,7 @@ export const SETTINGS_TAB_GROUPS: SettingsTabGroup[] = [label: 'Workspace',items: [{ tab: 'Team', label: 'Team', icon: UsersThreeIcon },+ { tab: 'Tags', label: 'Tags', icon: TagIcon },{ tab: 'CRM', label: 'CRM', icon: BuildingsIcon },{tab: 'Connected',@@ -98,6 +100,7 @@ const SETTINGS_TAB_SLUGS: Record<SettingsTab, string> = {Agent: 'mcp-server',Bots: 'bots',Team: 'team',+ Tags: 'tags',CRM: 'crm',Connected: 'connections',Email: 'email',@@ -153,6 +156,7 @@ export const useSettingsTabAvailable = () => {case 'Billing':return true;case 'Team':+ case 'Tags':return true;// CRM is still rolling out (Macro-internal only); keep the settings tab// behind the same enable-crm gate as every other CRM surface so it neverdiff --git a/apps/web/src/lib/queries/properties/tags.ts b/apps/web/src/lib/queries/properties/tags.tsindex 551c57aa09..8978727bd2 100644--- a/apps/web/src/lib/queries/properties/tags.ts+++ b/apps/web/src/lib/queries/properties/tags.ts@@ -2,8 +2,10 @@ import { toast } from '@core/component/Toast/Toast';import { throwOnErr } from '@core/util/result';import { useMutation, useQuery } from '@tanstack/solid-query';import { propertiesServiceClient } from '../../service-clients/service-properties/client';+import type { AddPropertyOptionRequest } from '../../service-clients/service-properties/generated/schemas/addPropertyOptionRequest';import type { EnsureTagSetRequest } from '../../service-clients/service-properties/generated/schemas/ensureTagSetRequest';import type { PropertyOption } from '../../service-clients/service-properties/generated/schemas/propertyOption';+import type { PropertyOptionResponse } from '../../service-clients/service-properties/generated/schemas/propertyOptionResponse';import type { TagSetResponse } from '../../service-clients/service-properties/generated/schemas/tagSetResponse';import type { UpdatePropertyOptionRequest } from '../../service-clients/service-properties/generated/schemas/updatePropertyOptionRequest';import { queryClient } from '../client';@@ -30,6 +32,25 @@ function invalidatePropertyOptions(propertyDefinitionId: string) {});}+function propertyOptionToResponse(+ option: PropertyOption+): PropertyOptionResponse {+ return {+ id: option.id,+ propertyDefinitionId: option.property_definition_id,+ displayOrder: option.display_order,+ value: option.value,+ color: option.color,+ };+}++function updateTagsCache(update: (sets: TagSetResponse[]) => TagSetResponse[]) {+ queryClient.setQueryData<TagSetResponse[]>(+ propertiesKeys.tags.queryKey,+ (current) => (current ? update(current) : current)+ );+}+type EnsureTagSetParams = { scope: EnsureTagSetRequest['scope'] };/** Provision (get-or-create) the caller's tag definition for a scope. */@@ -63,15 +84,56 @@ type UpdatePropertyOptionParams = {body: UpdatePropertyOptionRequest;};+type TagsMutationContext = {+ previousTags?: TagSetResponse[];+ optimisticOptionId?: string;+};+/** Rename / recolor a label in place. The option id is preserved so the change propagates. */export function useUpdatePropertyOptionMutation(callbacks?: MutationCallbacks<PropertyOption,Error,- UpdatePropertyOptionParams+ UpdatePropertyOptionParams,+ TagsMutationContext>) {return useMutation(() => ({+ onMutate: async (vars): Promise<TagsMutationContext> => {+ await queryClient.cancelQueries({+ queryKey: propertiesKeys.tags.queryKey,+ });+ const previousTags = queryClient.getQueryData<TagSetResponse[]>(+ propertiesKeys.tags.queryKey+ );++ updateTagsCache((sets) =>+ sets.map((set) => ({+ ...set,+ options: set.options.map((option) => {+ if (+ option.id !== vars.optionId ||+ option.propertyDefinitionId !== vars.propertyDefinitionId+ ) {+ return option;+ }++ return {+ ...option,+ displayOrder: vars.body.display_order ?? option.displayOrder,+ color:+ vars.body.color === undefined ? option.color : vars.body.color,+ value:+ vars.body.value == null+ ? option.value+ : { type: 'string', value: vars.body.value },+ };+ }),+ }))+ );++ return { previousTags };+ },mutationFn: async (vars: UpdatePropertyOptionParams) =>await throwOnErr(async () =>@@ -81,13 +143,37 @@ export function useUpdatePropertyOptionMutation(body: vars.body,})),- ...withCallbacks<PropertyOption, Error, UpdatePropertyOptionParams>(+ ...withCallbacks<+ PropertyOption,+ Error,+ UpdatePropertyOptionParams,+ TagsMutationContext+ >({- onError(error) {+ onError(error, _variables, context) {+ if (context?.previousTags) {+ queryClient.setQueryData(+ propertiesKeys.tags.queryKey,+ context.previousTags+ );+ }console.error('Failed to update label', error);toast.failure('Failed to update label');},- onSuccess: (_data, variables) => {+ onSuccess: (data, variables) => {+ const updated = propertyOptionToResponse(data);+ updateTagsCache((sets) =>+ sets.map((set) =>+ set.definition?.id === variables.propertyDefinitionId+ ? {+ ...set,+ options: set.options.map((option) =>+ option.id === variables.optionId ? updated : option+ ),+ }+ : set+ )+ );invalidatePropertyOptions(variables.propertyDefinitionId);invalidateTags();},@@ -97,6 +183,158 @@ export function useUpdatePropertyOptionMutation(}));}+type CreateTagParams = {+ scope: EnsureTagSetRequest['scope'];+ value: string;+ color?: string;+};++export type CreateTagResult = {+ scope: EnsureTagSetRequest['scope'];+ tagSet: TagSetResponse;+ option: PropertyOption;+};++/** Create a tag in the caller's personal or team set. */+export function useCreateTagMutation(+ callbacks?: MutationCallbacks<+ CreateTagResult,+ Error,+ CreateTagParams,+ TagsMutationContext+ >+) {+ return useMutation(() => ({+ onMutate: async (vars): Promise<TagsMutationContext> => {+ await queryClient.cancelQueries({+ queryKey: propertiesKeys.tags.queryKey,+ });+ const previousTags = queryClient.getQueryData<TagSetResponse[]>(+ propertiesKeys.tags.queryKey+ );+ const optimisticOptionId = `optimistic-${crypto.randomUUID()}`;++ updateTagsCache((sets) =>+ sets.map((set) => {+ if (set.scope !== vars.scope || !set.definition) return set;++ return {+ ...set,+ options: [+ ...set.options,+ {+ id: optimisticOptionId,+ propertyDefinitionId: set.definition.id,+ displayOrder:+ set.options.reduce(+ (max, option) => Math.max(max, option.displayOrder),+ -1+ ) + 1,+ value: { type: 'string', value: vars.value },+ color: vars.color,+ },+ ],+ };+ })+ );++ return { previousTags, optimisticOptionId };+ },+ mutationFn: async (vars): Promise<CreateTagResult> => {+ const tagSet = await throwOnErr(+ async () =>+ await propertiesServiceClient.ensureTagSet({+ body: { scope: vars.scope },+ })+ );++ if (!tagSet.definition) {+ throw new Error(`Tag set for scope "${vars.scope}" has no definition`);+ }++ const body: AddPropertyOptionRequest = {+ type: 'select_string',+ option: {+ value: vars.value,+ color: vars.color,+ display_order:+ tagSet.options.reduce(+ (max, option) => Math.max(max, option.displayOrder),+ -1+ ) + 1,+ },+ };++ const option = await throwOnErr(+ async () =>+ await propertiesServiceClient.addPropertyOption({+ definition_id: tagSet.definition!.id,+ body,+ })+ );++ return { scope: vars.scope, tagSet, option };+ },+ ...withCallbacks<+ CreateTagResult,+ Error,+ CreateTagParams,+ TagsMutationContext+ >(+ {+ onError(error, _variables, context) {+ if (context?.previousTags) {+ queryClient.setQueryData(+ propertiesKeys.tags.queryKey,+ context.previousTags+ );+ }+ console.error('Failed to create tag', error);+ toast.failure('Failed to create tag');+ },+ onSuccess(data, _variables, context) {+ const created = propertyOptionToResponse(data.option);+ updateTagsCache((sets) => {+ const hasScope = sets.some((set) => set.scope === data.scope);+ const nextSets = hasScope+ ? sets+ : [+ ...sets,+ {+ scope: data.scope,+ definition: data.tagSet.definition,+ options: [],+ },+ ];++ return nextSets.map((set) => {+ if (set.scope !== data.scope) return set;++ const withoutOptimistic = context?.optimisticOptionId+ ? set.options.filter(+ (option) => option.id !== context.optimisticOptionId+ )+ : set.options;++ return {+ ...set,+ definition: set.definition ?? data.tagSet.definition,+ options: [...withoutOptimistic, created].sort(+ (a, b) => a.displayOrder - b.displayOrder+ ),+ };+ });+ });++ invalidatePropertyOptions(data.option.property_definition_id);+ invalidateTags();+ },+ },+ callbacks+ ),+ }));+}+type DeletePropertyOptionParams = {propertyDefinitionId: string;optionId: string;@@ -107,10 +345,34 @@ export function useDeletePropertyOptionMutation(callbacks?: MutationCallbacks<{ success: boolean },Error,- DeletePropertyOptionParams+ DeletePropertyOptionParams,+ TagsMutationContext>) {return useMutation(() => ({+ onMutate: async (vars): Promise<TagsMutationContext> => {+ await queryClient.cancelQueries({+ queryKey: propertiesKeys.tags.queryKey,+ });+ const previousTags = queryClient.getQueryData<TagSetResponse[]>(+ propertiesKeys.tags.queryKey+ );++ updateTagsCache((sets) =>+ sets.map((set) =>+ set.definition?.id === vars.propertyDefinitionId+ ? {+ ...set,+ options: set.options.filter(+ (option) => option.id !== vars.optionId+ ),+ }+ : set+ )+ );++ return { previousTags };+ },mutationFn: async (vars: DeletePropertyOptionParams) =>await throwOnErr(async () =>@@ -119,9 +381,20 @@ export function useDeletePropertyOptionMutation(option_id: vars.optionId,})),- ...withCallbacks<{ success: boolean }, Error, DeletePropertyOptionParams>(+ ...withCallbacks<+ { success: boolean },+ Error,+ DeletePropertyOptionParams,+ TagsMutationContext+ >({- onError(error) {+ onError(error, _variables, context) {+ if (context?.previousTags) {+ queryClient.setQueryData(+ propertiesKeys.tags.queryKey,+ context.previousTags+ );+ }console.error('Failed to delete label', error);toast.failure('Failed to delete label');},