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
style(tags): move tags to own side panel section, improve styles (#4835)
Seamus09ebca939474
diff --git a/apps/web/src/components/app/side-panel/FileSidePanelSections.tsx b/apps/web/src/components/app/side-panel/FileSidePanelSections.tsxindex cda7de1606..49a9350f02 100644--- a/apps/web/src/components/app/side-panel/FileSidePanelSections.tsx+++ b/apps/web/src/components/app/side-panel/FileSidePanelSections.tsx@@ -1,4 +1,7 @@-import { EntityPropertiesSection } from '@app/features/property/side-panel/properties';+import {+ EntityPropertiesSection,+ EntityTagsSection,+} from '@app/features/property/side-panel/properties';import { useBlockId } from '@core/block';import { EntityIcon } from '@core/component/EntityIcon';import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';@@ -17,7 +20,8 @@ export function FileSidePanelSections() {return (<><FileDetailsSection order={10} />- <FilePropertiesSection order={20} />+ <FileTagsSection order={20} />+ <FilePropertiesSection order={30} /></>);}@@ -48,6 +52,20 @@ export function FilePropertiesSection(props: { order?: number }) {);}+export function FileTagsSection(props: { order?: number }) {+ const blockId = useBlockId();+ const canEdit = useCanEdit();++ return (+ <EntityTagsSection+ entityId={blockId}+ entityType="DOCUMENT"+ canEdit={canEdit()}+ order={props.order}+ />+ );+}+function PropertiesSectionContent() {const blockId = useBlockId();const canEdit = useCanEdit();@@ -59,6 +77,7 @@ function PropertiesSectionContent() {entityType="DOCUMENT"canEdit={canEdit()}documentName={documentName()}+ showTags={false}/>);}diff --git a/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsx b/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsxindex 2e36df8a34..dc96dd18ea 100644--- a/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsx+++ b/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsx@@ -1,4 +1,7 @@-import { EntityPropertiesSection } from '@app/features/property/side-panel/properties';+import {+ EntityPropertiesSection,+ EntityTagsSection,+} from '@app/features/property/side-panel/properties';import {DateValueDisplay,FolderLink,@@ -22,11 +25,17 @@ export function ChatSidePanelSections() {<ChatDetailsContent chatId={chatId} /></Suspense></SidePanel.Section>+ <EntityTagsSection+ entityId={chatId}+ entityType="CHAT"+ canEdit={canEdit()}+ order={20}+ /><SidePanel.Sectionid="properties"title="Properties"defaultOpen- order={20}+ order={30}><Suspense fallback={<SidePanel.Loading />}><ChatPropertiesContent chatId={chatId} canEdit={canEdit()} />@@ -92,6 +101,7 @@ function ChatPropertiesContent(props: { chatId: string; canEdit: boolean }) {entityType="CHAT"canEdit={props.canEdit}documentName={query.data?.name}+ showTags={false}/>);}diff --git a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsxindex 4400f544ad..d0773c3951 100644--- a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx+++ b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx@@ -1,4 +1,7 @@-import { EntityPropertiesSection } from '@app/features/property/side-panel/properties';+import {+ EntityPropertiesSection,+ EntityTagsSection,+} from '@app/features/property/side-panel/properties';import { SidePanel } from '@components/app/side-panel';import { References } from '@core/component/References';import type { Property } from '@property/types';@@ -33,11 +36,17 @@ export function EmailSidePanelSections(props: EmailSidePanelSectionsProps) {/></Suspense></SidePanel.Section>+ <EntityTagsSection+ entityId={props.threadId}+ entityType="THREAD"+ canEdit={canEdit()}+ order={20}+ /><SidePanel.Sectionid="properties"title="Properties"defaultOpen- order={20}+ order={30}><Suspense fallback={<SidePanel.Loading />}><EntityPropertiesSection@@ -46,6 +55,7 @@ export function EmailSidePanelSections(props: EmailSidePanelSectionsProps) {canEdit={canEdit()}documentName={props.title}propertyFilter={(property) => property.isMetadata !== true}+ showTags={false}/></Suspense></SidePanel.Section>diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsxindex 378ccc66e6..dbbea47c81 100644--- a/apps/web/src/features/block-md/component/ComposeTask.tsx+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx@@ -40,15 +40,18 @@ import {PropertiesProvider,type PropertySaveHandler,} from '@property/context/PropertiesContext';+import { InlineTagsPill, useLocalDocTags } from '@property/tags';import type {Property,PropertyApiValues,PropertyOption,} from '@property/types';import { useUpsertToHistoryMutation } from '@queries/history/history';+import { useTagsQuery } from '@queries/properties/tags';import { refetchSoupEntity } from '@queries/soup/cache';import { propertiesServiceClient } from '@service-properties/client';import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';+import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';import { onElementConnect } from '@solid-primitives/lifecycle';import { debounce } from '@solid-primitives/scheduled';import { useQuery } from '@tanstack/solid-query';@@ -94,6 +97,7 @@ const COMPOSER_PROPERTIES = [SYSTEM_PROPERTY_IDS.ASSIGNEES,SYSTEM_PROPERTY_IDS.DUE_DATE,];+const COMPOSER_PROPERTY_SET = new Set<string>(COMPOSER_PROPERTIES);function composerTitleNavigationPlugin(bodyEditor: Accessor<LexicalEditor | undefined>,@@ -278,12 +282,20 @@ async function createTaskWithProperties(taskTitle: string,taskContent: string,properties: Array<[string, PropertyApiValues]>,- definitions: Map<string, PropertyDefinition>,+ definitions: Map<+ string,+ PropertyDefinition | PropertyDefinitionDetailResponse+ >,upsertToHistory: (params: { itemId: string; itemType: 'document' }) => void) {// Convert properties to API format (filter out null values)const propertyValues = properties.flatMap(([id, value]) => {- const isMultiSelect = definitions.get(id)?.is_multi_select ?? false;+ const definition = definitions.get(id);+ const isMultiSelect = definition+ ? 'is_multi_select' in definition+ ? definition.is_multi_select+ : definition.isMultiSelect+ : value.valueType === 'SELECT_STRING' && !COMPOSER_PROPERTY_SET.has(id);const apiValue = propertyValueToApi(value, isMultiSelect);if (apiValue === null) return [];return [{ propertyId: id, value: apiValue }];@@ -519,6 +531,7 @@ export function ComposeTask(props: ComposeTaskProps) {refetchOnReconnect: false,placeholderData: (prev) => prev,}));+ const tagsQuery = useTagsQuery();const definitions = () => {if (!systemPropertiesQuery.isSuccess) return new Map();@@ -531,6 +544,19 @@ export function ComposeTask(props: ComposeTaskProps) {);};+ const createDefinitions = () => {+ const map = new Map<+ PropertyDefinition['id'],+ PropertyDefinition | PropertyDefinitionDetailResponse+ >(definitions());+ for (const tagSet of tagsQuery.data ?? []) {+ if (tagSet.definition) {+ map.set(tagSet.definition.id, tagSet.definition);+ }+ }+ return map;+ };+const options = () => {if (!systemPropertiesQuery.isSuccess) return new Map();const data = systemPropertiesQuery.data;@@ -575,6 +601,21 @@ export function ComposeTask(props: ComposeTaskProps) {},};+ const composerTags = useLocalDocTags(+ (definitionId) => {+ const value = propertyValues[definitionId];+ return value?.valueType === 'SELECT_STRING' && value.values+ ? value.values+ : [];+ },+ (definition, optionIds) => {+ setPropertyValues(definition.id, {+ valueType: 'SELECT_STRING',+ values: optionIds,+ });+ }+ );+const showTaskCreatedToast = async (documentId: string) => {// Auto-copy link to clipboardconst url = buildSimpleEntityUrl({ type: 'task', id: documentId });@@ -651,7 +692,7 @@ export function ComposeTask(props: ComposeTaskProps) {taskTitle,taskContent,properties,- definitions(),+ createDefinitions(),(params) => upsertToHistoryMutation.mutate(params));@@ -678,7 +719,7 @@ export function ComposeTask(props: ComposeTaskProps) {taskTitle,taskContent,properties,- definitions(),+ createDefinitions(),(params) => upsertToHistoryMutation.mutate(params));@@ -737,7 +778,7 @@ export function ComposeTask(props: ComposeTaskProps) {taskTitle,taskContent,properties,- definitions(),+ createDefinitions(),(params) => upsertToHistoryMutation.mutate(params));@@ -989,6 +1030,7 @@ export function ComposeTask(props: ComposeTaskProps) {/>)}</For>+ <InlineTagsPill docTags={composerTags} showPlaceholder /></div><Modals /></PropertiesProvider>diff --git a/apps/web/src/features/block-md/component/InlineTaskProperties.tsx b/apps/web/src/features/block-md/component/InlineTaskProperties.tsxindex e57326ad5f..e08cd4986f 100644--- a/apps/web/src/features/block-md/component/InlineTaskProperties.tsx+++ b/apps/web/src/features/block-md/component/InlineTaskProperties.tsx@@ -13,6 +13,7 @@ import {type PropertySaveHandler,} from '@property/context/PropertiesContext';import { useEntityProperties } from '@property/hooks';+import { InlineFetchedEntityTagsPill } from '@property/tags';import type { Property, PropertyApiValues } from '@property/types';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import type { EntityType } from '@service-properties/generated/schemas/entityType';@@ -51,7 +52,10 @@ export function InlineTaskProperties() {.filter((p): p is Property => p !== undefined);});const shouldShowRow = createMemo(- () => blockName === 'task' || inlineProperties().length > 0+ () =>+ blockName === 'task' ||+ blockName === 'md' ||+ inlineProperties().length > 0);const saveMutation = useBulkSaveEntityPropertiesMutation();@@ -83,6 +87,10 @@ export function InlineTaskProperties() {<For each={inlineProperties()}>{(property) => <InlinePropertyValue property={property} />}</For>+ <InlineFetchedEntityTagsPill+ entityId={blockId}+ entityType={entityType}+ /><Modals /></PropertiesProvider></Show>diff --git a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsxindex 50f2107686..dd976157e6 100644--- a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx+++ b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx@@ -1,4 +1,7 @@-import { EntityPropertiesSection } from '@app/features/property/side-panel/properties';+import {+ EntityPropertiesSection,+ EntityTagsSection,+} from '@app/features/property/side-panel/properties';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import {GithubPullRequestDetailsRows,@@ -85,6 +88,8 @@ export function MarkdownSidePanelSections(const itemType = blockNameToItemType(rawBlockName);const entity = (): Entity => ({ id: blockId, type: itemType as EntityType });+ const propertiesEntityType = (): PropertiesEntityType =>+ blockName === 'task' ? 'TASK' : 'DOCUMENT';return (<>@@ -94,11 +99,17 @@ export function MarkdownSidePanelSections(<Show when={isSnippet()}><SnippetSharingOwnerSectionConditional documentId={blockId} /></Show>+ <EntityTagsSection+ entityId={blockId}+ entityType={propertiesEntityType()}+ canEdit={props.canEdit}+ order={20}+ /><SidePanel.Sectionid="properties"title="Properties"defaultOpen- order={20}+ order={25}><PropertiesSectionContentcanEdit={props.canEdit}@@ -440,6 +451,7 @@ function PropertiesSectionContent(props: {pinnedPropertyDefinitionOrder={PINNED_ORDER}onPropertyPinned={handlePropertyPinned}onPropertyUnpinned={handlePropertyUnpinned}+ showTags={false}/>);}diff --git a/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsx b/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsxindex 0603404a3b..e9771562a9 100644--- a/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsx+++ b/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsx@@ -1,4 +1,7 @@-import { EntityPropertiesSection } from '@app/features/property/side-panel/properties';+import {+ EntityPropertiesSection,+ EntityTagsSection,+} from '@app/features/property/side-panel/properties';import { SidePanel } from '@components/app/side-panel';import { useBlockId } from '@core/block';import { useCanEdit } from '@core/signal/permissions';@@ -26,11 +29,17 @@ export function ProjectSidePanelSections() {/></Suspense></SidePanel.Section>+ <EntityTagsSection+ entityId={projectId}+ entityType="PROJECT"+ canEdit={canEdit()}+ order={20}+ /><SidePanel.Sectionid="properties"title="Properties"defaultOpen- order={20}+ order={30}><Suspense fallback={<SidePanel.Loading />}><EntityPropertiesSection@@ -39,6 +48,7 @@ export function ProjectSidePanelSections() {canEdit={canEdit()}documentName={projectName()}propertyFilter={(property) => property.isMetadata !== true}+ showTags={false}/></Suspense></SidePanel.Section>diff --git a/apps/web/src/features/entity/extractors-property/entity-key-properties.tsx b/apps/web/src/features/entity/extractors-property/entity-key-properties.tsxindex 0aa1d20222..0837b2f663 100644--- a/apps/web/src/features/entity/extractors-property/entity-key-properties.tsx+++ b/apps/web/src/features/entity/extractors-property/entity-key-properties.tsx@@ -112,29 +112,27 @@ export function EntityKeyProperties(props: EntityKeyPropertiesProps) {};return (- <Show when={keyProperties().length > 0}>- <PropertiesProvider- entityType={entityType()}- canEdit={true}+ <PropertiesProvider+ entityType={entityType()}+ canEdit={true}+ properties={keyProperties}+ onRefresh={props.onRefresh ?? (() => {})}+ onPropertyAdded={() => {}}+ onPropertyDeleted={() => {}}+ saveHandler={saveHandler}+ >+ <KeyPropertiesRowproperties={keyProperties}- onRefresh={props.onRefresh ?? (() => {})}- onPropertyAdded={() => {}}- onPropertyDeleted={() => {}}- saveHandler={saveHandler}- >- <KeyPropertiesRow- properties={keyProperties}- onRefresh={props.onRefresh}- maxUserStackUsers={props.maxUserStackUsers}- showCaret={props.showCaret}- />- <ScopedPortal scope="split">- <Suspense>- <Modals />- </Suspense>- </ScopedPortal>- </PropertiesProvider>- </Show>+ onRefresh={props.onRefresh}+ maxUserStackUsers={props.maxUserStackUsers}+ showCaret={props.showCaret}+ />+ <ScopedPortal scope="split">+ <Suspense>+ <Modals />+ </Suspense>+ </ScopedPortal>+ </PropertiesProvider>);}diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsxindex 44eb4963a1..9bebcdb09b 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx@@ -26,7 +26,7 @@ import { Button, Tooltip } from '@ui';import { createMemo, createSignal, Show } from 'solid-js';import { useSoup } from '../../soup-context';-export function SoupFiltersBar() {+export function SoupFiltersBar(props: { variant?: 'default' | 'tag' } = {}) {const { resetToTabDefaults, consolidatedFiltersList } =useFilterRefinements();@@ -67,6 +67,7 @@ export function SoupFiltersBar() {const content = panel.handle.content();return content.type === 'component' && content.id === 'search';});+ const isTagView = createMemo(() => props.variant === 'tag');// The new inbox hides sort (it's fixed to updated_at for this view).const newInboxFlag = useFeatureFlag(ENABLE_NEW_INBOX_FLAG, {@@ -85,7 +86,17 @@ export function SoupFiltersBar() {<Show when={!isMobile()}><SplitToolbarLeft><div class="flex items-start gap-1 min-w-0 flex-1">- <Show when={!isSearchView()} fallback={<SearchFiltersRow />}>+ <Show+ when={!isSearchView() && !isTagView()}+ fallback={+ <Show when={isTagView()} fallback={<SearchFiltersRow />}>+ <Show when={!isNewInbox()}>+ <SoupViewContextSort />+ </Show>+ <SoupViewContextGroup />+ </Show>+ }+ ><Show when={!isNewInbox()}><SoupViewContextSort /></Show>@@ -118,7 +129,7 @@ export function SoupFiltersBar() {</Tooltip></SplitToolbarRight>{/* Active filters bar - shown below the toolbar when there are filters */}- <Show when={!isSearchView()}>+ <Show when={!isSearchView() && !isTagView()}><SoupActiveFiltersBarfilters={consolidatedFiltersList()}onClearAll={resetToTabDefaults}diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsxindex 174573bd8c..caa6a6ab0d 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsx@@ -3,6 +3,7 @@ import { GroupDropdown } from '@app/features/next-soup/soup-view/filters-bar/groimport {COMPANY_GROUP_OPTIONS,type GroupOptionId,+ TAG_VIEW_GROUP_OPTIONS,TASK_GROUP_OPTIONS,} from '@app/features/next-soup/soup-view/group-options';import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';@@ -66,6 +67,15 @@ export const SoupViewContextGroup = () => {onOpenChange={setGroupOpen}/></Show>+ <Show when={component() === 'tag'}>+ <GroupDropdown+ value={value}+ onChange={onChange}+ options={TAG_VIEW_GROUP_OPTIONS}+ open={groupOpen()}+ onOpenChange={setGroupOpen}+ />+ </Show></Show>);};diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-sort.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-sort.tsxindex 829cb08dfe..f7268c7a96 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-sort.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-sort.tsx@@ -76,6 +76,9 @@ export const SoupViewContextSort = () => {<Match when={isComponentListView('folders')}><FilesSort {...openProps()} /></Match>+ <Match when={component() === 'tag'}>+ <FilesSort {...openProps()} />+ </Match></Switch>);};diff --git a/apps/web/src/features/next-soup/soup-view/group-options.ts b/apps/web/src/features/next-soup/soup-view/group-options.tsindex 32f1a5de5b..a945490545 100644--- a/apps/web/src/features/next-soup/soup-view/group-options.ts+++ b/apps/web/src/features/next-soup/soup-view/group-options.ts@@ -61,6 +61,13 @@ export const COMPANY_GROUP_OPTIONS: GroupOption[] = [{ value: `property:${SYSTEM_PROPERTY_IDS.COMPANY_OWNER}`, label: 'Owner' },];+export const TAG_VIEW_GROUP_OPTIONS: GroupOption[] = [+ { value: 'none', label: 'None' },+ { value: 'entity_type', label: 'Type' },+ { value: 'project', label: 'Project' },+ { value: 'date', label: 'Date' },+];+const _EMAIL_GROUP_OPTIONS: GroupOption[] = [{ value: 'none', label: 'None' },{ value: 'date', label: 'Date' },diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsxindex 3cb013fa3d..a6d561877c 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx@@ -310,6 +310,9 @@ type SoupListEntryState = {interface SoupViewProps {viewName: string;+ customTabs?: JSX.Element;+ filterBarVariant?: 'default' | 'tag';+ showCreateButton?: boolean;initialClientFilters?: SetPredicatesInput<string>;initialFilters?: Query;initialSearchText?: string;@@ -654,8 +657,10 @@ export const SoupView = (props: SoupViewProps) => {<CollapsibleHeaderItemid="tabs"priority={1}- expanded={() => <SoupViewTabs />}- collapsed={() => <CollapsedSoupViewTabs />}+ expanded={() => props.customTabs ?? <SoupViewTabs />}+ collapsed={() =>+ props.customTabs ?? <CollapsedSoupViewTabs />+ }containerClass="h-full"/></Show>@@ -681,7 +686,11 @@ export const SoupView = (props: SoupViewProps) => {<CompanyDisplayMenu /></Show><Show- when={!narrowSearchExpanded() && !isComponentListView('search')}+ when={+ !narrowSearchExpanded() &&+ !isComponentListView('search') &&+ props.showCreateButton !== false+ }><SoupViewCreateButton /></Show>@@ -747,7 +756,7 @@ export const SoupView = (props: SoupViewProps) => {</SplitHeaderRight></Show></div>- <SoupFiltersBar />+ <SoupFiltersBar variant={props.filterBarVariant} /><div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full"><Suspense><Show when={!isBoardMode()} fallback={<CompanyKanban />}>diff --git a/apps/web/src/features/property/component/modal/SelectPropertyModal.tsx b/apps/web/src/features/property/component/modal/SelectPropertyModal.tsxindex 5f62b5ae9c..370d073e2a 100644--- a/apps/web/src/features/property/component/modal/SelectPropertyModal.tsx+++ b/apps/web/src/features/property/component/modal/SelectPropertyModal.tsx@@ -9,6 +9,7 @@ import {} from '@property/constants';import { useListPropertiesQuery } from '@queries/properties/definitions';import { useAddEntityPropertyMutation } from '@queries/properties/entity';+import { useTagsQuery } from '@queries/properties/tags';import { cn, Dialog, Surface } from '@ui';import {createEffect,@@ -42,6 +43,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {const [dialogRef, setDialogRef] = createSignal<HTMLDivElement | undefined>();const addMutation = useAddEntityPropertyMutation();+ const tagsQuery = useTagsQuery();const listPropertiesQuery = useListPropertiesQuery(() => ({scope: 'all',@@ -59,6 +61,11 @@ export function SelectPropertyModal(props: PropertySelectorProps) {}const data = listPropertiesQuery.data;+ const tagDefinitionIds = new Set(+ (tagsQuery.data ?? [])+ .map((set) => set.definition?.id)+ .filter((id): id is string => !!id)+ );const properties = Array.isArray(data) ? data : [];return properties@@ -74,9 +81,14 @@ export function SelectPropertyModal(props: PropertySelectorProps) {.filter(// Reserved internal definitions (`__macro:*` config carriers) and// the CRM-managed team Stage definition must never surface in- // property pickers.+ // property pickers. Tags have their own top-level sidepanel section+ // and picker, so exclude the backing tag definitions here too. The+ // value-type check covers the initial render before the tags query+ // has returned definition ids.(property) =>!isReservedPropertyDefinitionName(property.displayName) &&+ property.valueType !== 'TAG' &&+ !tagDefinitionIds.has(property.id) &&!(property.displayName === CRM_TEAM_STAGE_DEFINITION_NAME &&!property.isSystemdiff --git a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsxindex ee8b6e06f2..8b730f433b 100644--- a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx+++ b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx@@ -78,13 +78,25 @@ function getEntityTypePluralLabel(}}+type UserEntityParts = {+ name: string;+ email?: string;+};++function getUserEntityParts(entity: CombinedEntity): UserEntityParts | null {+ if (entity.kind !== 'user') return null;++ const { name, email } = entity.data;+ if (!name || name === email) return { name: email };+ return { name, email };+}+/** Gets display name for a CombinedEntity */function getEntityName(entity: CombinedEntity): string {if (entity.kind === 'user') {- const { name, email } = entity.data;- if (name === email) return email.split('@')[0] || email;- return `${name} | ${email}`;+ return entity.data.name || entity.data.email;}+const data = entity.data;if (data.type === 'email') {return data.name ?? 'No Subject';@@ -535,7 +547,23 @@ export function PropertyEntitySelector(props: EntityInputProps) {<span class="truncate min-w-0 max-w-full"><Showwhen={entity.kind === 'entity'}- fallback={getEntityName(entity)}+ fallback={+ <Show+ when={getUserEntityParts(entity)}+ fallback={getEntityName(entity)}+ >+ {(parts) => (+ <>+ {parts().name}+ <Show when={parts().email}>+ <span class="ml-[0.5em] opacity-50">+ {parts().email}+ </span>+ </Show>+ </>+ )}+ </Show>+ }><Entity.Titleentity={entity.data as EntityData}diff --git a/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsxindex b221d7bcd5..7400843b4e 100644--- a/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsx+++ b/apps/web/src/features/property/editors/selectors/PropertyOptionSelector.tsx@@ -25,13 +25,14 @@ import {import { OptionCheckBox } from './OptionCheckBox';import type { OptionSelectorConfig, SelectableOption } from './types';-type UseDropdownSearchOptions = {+export type UseDropdownSearchOptions = {itemCount: Accessor<number>;- onSelect: (index: number) => void;+ onSelect: (index: number, event?: KeyboardEvent) => void;onClose: () => void;+ enableNumericHotkeys?: boolean;};-const useDropdownSearch = (options: UseDropdownSearchOptions) => {+export const useDropdownSearch = (options: UseDropdownSearchOptions) => {const [searchQuery, setSearchQuery] = createSignal('');const [selectedIndex, setSelectedIndex] = createSignal(0);const keyboardMode = useKeyPressed(100);@@ -46,7 +47,9 @@ const useDropdownSearch = (options: UseDropdownSearchOptions) => {});const shouldShowHotkeys = () =>- !searchQuery().trim() && options.itemCount() <= 9;+ (options.enableNumericHotkeys ?? true) &&+ !searchQuery().trim() &&+ options.itemCount() <= 9;const handleKeyDown = (e: KeyboardEvent) => {if (e.key === 'Escape') {@@ -64,7 +67,7 @@ const useDropdownSearch = (options: UseDropdownSearchOptions) => {const keyNum = parseInt(e.key);// 0 selects index 0 (the clear option when present)// 1-9 select indices 1-9 (the actual options)- if (keyNum < count) options.onSelect(keyNum);+ if (keyNum < count) options.onSelect(keyNum, e);return;}@@ -76,7 +79,7 @@ const useDropdownSearch = (options: UseDropdownSearchOptions) => {setSelectedIndex((prev) => (prev - 1 + count) % count);} else if (e.key === 'Enter') {e.preventDefault();- options.onSelect(selectedIndex());+ options.onSelect(selectedIndex(), e);}};@@ -91,15 +94,16 @@ const useDropdownSearch = (options: UseDropdownSearchOptions) => {};};-type DropdownSearchInputProps = {+export type DropdownSearchInputProps = {value: string;placeholder: string;onInput: (value: string) => void;+ onKeyDown?: JSX.EventHandlerUnion<HTMLInputElement, KeyboardEvent>;inputType?: string;inputRef?: (element: HTMLInputElement) => void;};-const DropdownSearchInput = (props: DropdownSearchInputProps) => {+export const DropdownSearchInput = (props: DropdownSearchInputProps) => {return (<div class="flex w-full items-center py-2 gap-2 px-2 border-b border-edge-muted"><SearchIcon class="h-4 w-4 text-ink-muted" />@@ -109,13 +113,14 @@ const DropdownSearchInput = (props: DropdownSearchInputProps) => {type={props.inputType ?? 'text'}value={props.value}onInput={(event) => props.onInput(event.currentTarget.value)}+ onKeyDown={props.onKeyDown}placeholder={props.placeholder}/></div>);};-type DropdownSelectableRowProps = {+export type DropdownSelectableRowProps = {isSelected: boolean;showHotkey?: boolean;hotkeyShortcut?: string;@@ -124,9 +129,9 @@ type DropdownSelectableRowProps = {onMouseEnter?: JSX.EventHandlerUnion<HTMLDivElement, MouseEvent>;};-const DropdownSelectableRow: ParentComponent<DropdownSelectableRowProps> = (- props-) => {+export const DropdownSelectableRow: ParentComponent<+ DropdownSelectableRowProps+> = (props) => {return (<divclass="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default"@@ -173,13 +178,20 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {const isOptionSelected = (value: string) =>props.selectedOptions().has(value);- const handleAddOption = async () => {+ const shouldCloseAfterSelect = (+ event?: KeyboardEvent | MouseEvent+ ): boolean => !props.config.isMultiSelect || !event?.shiftKey;++ const handleAddOption = async (event?: KeyboardEvent | MouseEvent) => {if (!props.onAddOption || !isValidNewOption()) return;setIsAddingOption(true);try {await props.onAddOption(dropdown.searchQuery().trim());dropdown.setSearchQuery('');+ if (shouldCloseAfterSelect(event) && props.onClose) {+ props.onClose();+ }} catch (error) {console.error('PropertyOptionsList.handleAddOption:',@@ -191,18 +203,18 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {}};- const handleSelectableItem = (idx: number) => {+ const handleSelectableItem = (idx: number, event?: KeyboardEvent) => {const item = selectableItems()[idx];if (item?.type === 'add') {- handleAddOption();+ handleAddOption(event);} else if (item?.type === 'clear') {props.clearOption?.onClear();- if (!props.config.isMultiSelect && props.onClose) {+ if (shouldCloseAfterSelect(event) && props.onClose) {props.onClose();}} else if (item?.type === 'option') {props.onToggleOption(item.option.id);- if (!props.config.isMultiSelect && props.onClose) {+ if (shouldCloseAfterSelect(event) && props.onClose) {props.onClose();}}@@ -409,10 +421,10 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {{(optionItem) => (<DropdownSelectableRowisSelected={isSelected()}- onClick={() => {+ onClick={(event) => {props.onToggleOption(optionItem().option.id);if (- !props.config.isMultiSelect &&+ shouldCloseAfterSelect(event) &&props.onClose) {props.onClose();@@ -451,10 +463,10 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {{(clear) => (<DropdownSelectableRowisSelected={isSelected()}- onClick={() => {+ onClick={(event) => {clear().onClear();if (- !props.config.isMultiSelect &&+ shouldCloseAfterSelect(event) &&props.onClose) {props.onClose();diff --git a/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx b/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsxindex 64b0b2eace..3340e06430 100644--- a/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx+++ b/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx@@ -39,6 +39,7 @@ import {type JSX,Match,Show,+ Suspense,Switch,} from 'solid-js';@@ -71,6 +72,13 @@ export interface EntityPropertiesSectionProps {hidePropertyDefinitionIds?: string[];}+export interface EntityTagsSectionProps {+ entityId: string;+ entityType: EntityType;+ canEdit: boolean;+ order?: number;+}+const TAGGABLE_ENTITY_TYPES: ReadonlySet<EntityType> = new Set<EntityType>(['DOCUMENT','TASK',@@ -80,6 +88,31 @@ const TAGGABLE_ENTITY_TYPES: ReadonlySet<EntityType> = new Set<EntityType>(['CALL_RECORD',]);+export function EntityTagsSection(props: EntityTagsSectionProps) {+ const tagsFlag = useFeatureFlag(ENABLE_TAGS_FE_FLAG, {+ enabledOverride: ENABLE_TAGS_FE_OVERRIDE,+ });++ return (+ <Show+ when={tagsFlag().enabled && TAGGABLE_ENTITY_TYPES.has(props.entityType)}+ >+ <SidePanel.Section id="tags" title="Tags" defaultOpen order={props.order}>+ <Suspense fallback={<SidePanel.Loading />}>+ <div class="text-xs">+ <TagsRow+ entityId={props.entityId}+ entityType={props.entityType}+ canEdit={props.canEdit}+ triggerVariant="pill"+ />+ </div>+ </Suspense>+ </SidePanel.Section>+ </Show>+ );+}+export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {const { properties, isLoading, error, refetch } = useEntityProperties(props.entityId,diff --git a/apps/web/src/features/property/side-panel/properties/index.ts b/apps/web/src/features/property/side-panel/properties/index.tsindex ea7ee445e7..5369d6f9e0 100644--- a/apps/web/src/features/property/side-panel/properties/index.ts+++ b/apps/web/src/features/property/side-panel/properties/index.ts@@ -1,2 +1,8 @@-export type { EntityPropertiesSectionProps } from './EntityPropertiesSection';-export { EntityPropertiesSection } from './EntityPropertiesSection';+export type {+ EntityPropertiesSectionProps,+ EntityTagsSectionProps,+} from './EntityPropertiesSection';+export {+ EntityPropertiesSection,+ EntityTagsSection,+} from './EntityPropertiesSection';diff --git a/apps/web/src/features/property/tags/EntityRowTags.tsx b/apps/web/src/features/property/tags/EntityRowTags.tsxindex 1ddd8dc4e4..e7990a57a2 100644--- a/apps/web/src/features/property/tags/EntityRowTags.tsx+++ b/apps/web/src/features/property/tags/EntityRowTags.tsx@@ -1,11 +1,13 @@+import CaretDownIcon from '@phosphor/caret-down.svg';+import CircleDashedEmpty from '@phosphor/circle-dashed.svg';import FilterIcon from '@phosphor/funnel-simple.svg';-import type { EntityType } from '@service-properties/generated/schemas/entityType';+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, Show } from 'solid-js';+import { createSignal, For, Match, Show, Switch } from 'solid-js';import { TagDot } from './TagDot';import { TagPicker } from './TagPicker';-import { type ResolvedTag, useSoupDocTags } from './useDocTags';+import { type ResolvedTag, useDocTags, useSoupDocTags } from './useDocTags';type DocTags = ReturnType<typeof useSoupDocTags>;@@ -73,7 +75,7 @@ function TagChip(props: {<TagPickerdocTags={props.docTags}triggerClass={chipClass}- triggerLabel={`Edit ${props.tag.label}`}+ triggerLabel={`Change or select tag ${props.tag.label}`}onOpenChange={setPickerOpen}><TagDot color={props.tag.color} class="size-2" />@@ -182,3 +184,108 @@ export function EntityRowTags(props: {</Show>);}++export function InlineTagsPill(props: {+ docTags: DocTags;+ class?: string;+ showPlaceholder?: boolean;+}) {+ const tags = () => props.docTags.appliedTags();+ const first = () => tags()[0];+ const dots = () => tags().slice(0, MAX_OVERFLOW_DOTS);+ const label = () =>+ `${tags().length} ${tags().length === 1 ? 'Tag' : 'Tags'}`;++ return (+ <Show when={tags().length > 0 || props.showPlaceholder}>+ <Layer depth={2}>+ <TagPicker+ docTags={props.docTags}+ triggerClass={cn(+ 'inline-flex items-center gap-1.5 min-w-0 ring ring-edge-muted',+ 'px-2 py-1 leading-tight text-left rounded-full bg-surface',+ 'hover:bg-hover text-ink-muted focus-visible:bg-active focus-visible:ring-accent/10',+ tags().length === 0 && 'text-ink-extra-muted',+ props.class+ )}+ triggerLabel="Change or select tags"+ >+ <Switch>+ <Match when={tags().length === 0}>+ <span class="inline-flex min-w-0 items-center gap-1.5 opacity-50">+ <CircleDashedEmpty class="size-3 shrink-0" />+ <span class="min-w-0 truncate @max-2xl/u-list:hidden">+ Tags+ </span>+ </span>+ </Match>+ <Match when={tags().length === 1 && first()}>+ {(tag) => (+ <>+ <TagDot color={tag().color} class="size-2.5" />+ <span class="min-w-0 truncate @max-2xl/u-list:hidden">+ {tag().label}+ </span>+ </>+ )}+ </Match>+ <Match when={tags().length > 1}>+ <span class="flex items-center">+ <For each={dots()}>+ {(tag, index) => (+ <TagDot+ color={tag.color}+ class={cn(+ 'size-2.5 ring-2 ring-surface',+ index() > 0 && '-ml-1'+ )}+ />+ )}+ </For>+ </span>+ <span class="min-w-0 truncate @max-2xl/u-list:hidden">+ {label()}+ </span>+ </Match>+ </Switch>+ <CaretDownIcon class="size-3 shrink-0 @max-2xl/u-list:hidden" />+ </TagPicker>+ </Layer>+ </Show>+ );+}++export function InlineEntityTagsPill(props: {+ entityId: string;+ entityType: EntityType;+ properties: SoupProperty[] | undefined;+ class?: string;+}) {+ const docTags = useSoupDocTags(+ props.entityId,+ props.entityType,+ () => props.properties+ );+ return (+ <InlineTagsPill+ docTags={docTags}+ class={props.class}+ showPlaceholder={props.entityType === EntityType.TASK}+ />+ );+}++export function InlineFetchedEntityTagsPill(props: {+ entityId: string;+ entityType: EntityType;+ class?: string;+}) {+ const docTags = useDocTags(props.entityId, props.entityType);+ return (+ <InlineTagsPill+ docTags={docTags}+ class={props.class}+ showPlaceholder={props.entityType === EntityType.TASK}+ />+ );+}diff --git a/apps/web/src/features/property/tags/TagPicker.tsx b/apps/web/src/features/property/tags/TagPicker.tsxindex 6a743fc060..86f2d9ccec 100644--- a/apps/web/src/features/property/tags/TagPicker.tsx+++ b/apps/web/src/features/property/tags/TagPicker.tsx@@ -1,32 +1,62 @@import { Popover } from '@kobalte/core/popover';-import SearchIcon from '@phosphor/magnifying-glass.svg';-import PencilSimple from '@phosphor/pencil-simple.svg';-import Trash from '@phosphor/trash.svg';+import PlusIcon from '@phosphor/plus.svg';+import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';+import {+ DropdownSearchInput,+ DropdownSelectableRow,+ useDropdownSearch,+} from '@property/editors/selectors/PropertyOptionSelector';import { useAddPropertyOptionMutation } from '@queries/properties/options';import {invalidateTags,- useDeletePropertyOptionMutation,useEnsureTagSetMutation,- useUpdatePropertyOptionMutation,} 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 { Button, cn, Dialog, Layer, SingleSelectCheck } from '@ui';+import { Layer } from '@ui';import {+ createEffect,createMemo,createSignal,For,type JSX,- Match,+ onCleanup,+ onMount,Show,- Switch,+ untrack,} from 'solid-js';import { TagDot } from './TagDot';-import { DEFAULT_TAG_COLOR, TAG_COLORS } from './tagColors';-import type { useDocTags } from './useDocTags';+import { DEFAULT_TAG_COLOR, type TAG_COLORS } from './tagColors';+import type { ResolvedTag, useDocTags } from './useDocTags';type DocTags = ReturnType<typeof useDocTags>;+type TagOptionItem = {+ scope: TagScope;+ option: PropertyOptionResponse;+};++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;+}[];+function optionLabel(option: PropertyOptionResponse): string {return option.value.type === 'string' ? option.value.value : '';}@@ -37,36 +67,37 @@ function nextDisplayOrder(options: PropertyOptionResponse[]): number {);}-// Bring a newly expanded row fully into view once it mounts so the bottom-// row's action buttons are never clipped below the scroll viewport. Deferred a-// frame so it runs after the expanded layout settles.-function scrollExpandedRowIntoView(el: HTMLElement) {- requestAnimationFrame(() => el.scrollIntoView({ block: 'nearest' }));-}--function focusWithoutScroll(el: HTMLInputElement) {- requestAnimationFrame(() => el.focus({ preventScroll: true }));-}--const SCOPE_LABEL: Record<TagScope, string> = {- user: 'My labels',- team: 'Team labels',-};+const MAX_LIST_HEIGHT = 192;export function TagPicker(props: {docTags: DocTags;+ replaceTag?: ResolvedTag;triggerClass?: string;triggerLabel: string;children: JSX.Element;onOpenChange?: (open: boolean) => void;}) {const [open, setOpen] = createSignal(false);+ let saveAndClose: (() => Promise<void>) | undefined;- const handleOpenChange = (value: boolean) => {+ const setOpenState = (value: boolean) => {setOpen(value);props.onOpenChange?.(value);};+ const handleOpenChange = (value: boolean) => {+ if (value) {+ setOpenState(true);+ return;+ }++ if (saveAndClose) {+ void saveAndClose();+ } else {+ setOpenState(false);+ }+ };+return (<Popoveropen={open()}@@ -81,10 +112,15 @@ export function TagPicker(props: {>{props.children}</Popover.Trigger>- <TagPickerBody- docTags={props.docTags}- onClose={() => handleOpenChange(false)}- />+ <Show when={open()}>+ <TagPickerBody+ docTags={props.docTags}+ onClose={() => setOpenState(false)}+ registerSave={(handler) => {+ saveAndClose = handler;+ }}+ />+ </Show></Popover>);}@@ -99,23 +135,38 @@ export function TagPickerPopover(props: {onOpenChange: (open: boolean) => void;getAnchorRect: () => { x: number; y: number } | undefined;}) {+ let saveAndClose: (() => Promise<void>) | undefined;++ const handleOpenChange = (value: boolean) => {+ if (value) {+ props.onOpenChange(true);+ return;+ }++ if (saveAndClose) {+ void saveAndClose();+ } else {+ props.onOpenChange(false);+ }+ };+return (<Popoveropen={props.open}- onOpenChange={props.onOpenChange}+ onOpenChange={handleOpenChange}getAnchorRect={props.getAnchorRect}placement="bottom-start"gutter={4}>- <TagPickerBody- docTags={props.docTags}- onClose={() => props.onOpenChange(false)}- // Focus starts outside the popover (the opener, e.g. a context menu,- // is still tearing down when it mounts), so dismissing on- // focus-outside would close it immediately. Pointer-down outside and- // Escape still dismiss.- dismissOnFocusOutside={false}- />+ <Show when={props.open}>+ <TagPickerBody+ docTags={props.docTags}+ onClose={() => props.onOpenChange(false)}+ registerSave={(handler) => {+ saveAndClose = handler;+ }}+ />+ </Show></Popover>);}@@ -123,152 +174,453 @@ export function TagPickerPopover(props: {function TagPickerBody(props: {docTags: DocTags;onClose: () => void;- dismissOnFocusOutside?: boolean;+ registerSave: (handler: (() => Promise<void>) | undefined) => void;}) {const [search, setSearch] = createSignal('');- const [createScope, setCreateScope] = createSignal<TagScope>('user');- const [createColor, setCreateColor] = createSignal<string>(DEFAULT_TAG_COLOR);- const [editingId, setEditingId] = createSignal<string | null>(null);-+ const [saved, setSaved] = createSignal(false);+ const [selectedIds, setSelectedIds] = createSignal<Set<string>>(+ new Set(props.docTags.appliedTags().map((tag) => tag.optionId))+ );+ const [createStep, setCreateStep] = createSignal<CreateStep | null>(null);+ const [createDraftLabel, setCreateDraftLabel] = createSignal('');+ const [selectedColorIndex, setSelectedColorIndex] = createSignal(0);+ const [selectedScopeIndex, setSelectedScopeIndex] = createSignal(0);+ const currentTeamQuery = useCurrentTeamQuery();const addOption = useAddPropertyOptionMutation();const ensureTagSet = useEnsureTagSetMutation();+ let scrollContainerRef: HTMLDivElement | undefined;- const hasTeamSet = createMemo(() =>- props.docTags.tagSets().some((set) => set.scope === 'team')+ const initialAppliedTags = createMemo(() => props.docTags.appliedTags());+ const initialAppliedIds = createMemo(+ () => new Set(initialAppliedTags().map((tag) => tag.optionId)));+ const initialTagState = createMemo(() => {+ const optionScopes = new Map<string, TagScope>();+ const optionsById = new Map<string, PropertyOptionResponse>();+ const itemsByScope = new Map<TagScope, TagOptionItem[]>();++ for (const set of props.docTags.tagSets()) {+ for (const option of set.options) {+ optionsById.set(option.id, option);+ }++ itemsByScope.set(+ set.scope,+ [...set.options]+ .sort((a, b) => a.displayOrder - b.displayOrder)+ .map((option) => {+ optionScopes.set(option.id, set.scope);+ return {+ scope: set.scope,+ option,+ };+ })+ );+ }- const query = () => search().trim().toLowerCase();-- const filteredSet = (scope: TagScope): PropertyOptionResponse[] => {- const set = props.docTags.tagSets().find((s) => s.scope === scope);- if (!set) return [];- const q = query();- const options = q- ? set.options.filter((option) =>- optionLabel(option).toLowerCase().includes(q)- )- : set.options;- return [...options].sort((a, b) => a.displayOrder - b.displayOrder);+ const selectedItems = initialAppliedTags().flatMap((tag) => {+ const option = optionsById.get(tag.optionId);+ return option ? [{ scope: tag.scope, option }] : [];+ });++ return {+ optionScopes,+ itemsByScope,+ selectedItems,+ items: [...itemsByScope.values()].flat(),+ };+ });++ createEffect(() => {+ const appliedTags = initialAppliedTags();+ if (untrack(saved)) return;+ setSelectedIds(new Set(appliedTags.map((tag) => tag.optionId)));+ });++ const isSelected = (optionId: string) => selectedIds().has(optionId);++ const toggleSelected = (optionId: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(optionId)) next.delete(optionId);+ else next.add(optionId);+ return next;+ });+ };++ const optionScope = (optionId: string): TagScope | undefined =>+ initialTagState().optionScopes.get(optionId);++ const persistSelection = async () => {+ if (saved()) return true;+ setSaved(true);++ try {+ const nextSelectedIds = selectedIds();+ for (const tag of initialAppliedTags()) {+ if (!nextSelectedIds.has(tag.optionId)) {+ await props.docTags.removeTag(tag.scope, tag.optionId);+ }+ }++ for (const optionId of nextSelectedIds) {+ if (initialAppliedIds().has(optionId)) continue;+ const scope = optionScope(optionId);+ if (scope) await props.docTags.applyTag(scope, optionId);+ }+ return true;+ } catch (error) {+ setSaved(false);+ console.error('Failed to persist tag selection', error);+ return false;+ }+ };++ const save = async () => {+ return persistSelection();+ };++ const saveAndClose = async () => {+ if (await save()) props.onClose();};- const exactMatchExists = createMemo(() => {- const q = search().trim().toLowerCase();- if (!q) return false;- return props.docTags- .tagSets()- .some((set) =>- set.options.some((option) => optionLabel(option).toLowerCase() === q)+ const filteredItems = createMemo(() => {+ const query = search().trim().toLowerCase();+ const matchesSearch = (item: TagOptionItem) =>+ !query || optionLabel(item.option).toLowerCase().includes(query);++ const selectedAtOpen =+ initialTagState().selectedItems.filter(matchesSearch);+ const remainingForScope = (scope: TagScope) =>+ (initialTagState().itemsByScope.get(scope) ?? []).filter(+ (item) =>+ !initialAppliedIds().has(item.option.id) && matchesSearch(item));++ return [+ ...selectedAtOpen,+ ...remainingForScope('user'),+ ...remainingForScope('team'),+ ];});- const handleCreate = async () => {- const value = search().trim();- if (!value || exactMatchExists()) return;- const scope = createScope();- const provisioned = await ensureTagSet.mutateAsync({ scope });- if (!provisioned.definition) return;- const created = await addOption.mutateAsync({- propertyDefinitionId: provisioned.definition.id,- body: {- type: 'select_string',- option: {- value,- display_order: nextDisplayOrder(provisioned.options),- color: createColor(),+ const selectedAtOpenItems = createMemo(() => {+ const query = search().trim().toLowerCase();+ return initialTagState().selectedItems.filter(+ (item) => !query || optionLabel(item.option).toLowerCase().includes(query)+ );+ });++ const remainingItemsForScope = (scope: TagScope) => {+ const query = search().trim().toLowerCase();+ return (initialTagState().itemsByScope.get(scope) ?? []).filter(+ (item) =>+ !initialAppliedIds().has(item.option.id) &&+ (!query || optionLabel(item.option).toLowerCase().includes(query))+ );+ };++ const createLabel = () => search().trim();+ const exactTagMatchExists = () => {+ const label = createLabel().toLowerCase();+ return (+ !!label &&+ initialTagState().items.some(+ (item) => optionLabel(item.option).toLowerCase() === label+ )+ );+ };+ const showCreateRow = () =>+ createLabel().length >= 2 && !exactTagMatchExists();+ const createRowIndex = () => filteredItems().length;+ const teamName = () => currentTeamQuery.data?.team.name?.trim() || 'Team';+ const scopeOptions = createMemo<{ scope: TagScope; label: string }[]>(() => [+ { scope: 'user', label: 'Personal' },+ { scope: 'team', label: `Shared with ${teamName()}` },+ ]);+ const selectedColor = () =>+ TAG_COLOR_OPTIONS[selectedColorIndex()]?.color ?? DEFAULT_TAG_COLOR;+ const createItemCount = () =>+ createStep() === 'color' ? TAG_COLOR_OPTIONS.length : scopeOptions().length;++ const beginCreate = () => {+ const label = createLabel();+ if (!showCreateRow() || !label) return;+ setCreateDraftLabel(label);+ setSelectedColorIndex(0);+ setSelectedScopeIndex(0);+ setCreateStep('color');+ };++ const createTag = async (scope: TagScope) => {+ const value = createDraftLabel().trim();+ if (!value) return;++ try {+ if (!(await persistSelection())) return;++ const provisioned = await ensureTagSet.mutateAsync({ scope });+ if (!provisioned.definition) return;++ const created = await addOption.mutateAsync({+ propertyDefinitionId: provisioned.definition.id,+ body: {+ type: 'select_string',+ option: {+ value,+ display_order: nextDisplayOrder(provisioned.options),+ color: selectedColor(),+ },},- },- });- invalidateTags();- await props.docTags.applyTag(scope, created.id);- setSearch('');+ });+ invalidateTags();+ await props.docTags.applyTag(scope, created.id);+ props.onClose();+ } catch (error) {+ console.error('Failed to create tag', error);+ }+ };++ const handleCreateKeyDown = (event: KeyboardEvent) => {+ const step = createStep();+ if (!step) return;++ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ if (step === 'scope') {+ setCreateStep('color');+ return;+ }+ setCreateStep(null);+ return;+ }++ const count = createItemCount();+ if (count === 0) return;++ if (event.key === 'ArrowDown' || (event.ctrlKey && event.key === 'j')) {+ event.preventDefault();+ if (step === 'color') {+ setSelectedColorIndex((prev) => (prev + 1) % count);+ } else {+ setSelectedScopeIndex((prev) => (prev + 1) % count);+ }+ } else if (+ event.key === 'ArrowUp' ||+ (event.ctrlKey && event.key === 'k')+ ) {+ event.preventDefault();+ if (step === 'color') {+ setSelectedColorIndex((prev) => (prev - 1 + count) % count);+ } else {+ setSelectedScopeIndex((prev) => (prev - 1 + count) % count);+ }+ } else if (event.key === 'Enter') {+ event.preventDefault();+ if (step === 'color') {+ setCreateStep('scope');+ } else {+ const scope = scopeOptions()[selectedScopeIndex()]?.scope;+ if (scope) void createTag(scope);+ }+ }};- const closePicker = () => {- setSearch('');- setEditingId(null);- props.onClose();+ const dropdown = useDropdownSearch({+ itemCount: () => filteredItems().length + (showCreateRow() ? 1 : 0),+ onSelect: (index, event) => {+ if (showCreateRow() && index === createRowIndex()) {+ beginCreate();+ return;+ }++ const item = filteredItems()[index];+ if (!item) return;++ toggleSelected(item.option.id);+ if (!event?.shiftKey) saveAndClose();+ },+ onClose: saveAndClose,+ enableNumericHotkeys: false,+ });++ // Reset selected index to top when search term or list changes.+ createEffect(() => {+ if (createStep()) return;+ search();+ filteredItems().length;+ dropdown.setSelectedIndex(0);+ });++ createEffect(() => {+ if (createStep()) return;+ const index = dropdown.selectedIndex();+ if (!dropdown.keyboardMode() || !scrollContainerRef) return;++ const row = scrollContainerRef.querySelector<HTMLDivElement>(+ `[data-tag-index="${index}"]`+ );+ row?.scrollIntoView({ block: 'nearest' });+ });++ const handleKeyDown = (event: KeyboardEvent) => {+ if (saved()) return;+ if (createStep()) {+ handleCreateKeyDown(event);+ return;+ }+ dropdown.handleKeyDown(event);};+ onMount(() => {+ props.registerSave(saveAndClose);+ document.addEventListener('keydown', handleKeyDown);+ });++ onCleanup(() => {+ props.registerSave(undefined);+ document.removeEventListener('keydown', handleKeyDown);+ });+return (<Popover.Portal><Layer depth={3}><Popover.Content- class="z-modal w-64 rounded-xl bg-surface text-sm shadow-lg ring ring-edge-muted"+ class="z-modal w-64 rounded-xl bg-surface text-sm shadow-menu ring ring-edge-muted menu-open-animation"onCloseAutoFocus={(event) => event.preventDefault()}- onFocusOutside={(event) => {- if (props.dismissOnFocusOutside === false) event.preventDefault();- }}>- <div class="flex items-center gap-2 border-b border-edge-muted px-2 py-2">- <SearchIcon class="size-4 text-ink-muted" />- <input- class="w-full bg-transparent caret-accent outline-none"- value={search()}- placeholder="Search or create label"- onInput={(event) => setSearch(event.currentTarget.value)}- onKeyDown={(event) => {- if (event.key === 'Enter') {- event.preventDefault();- handleCreate();- } else if (event.key === 'Escape') {- event.preventDefault();- closePicker();- }- }}- />- </div>-- <div class="max-h-72 scroll-pb-1.5 overflow-y-auto p-1.5">- <For each={['user', 'team'] as const}>- {(scope) => (- <Show when={scope === 'user' || hasTeamSet()}>- <Show when={filteredSet(scope).length > 0}>- <div class="px-2 pb-1 pt-2 text-xs text-ink-extra-muted">- {SCOPE_LABEL[scope]}- </div>- <For each={filteredSet(scope)}>- {(option) => (- <TagPickerRow- scope={scope}- option={option}- docTags={props.docTags}- editing={editingId() === option.id}- onEdit={() => setEditingId(option.id)}- onEditClose={() => setEditingId(null)}+ <Show+ when={createStep()}+ fallback={+ <>+ <DropdownSearchInput+ value={search()}+ placeholder="Change or Add tags"+ onInput={(value) => {+ setSearch(value);+ dropdown.setSearchQuery(value);+ }}+ />+ <div class="p-1.5">+ <div+ ref={scrollContainerRef}+ class="overflow-y-auto overflow-x-hidden scrollbar-hidden"+ style={{ 'max-height': `${MAX_LIST_HEIGHT}px` }}+ >+ <Show+ when={filteredItems().length > 0 || showCreateRow()}+ fallback={+ <div class="px-2 py-4 text-center text-ink-muted">+ {initialTagState().items.length === 0+ ? 'No tags available'+ : 'No tags match your search'}+ </div>+ }+ >+ <For each={selectedAtOpenItems()}>+ {(item) => (+ <TagPickerRow+ item={item}+ index={filteredItems().indexOf(item)}+ teamName={teamName()}+ checked={isSelected(item.option.id)}+ selected={+ dropdown.selectedIndex() ===+ filteredItems().indexOf(item)+ }+ onSelect={(event) => {+ toggleSelected(item.option.id);+ if (!event.shiftKey) saveAndClose();+ }}+ onMouseEnter={() => {+ if (!dropdown.keyboardMode()) {+ dropdown.setSelectedIndex(+ filteredItems().indexOf(item)+ );+ }+ }}+ />+ )}+ </For>+ <Show+ when={+ selectedAtOpenItems().length > 0 &&+ (remainingItemsForScope('user').length > 0 ||+ remainingItemsForScope('team').length > 0)+ }+ >+ <div class="my-1 border-t border-edge-muted" />+ </Show>+ <For each={['user', 'team'] as const}>+ {(scope) => (+ <For each={remainingItemsForScope(scope)}>+ {(item) => (+ <TagPickerRow+ item={item}+ index={filteredItems().indexOf(item)}+ teamName={teamName()}+ checked={isSelected(item.option.id)}+ selected={+ dropdown.selectedIndex() ===+ filteredItems().indexOf(item)+ }+ onSelect={(event) => {+ toggleSelected(item.option.id);+ if (!event.shiftKey) saveAndClose();+ }}+ onMouseEnter={() => {+ if (!dropdown.keyboardMode()) {+ dropdown.setSelectedIndex(+ filteredItems().indexOf(item)+ );+ }+ }}+ />+ )}+ </For>+ )}+ </For>+ <Show when={showCreateRow()}>+ <CreateTagRow+ index={createRowIndex()}+ label={createLabel()}+ selected={+ dropdown.selectedIndex() === createRowIndex()+ }+ onClick={beginCreate}+ onMouseEnter={() => {+ if (!dropdown.keyboardMode()) {+ dropdown.setSelectedIndex(createRowIndex());+ }+ }}/>- )}- </For>- </Show>- </Show>- )}- </For>-- <Show when={search().trim() && !exactMatchExists()}>- <CreateRow- label={search().trim()}- scope={createScope()}- color={createColor()}- hasTeamSet={hasTeamSet()}+ </Show>+ </Show>+ </div>+ </div>+ </>+ }+ >+ {(step) => (+ <CreateTagFlow+ step={step()}+ label={createDraftLabel()}+ colorOptions={TAG_COLOR_OPTIONS}+ selectedColorIndex={selectedColorIndex()}+ scopeOptions={scopeOptions()}+ selectedScopeIndex={selectedScopeIndex()}pending={addOption.isPending || ensureTagSet.isPending}- onScope={setCreateScope}- onColor={setCreateColor}- onCreate={handleCreate}- onCancel={() => setSearch('')}+ onColorMouseEnter={setSelectedColorIndex}+ onColorSelect={(index) => {+ setSelectedColorIndex(index);+ setCreateStep('scope');+ }}+ onScopeMouseEnter={setSelectedScopeIndex}+ onScopeSelect={(scope) => void createTag(scope)}/>- </Show>-- <Show- when={- props.docTags- .tagSets()- .every((set) => set.options.length === 0) && !search().trim()- }- >- <div class="px-2 py-4 text-center text-ink-muted">- Type to create your first label- </div>- </Show>- </div>+ )}+ </Show></Popover.Content></Layer></Popover.Portal>@@ -276,242 +628,117 @@ function TagPickerBody(props: {}function TagPickerRow(props: {- scope: TagScope;- option: PropertyOptionResponse;- docTags: DocTags;- editing: boolean;- onEdit: () => void;- onEditClose: () => void;+ item: TagOptionItem;+ index: number;+ teamName: string;+ checked: boolean;+ selected: boolean;+ onSelect: (event: MouseEvent) => void;+ onMouseEnter: () => void;}) {- const updateOption = useUpdatePropertyOptionMutation();- const deleteOption = useDeletePropertyOptionMutation();- const [confirmDelete, setConfirmDelete] = createSignal(false);- const [draftLabel, setDraftLabel] = createSignal(optionLabel(props.option));- const [draftColor, setDraftColor] = createSignal(- props.option.color ?? DEFAULT_TAG_COLOR- );-- const beginEdit = () => {- setDraftLabel(optionLabel(props.option));- setDraftColor(props.option.color ?? DEFAULT_TAG_COLOR);- props.onEdit();- };-- const saveEdit = async () => {- const value = draftLabel().trim();- await updateOption.mutateAsync({- propertyDefinitionId: props.option.propertyDefinitionId,- optionId: props.option.id,- body: {- value: value || undefined,- color: draftColor(),- },- });- props.onEditClose();- };-- const handleDelete = async () => {- await deleteOption.mutateAsync({- propertyDefinitionId: props.option.propertyDefinitionId,- optionId: props.option.id,- });- setConfirmDelete(false);- props.onEditClose();- };-return (- <Switch>- <Match when={props.editing}>- <div- class="flex flex-col gap-2 rounded-lg bg-hover p-2"- ref={scrollExpandedRowIntoView}- >- <div class="flex items-center gap-2">- <TagDot color={draftColor()} />- <input- class="w-full bg-transparent caret-accent outline-none"- value={draftLabel()}- ref={focusWithoutScroll}- onInput={(event) => setDraftLabel(event.currentTarget.value)}- onKeyDown={(event) => {- if (event.key === 'Enter') {- event.preventDefault();- saveEdit();- }- }}- />- </div>- <ColorSwatchRow- selected={draftColor()}- onSelect={(color) => setDraftColor(color)}- />- <div class="flex items-center justify-between">- <Button- variant="ghost"- size="sm"- class="gap-1.5 text-failure-ink"- onClick={() => setConfirmDelete(true)}- >- <Trash class="size-3.5" />- Delete- </Button>- <div class="flex items-center gap-1.5">- <Button variant="ghost" size="sm" onClick={props.onEditClose}>- Cancel- </Button>- <Button- variant="base"- size="sm"- onClick={saveEdit}- disabled={updateOption.isPending}- >- Save- </Button>- </div>- </div>- </div>- <DeleteConfirm- open={confirmDelete()}- label={optionLabel(props.option)}- onCancel={() => setConfirmDelete(false)}- onConfirm={handleDelete}- />- </Match>- <Match when={!props.editing}>- <div class="group flex items-center gap-2 rounded-lg p-1.5 hover:bg-hover">- <button- type="button"- class="flex min-w-0 flex-1 items-center gap-2 text-left"- onClick={() =>- props.docTags.toggleTag(props.scope, props.option.id)- }- >- <TagDot color={props.option.color ?? undefined} />- <span class="min-w-0 flex-1 truncate">- {optionLabel(props.option)}- </span>- <SingleSelectCheck- active={props.docTags.isApplied(props.option.id)}- />- </button>- <button- type="button"- class="shrink-0 rounded-md p-1 text-ink-muted opacity-0 hover:bg-active hover:text-ink group-hover:opacity-100"- aria-label={`Edit ${optionLabel(props.option)}`}- onClick={beginEdit}- >- <PencilSimple class="size-3.5" />- </button>- </div>- </Match>- </Switch>+ <div data-tag-index={props.index}>+ <DropdownSelectableRow+ isSelected={props.selected}+ onClick={props.onSelect}+ onMouseEnter={props.onMouseEnter}+ >+ <OptionCheckBox checked={props.checked} multiselect />+ <TagDot color={props.item.option.color ?? undefined} />+ <span class="min-w-0 truncate">{optionLabel(props.item.option)}</span>+ <Show when={props.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>+ </DropdownSelectableRow>+ </div>);}-function CreateRow(props: {+function CreateTagRow(props: {+ index: number;label: string;- scope: TagScope;- color: string;- hasTeamSet: boolean;- pending: boolean;- onScope: (scope: TagScope) => void;- onColor: (color: string) => void;- onCreate: () => void;- onCancel: () => void;+ selected: boolean;+ onClick: () => void;+ onMouseEnter: () => void;}) {return (<div- class="mt-1 flex flex-col gap-2 rounded-lg border border-edge-muted p-2"- ref={scrollExpandedRowIntoView}+ data-tag-index={props.index}+ class="rounded-lg w-full flex items-center gap-2 p-1.5 px-2 text-left text-ink font-normal cursor-default"+ classList={{+ 'bg-hover': props.selected,+ }}+ onClick={props.onClick}+ onMouseEnter={props.onMouseEnter}>- <div class="flex items-center gap-2">- <TagDot color={props.color} />- <span class="min-w-0 flex-1 truncate">New label "{props.label}"</span>- </div>- <ColorSwatchRow selected={props.color} onSelect={props.onColor} />- <Show when={props.hasTeamSet}>- <div class="flex items-center gap-1">- <For each={['user', 'team'] as const}>- {(scope) => (- <button- type="button"- class={cn(- 'rounded-md px-2 py-0.5 text-xs',- props.scope === scope- ? 'bg-accent text-surface'- : 'text-ink-muted hover:bg-hover'- )}- onClick={() => props.onScope(scope)}- >- {scope === 'user' ? 'My label' : 'Team label'}- </button>- )}- </For>- </div>- </Show>- <div class="flex items-center justify-end gap-1.5">- <Button variant="ghost" size="sm" onClick={props.onCancel}>- Cancel- </Button>- <Button- variant="base"- size="sm"- onClick={props.onCreate}- disabled={props.pending}- >- Create- </Button>+ <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></div>);}-function ColorSwatchRow(props: {- selected: string;- onSelect: (color: string) => void;-}) {- return (- <div class="flex flex-wrap items-center gap-1.5">- <For each={TAG_COLORS}>- {(color) => (- <button- type="button"- class={cn(- 'size-4 rounded-full ring-offset-1 ring-offset-surface',- props.selected === color ? 'ring-2 ring-ink' : 'ring-0'- )}- style={{ 'background-color': color }}- aria-label={`Color ${color}`}- onClick={() => props.onSelect(color)}- />- )}- </For>- </div>- );-}--function DeleteConfirm(props: {- open: boolean;+function CreateTagFlow(props: {+ step: CreateStep;label: string;- onCancel: () => void;- onConfirm: () => void;+ colorOptions: typeof TAG_COLOR_OPTIONS;+ selectedColorIndex: number;+ scopeOptions: { scope: TagScope; label: string }[];+ selectedScopeIndex: number;+ pending: boolean;+ onColorMouseEnter: (index: number) => void;+ onColorSelect: (index: number) => void;+ onScopeMouseEnter: (index: number) => void;+ onScopeSelect: (scope: TagScope) => void;}) {return (- <Dialog open={props.open} position="center" onOpenChange={props.onCancel}>- <div class="rounded-xl bg-surface p-4 text-sm ring ring-edge-muted">- <div class="text-ink">Delete label "{props.label}"?</div>- <p class="mt-1 text-ink-muted">- It will be removed from every item it's applied to.- </p>- <div class="mt-4 flex items-center justify-end gap-2">- <Button variant="ghost" size="sm" onClick={props.onCancel}>- Cancel- </Button>- <Button variant="danger" size="sm" onClick={props.onConfirm}>- Delete- </Button>- </div>+ <div class="p-1.5">+ <div class="px-2 pb-1 pt-1 text-xs text-ink-extra-muted">+ Create tag "{props.label}"</div>- </Dialog>+ <Show+ when={props.step === 'color'}+ fallback={+ <For each={props.scopeOptions}>+ {(option, index) => (+ <DropdownSelectableRow+ isSelected={props.selectedScopeIndex === index()}+ onMouseEnter={() => props.onScopeMouseEnter(index())}+ onClick={() => props.onScopeSelect(option.scope)}+ >+ <TagDot+ color={+ props.colorOptions[props.selectedColorIndex]?.color ??+ DEFAULT_TAG_COLOR+ }+ />+ <span class="min-w-0 flex-1 truncate">{option.label}</span>+ <Show+ when={props.pending && props.selectedScopeIndex === index()}+ >+ <span class="text-xs text-ink-muted">Creating...</span>+ </Show>+ </DropdownSelectableRow>+ )}+ </For>+ }+ >+ <For each={props.colorOptions}>+ {(option, index) => (+ <DropdownSelectableRow+ isSelected={props.selectedColorIndex === index()}+ onMouseEnter={() => props.onColorMouseEnter(index())}+ onClick={() => props.onColorSelect(index())}+ >+ <TagDot color={option.color} />+ <span class="min-w-0 flex-1 truncate">{option.name}</span>+ </DropdownSelectableRow>+ )}+ </For>+ </Show>+ </div>);}diff --git a/apps/web/src/features/property/tags/TagsRow.tsx b/apps/web/src/features/property/tags/TagsRow.tsxindex d3f9a3c4a2..68d35e8f86 100644--- a/apps/web/src/features/property/tags/TagsRow.tsx+++ b/apps/web/src/features/property/tags/TagsRow.tsx@@ -1,33 +1,103 @@-import PencilSimpleIcon from '@phosphor/pencil-simple.svg';+import { useSplitLayout } from '@components/app/split-layout/layout';+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 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, Show } from 'solid-js';+import { For, Match, Show, Switch } from 'solid-js';import { TagDot } from './TagDot';import { TagPicker } from './TagPicker';+import {+ buildTaggedItemsSplitContent,+ buildTaggedItemsSplitOptions,+} from './tagNavigation';+import type { ResolvedTag } from './useDocTags';import { useDocTags } from './useDocTags';const chipClass = cn(- 'inline-flex items-center gap-1.5 min-w-0 max-w-[30ch]',- 'px-2 py-1 leading-tight rounded-full bg-surface'+ 'inline-flex items-center gap-1.5 m-px min-w-0 max-w-[30ch]',+ 'px-2 py-1 leading-tight rounded-full ring ring-edge-muted bg-surface',+ 'text-ink-muted transition-colors hover:bg-hover hover:text-ink');+function TagChip(props: {+ tag: ResolvedTag;+ docTags: ReturnType<typeof useDocTags>;+ canEdit: boolean;+}) {+ const split = useSplitLayout();+ const panel = useSplitPanel();++ const viewTaggedItems = () => {+ split.openWithSplit(+ buildTaggedItemsSplitContent(props.tag),+ buildTaggedItemsSplitOptions({ handle: panel?.handle })+ );+ };++ const removeTag = () => {+ void props.docTags.removeTag(props.tag.scope, props.tag.optionId);+ };++ return (+ <Layer depth={2}>+ <ContextMenu>+ <ContextMenu.Trigger class="contents">+ <Show+ when={props.canEdit}+ fallback={+ <span class={cn(chipClass, 'cursor-default hover:bg-surface')}>+ <TagDot color={props.tag.color} />+ <span class="min-w-0 truncate">{props.tag.label}</span>+ </span>+ }+ >+ <TagPicker+ docTags={props.docTags}+ replaceTag={props.tag}+ triggerClass={chipClass}+ triggerLabel={`Change or select tag ${props.tag.label}`}+ >+ <TagDot color={props.tag.color} />+ <span class="min-w-0 truncate">{props.tag.label}</span>+ </TagPicker>+ </Show>+ </ContextMenu.Trigger>+ <ContextMenu.Portal>+ <ContextMenuContent class="text-xs text-ink-muted">+ <MenuItem+ icon={FunnelIcon}+ text="View all items with tag"+ onClick={viewTaggedItems}+ />+ <Show when={props.canEdit}>+ <MenuItem icon={XIcon} text="Remove tag" onClick={removeTag} />+ </Show>+ </ContextMenuContent>+ </ContextMenu.Portal>+ </ContextMenu>+ </Layer>+ );+}+export function TagsRow(props: {entityId: string;entityType: EntityType;canEdit: boolean;+ triggerVariant?: 'icon' | 'pill';}) {const docTags = useDocTags(props.entityId, props.entityType);+ const triggerVariant = () => props.triggerVariant ?? 'icon';+ const hasTags = () => docTags.appliedTags().length > 0;return (<div class="flex flex-wrap items-center gap-1.5"><For each={docTags.appliedTags()}>{(tag) => (- <Layer depth={2}>- <span class={chipClass}>- <TagDot color={tag.color} />- <span class="min-w-0 truncate">{tag.label}</span>- </span>- </Layer>+ <TagChip tag={tag} docTags={docTags} canEdit={props.canEdit} />)}</For><Show@@ -38,16 +108,35 @@ export function TagsRow(props: {</Show>}>- <TagPicker- docTags={docTags}- triggerClass={cn(- 'inline-flex size-5 items-center justify-center rounded-full',- 'text-ink-muted transition-colors hover:bg-hover hover:text-ink'- )}- triggerLabel="Edit tags"- >- <PencilSimpleIcon class="size-3" />- </TagPicker>+ <Switch>+ <Match when={triggerVariant() === 'pill' && !hasTags()}>+ <TagPicker+ docTags={docTags}+ triggerClass={cn(+ 'inline-flex items-center gap-1.5 m-px ring ring-edge-muted bg-surface',+ 'px-2 py-1 leading-tight rounded-full text-ink-muted',+ 'hover:bg-hover hover:text-ink transition-colors'+ )}+ triggerLabel="Add tags"+ >+ <PlusIcon class="size-3" />+ <span>Add tags</span>+ </TagPicker>+ </Match>+ <Match when={true}>+ <TagPicker+ docTags={docTags}+ triggerClass={cn(+ 'inline-flex items-center justify-center rounded-full px-1 py-1 leading-tight',+ 'm-px ring ring-edge-muted bg-surface text-ink-muted',+ 'transition-colors hover:bg-hover hover:text-ink'+ )}+ triggerLabel="Add tags"+ >+ <PlusIcon class="size-3" />+ </TagPicker>+ </Match>+ </Switch></Show></div>);diff --git a/apps/web/src/features/property/tags/index.ts b/apps/web/src/features/property/tags/index.tsindex 632f83968d..e04a179935 100644--- a/apps/web/src/features/property/tags/index.ts+++ b/apps/web/src/features/property/tags/index.ts@@ -1,5 +1,15 @@-export { EntityRowTags } from './EntityRowTags';+export {+ EntityRowTags,+ InlineEntityTagsPill,+ InlineFetchedEntityTagsPill,+ InlineTagsPill,+} from './EntityRowTags';export { TagPicker, TagPickerPopover } from './TagPicker';export { TagsRow } from './TagsRow';export { DEFAULT_TAG_COLOR, TAG_COLORS } from './tagColors';-export { type ResolvedTag, useDocTags, useSoupDocTags } from './useDocTags';+export {+ type ResolvedTag,+ useDocTags,+ useLocalDocTags,+ useSoupDocTags,+} from './useDocTags';diff --git a/apps/web/src/features/property/tags/tagNavigation.ts b/apps/web/src/features/property/tags/tagNavigation.tsnew file mode 100644index 0000000000..cddc4bb3c2--- /dev/null+++ b/apps/web/src/features/property/tags/tagNavigation.ts@@ -0,0 +1,62 @@+import type {+ PropertyFilter,+ Query,+} from '@app/features/next-soup/filters/filter-store';+import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';+import type {+ OpenWithSplitOptions,+ SplitContent,+} from '@components/app/split-layout/layoutManager';++export type TagNavigationTarget = {+ optionId: string;+ propertyDefinitionId: string;+};++export function tagToPropertyFilter(tag: TagNavigationTarget): PropertyFilter {+ return {+ propertyId: tag.propertyDefinitionId,+ type: 'select',+ value: tag.optionId,+ };+}++export function buildTaggedItemsQuery(tag: TagNavigationTarget): Query {+ const baseline = getViewPreset('search')?.filters ?? {};+ return {+ ...baseline,+ include: {+ ...baseline.include,+ tagFilters: [tagToPropertyFilter(tag)],+ tagFilterMode: 'any',+ },+ exclude: { ...baseline.exclude },+ };+}++export function buildTaggedItemsSplitContent(+ tag: TagNavigationTarget+): SplitContent {+ const searchPreset = getViewPreset('search');+ return {+ type: 'component',+ id: 'search',+ preserveParams: true,+ params: {+ initialFilters: buildTaggedItemsQuery(tag),+ initialClientFilters: searchPreset?.clientFilters,+ },+ };+}++export function buildTaggedItemsSplitOptions(+ options: Pick<OpenWithSplitOptions, 'handle'> = {}+): OpenWithSplitOptions {+ return {+ ...options,+ activate: true,+ allowDuplicate: true,+ preferNewSplit: true,+ referredFrom: null,+ };+}diff --git a/apps/web/src/features/property/tags/useDocTags.ts b/apps/web/src/features/property/tags/useDocTags.tsindex 4e6abe5fca..0fb3dc0327 100644--- a/apps/web/src/features/property/tags/useDocTags.ts+++ b/apps/web/src/features/property/tags/useDocTags.ts@@ -12,12 +12,18 @@ import type { PropertyOptionResponse } from '@service-properties/generated/schemimport type { TagScope } from '@service-properties/generated/schemas/tagScope';import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';-import { type Accessor, createMemo } from 'solid-js';+import {+ type Accessor,+ createEffect,+ createMemo,+ createSignal,+} from 'solid-js';import { useEntityProperties } from '../hooks';import type { PropertyDefinitionDomain } from '../types';export type ResolvedTag = {optionId: string;+ propertyDefinitionId: string;scope: TagScope;label: string;color?: string;@@ -27,12 +33,10 @@ function optionLabel(option: PropertyOptionResponse): string {return option.value.type === 'string' ? option.value.value : '';}-function compareTags(a: ResolvedTag, b: ResolvedTag): number {- return (- a.label.localeCompare(b.label) ||- a.scope.localeCompare(b.scope) ||- a.optionId.localeCompare(b.optionId)- );+function sameOptionIds(a: string[], b: string[]): boolean {+ if (a.length !== b.length) return false;+ const bSet = new Set(b);+ return a.every((id) => bSet.has(id));}function definitionDomain(@@ -51,15 +55,22 @@ function definitionDomain(};}+type SetTagOptionIdsForDefinition = (+ definition: PropertyDefinitionDetailResponse,+ optionIds: string[]+) => Promise<void> | void;+function createDocTags(- entityId: string,- entityType: EntityType,- appliedOptionIdsForDefinition: (definitionId: string) => string[]+ appliedOptionIdsForDefinition: (definitionId: string) => string[],+ setTagOptionIdsForDefinition: SetTagOptionIdsForDefinition) {const tagsQuery = useTagsQuery();const ensureTagSet = useEnsureTagSetMutation();- const addOption = useAddEntityPropertyOptionMutation();- const removeOption = useRemoveEntityPropertyOptionMutation();+ const [pendingOptionIdsByDefinition, setPendingOptionIdsByDefinition] =+ createSignal<Map<string, string[]>>(new Map());+ const [displayOptionOrder, setDisplayOptionOrder] = createSignal<string[]>(+ []+ );const tagSets = (): TagSetResponse[] => tagsQuery.data ?? [];@@ -77,6 +88,7 @@ function createDocTags(for (const option of set.options) {map.set(option.id, {optionId: option.id,+ propertyDefinitionId: option.propertyDefinitionId,scope: set.scope,label: optionLabel(option),color: option.color ?? undefined,@@ -86,21 +98,61 @@ function createDocTags(return map;});- const appliedTags = createMemo((): ResolvedTag[] => {+ const visibleOptionIdsForDefinition = (definitionId: string): string[] =>+ pendingOptionIdsByDefinition().get(definitionId) ??+ appliedOptionIdsForDefinition(definitionId);++ const visibleTags = createMemo((): ResolvedTag[] => {const resolved: ResolvedTag[] = [];const lookup = optionById();for (const definition of definitionByScope().values()) {- for (const optionId of appliedOptionIdsForDefinition(definition.id)) {+ for (const optionId of visibleOptionIdsForDefinition(definition.id)) {const tag = lookup.get(optionId);if (tag) resolved.push(tag);}}- return resolved.sort(compareTags);+ return resolved;+ });++ const appliedTags = createMemo((): ResolvedTag[] => {+ const tags = visibleTags();+ const order = displayOptionOrder();+ if (order.length === 0) return tags;++ const byId = new Map(tags.map((tag) => [tag.optionId, tag]));+ const ordered: ResolvedTag[] = [];+ for (const optionId of order) {+ const tag = byId.get(optionId);+ if (tag) {+ ordered.push(tag);+ byId.delete(optionId);+ }+ }+ return [...ordered, ...byId.values()];});const isApplied = (optionId: string): boolean =>appliedTags().some((tag) => tag.optionId === optionId);+ createEffect(() => {+ const pending = pendingOptionIdsByDefinition();+ if (pending.size === 0) return;++ let changed = false;+ const next = new Map(pending);+ for (const [definitionId, pendingIds] of pending) {+ const sourceIds = appliedOptionIdsForDefinition(definitionId);+ if (sameOptionIds(sourceIds, pendingIds)) {+ next.delete(definitionId);+ changed = true;+ }+ }++ if (changed) {+ setPendingOptionIdsByDefinition(next);+ }+ });+const resolveDefinition = async (scope: TagScope): Promise<PropertyDefinitionDetailResponse> => {@@ -117,13 +169,7 @@ function createDocTags(const definition = await resolveDefinition(scope);const current = appliedOptionIdsForDefinition(definition.id);if (current.includes(optionId)) return;- await addOption.mutateAsync({- entityId,- entityType,- property: definitionDomain(definition),- optionId,- optimisticOptionIds: [...current, optionId],- });+ await setTagOptionIdsForDefinition(definition, [...current, optionId]);};const removeTag = async (scope: TagScope, optionId: string) => {@@ -131,13 +177,10 @@ function createDocTags(if (!definition) return;const current = appliedOptionIdsForDefinition(definition.id);if (!current.includes(optionId)) return;- await removeOption.mutateAsync({- entityId,- entityType,- property: definitionDomain(definition),- optionId,- optimisticOptionIds: current.filter((id) => id !== optionId),- });+ await setTagOptionIdsForDefinition(+ definition,+ current.filter((id) => id !== optionId)+ );};const toggleTag = async (scope: TagScope, optionId: string) => {@@ -148,6 +191,61 @@ function createDocTags(}};+ const replaceTag = async (+ currentTag: ResolvedTag,+ nextScope: TagScope,+ nextOptionId: string+ ) => {+ if (currentTag.optionId === nextOptionId) return;++ const currentDefinition = definitionByScope().get(currentTag.scope);+ const nextDefinition = await resolveDefinition(nextScope);+ if (!currentDefinition) return;++ const previousOverrides = pendingOptionIdsByDefinition();+ const previousDisplayOrder = displayOptionOrder();+ const currentIds = visibleOptionIdsForDefinition(currentDefinition.id);+ const nextIds = visibleOptionIdsForDefinition(nextDefinition.id);++ setDisplayOptionOrder(+ appliedTags().map((tag) =>+ tag.optionId === currentTag.optionId ? nextOptionId : tag.optionId+ )+ );++ setPendingOptionIdsByDefinition((prev) => {+ const next = new Map(prev);+ next.set(+ currentDefinition.id,+ currentIds.filter((id) => id !== currentTag.optionId)+ );+ if (currentDefinition.id === nextDefinition.id) {+ next.set(+ currentDefinition.id,+ currentIds.map((id) =>+ id === currentTag.optionId ? nextOptionId : id+ )+ );+ } else if (!nextIds.includes(nextOptionId)) {+ next.set(nextDefinition.id, [...nextIds, nextOptionId]);+ }+ return next;+ });++ try {+ await removeTag(currentTag.scope, currentTag.optionId);+ if (+ !appliedOptionIdsForDefinition(nextDefinition.id).includes(nextOptionId)+ ) {+ await applyTag(nextScope, nextOptionId);+ }+ } catch (error) {+ setPendingOptionIdsByDefinition(previousOverrides);+ setDisplayOptionOrder(previousDisplayOrder);+ throw error;+ }+ };+return {tagsQuery,tagSets,@@ -156,22 +254,59 @@ function createDocTags(isApplied,applyTag,removeTag,+ replaceTag,toggleTag,};}export function useDocTags(entityId: string, entityType: EntityType) {const { properties } = useEntityProperties(entityId, entityType, false);+ const addOption = useAddEntityPropertyOptionMutation();+ const removeOption = useRemoveEntityPropertyOptionMutation();- return createDocTags(entityId, entityType, (definitionId) => {- const property = properties().find(- (prop) => prop.propertyDefinitionId === definitionId- );- if (!property) return [];- return property.valueType === 'SELECT_STRING' && property.value- ? property.value- : [];- });+ return createDocTags(+ (definitionId) => {+ const property = properties().find(+ (prop) => prop.propertyDefinitionId === definitionId+ );+ if (!property) return [];+ return property.valueType === 'SELECT_STRING' && property.value+ ? property.value+ : [];+ },+ async (definition, optionIds) => {+ const property = definitionDomain(definition);+ const current = (() => {+ const source = properties().find(+ (prop) => prop.propertyDefinitionId === definition.id+ );+ return source?.valueType === 'SELECT_STRING' && source.value+ ? source.value+ : [];+ })();+ const added = optionIds.find((id) => !current.includes(id));+ if (added) {+ await addOption.mutateAsync({+ entityId,+ entityType,+ property,+ optionId: added,+ optimisticOptionIds: optionIds,+ });+ return;+ }+ const removed = current.find((id) => !optionIds.includes(id));+ if (removed) {+ await removeOption.mutateAsync({+ entityId,+ entityType,+ property,+ optionId: removed,+ optimisticOptionIds: optionIds,+ });+ }+ }+ );}/**@@ -184,11 +319,55 @@ export function useSoupDocTags(entityType: EntityType,properties: Accessor<SoupProperty[] | undefined>) {- return createDocTags(entityId, entityType, (definitionId) => {- const property = properties()?.find(- (prop) => prop.definition.id === definitionId- );- const value = property?.value;- return value?.type === 'SelectOption' ? value.value : [];- });+ const addOption = useAddEntityPropertyOptionMutation();+ const removeOption = useRemoveEntityPropertyOptionMutation();++ return createDocTags(+ (definitionId) => {+ const property = properties()?.find(+ (prop) => prop.definition.id === definitionId+ );+ const value = property?.value;+ return value?.type === 'SelectOption' ? value.value : [];+ },+ async (definition, optionIds) => {+ const property = definitionDomain(definition);+ const source = properties()?.find(+ (prop) => prop.definition.id === definition.id+ );+ const current =+ source?.value?.type === 'SelectOption' ? source.value.value : [];+ const added = optionIds.find((id) => !current.includes(id));+ if (added) {+ await addOption.mutateAsync({+ entityId,+ entityType,+ property,+ optionId: added,+ optimisticOptionIds: optionIds,+ });+ return;+ }+ const removed = current.find((id) => !optionIds.includes(id));+ if (removed) {+ await removeOption.mutateAsync({+ entityId,+ entityType,+ property,+ optionId: removed,+ optimisticOptionIds: optionIds,+ });+ }+ }+ );+}++export function useLocalDocTags(+ appliedOptionIdsForDefinition: (definitionId: string) => string[],+ setTagOptionIdsForDefinition: SetTagOptionIdsForDefinition+) {+ return createDocTags(+ appliedOptionIdsForDefinition,+ setTagOptionIdsForDefinition+ );}