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(properties): basic tags UI (#4394)
gbirman64e0ffbc2ffa
diff --git a/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsx b/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsxindex 7df2459d9a..89526f0904 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsx@@ -75,8 +75,12 @@ export function TaskGridLayout(props: LayoutProps) {const propertyMap = createMemo(() => {const map = new Map<string, Property>();for (const sp of entity().properties ?? []) {- const property = soupPropertyToProperty(sp);- map.set(property.propertyDefinitionId, property);+ try {+ const property = soupPropertyToProperty(sp);+ map.set(property.propertyDefinitionId, property);+ } catch (error) {+ console.warn('Skipping property with unsupported type', error);+ }}return map;});diff --git a/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsx b/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsxindex 9b9e9177bd..657bfee5e9 100644--- a/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsx+++ b/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsx@@ -1,8 +1,13 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';import type { BlockAlias, BlockName } from '@core/block';import { PopupPreview } from '@core/component/DocumentPreview';import { HoverCard } from '@core/component/HoverCard';import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';import { itemToBlockName } from '@core/constant/allBlocks';+import {+ ENABLE_TAGS_FE_FLAG,+ ENABLE_TAGS_FE_OVERRIDE,+} from '@core/constant/featureFlags';import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';import Plus from '@phosphor/plus.svg';import DeleteIcon from '@phosphor/x.svg';@@ -15,10 +20,12 @@ import {usePropertiesContext,} from '@property/context/PropertiesContext';import { useEntityProperties, usePropertyEntityDisplay } from '@property/hooks';+import { TagsRow } from '@property/tags';import type { Property, PropertyApiValues } from '@property/types';import { getEntityValues, hasValue } from '@property/utils';import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';+import { useTagsQuery } from '@queries/properties/tags';import type { EntityType } from '@service-properties/generated/schemas/entityType';import { Button, Layer } from '@ui';import { cn } from '@ui/utils/classname';@@ -57,6 +64,20 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {props.includeMetadata ?? false);+ const tagsFlag = useFeatureFlag(ENABLE_TAGS_FE_FLAG, {+ enabledOverride: ENABLE_TAGS_FE_OVERRIDE,+ });++ const tagsQuery = useTagsQuery();+ const tagDefinitionIds = createMemo(+ () =>+ new Set(+ (tagsQuery.data ?? [])+ .map((set) => set.definition?.id)+ .filter((id): id is string => !!id)+ )+ );+const filteredPinnedProperties = createMemo(() => {const defaultPinnedIds = props.defaultPinnedPropertyIds?.() ?? [];const pinnedIds = props.pinnedPropertyIds?.() ?? [];@@ -64,6 +85,9 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {props.defaultPinnedPropertyIds !== undefined ||props.pinnedPropertyIds !== undefined;const pinned = properties().filter((property) => {+ if (tagDefinitionIds().has(property.propertyDefinitionId)) {+ return false;+ }if (props.propertyFilter && !props.propertyFilter(property)) {return false;}@@ -170,6 +194,22 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {<SidePanel.Loading /></Show>+ <Show+ when={+ tagsFlag().enabled &&+ (props.entityType === 'DOCUMENT' || props.entityType === 'TASK')+ }+ >+ <div class="mb-2 flex items-center gap-3">+ <span class="text-ink-muted">Tags</span>+ <TagsRow+ entityId={props.entityId}+ entityType={props.entityType}+ canEdit={props.canEdit}+ />+ </div>+ </Show>+<Show when={gridPinnedProperties().length > 0}><SidePanel.Grid class="auto-rows-[minmax(1.75rem,auto)]"><For each={gridPinnedProperties()}>diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 6f6133ff44..905970d46d 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -428,3 +428,7 @@ export const ENABLE_HOME_OVERRIDE = DEV_MODE_ENV ? true : undefined;export const ENABLE_NEW_PRICING_OVERRIDE =resolveFeatureFlag('ENABLE_NEW_PRICING', DEV_MODE_ENV) || undefined;++export const ENABLE_TAGS_FE_FLAG = 'enable-tags-fe';+export const ENABLE_TAGS_FE_OVERRIDE =+ resolveFeatureFlag('ENABLE_TAGS_FE', DEV_MODE_ENV) || undefined;diff --git a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsxindex ed600ff333..21a3cd53ea 100644--- a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx+++ b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx@@ -78,7 +78,16 @@ export function EntityKeyProperties(props: EntityKeyPropertiesProps) {const keyProperties = createMemo((): PropertyT[] => {const soupProperties = props.entity.properties ?? [];- return getSortedKeyProperties(soupProperties.map(soupPropertyToProperty));+ return getSortedKeyProperties(+ soupProperties.flatMap((soupProperty) => {+ try {+ return [soupPropertyToProperty(soupProperty)];+ } catch (error) {+ console.warn('Skipping property with unsupported type', error);+ return [];+ }+ })+ );});const saveMutation = useBulkSaveEntityPropertiesMutation();diff --git a/js/app/packages/entity/src/extractors-property/property-helpers.ts b/js/app/packages/entity/src/extractors-property/property-helpers.tsindex e33ca2dbc3..0cc4cf41e4 100644--- a/js/app/packages/entity/src/extractors-property/property-helpers.ts+++ b/js/app/packages/entity/src/extractors-property/property-helpers.ts@@ -153,7 +153,9 @@ export function soupPropertyToProperty(soupProperty: SoupProperty): Property {updatedAt: definition.updated_at,};- const valueType = definition.data_type as ValueType;+ const valueType = (+ definition.data_type === 'TAG' ? 'SELECT_STRING' : definition.data_type+ ) as ValueType;// Handle each value type with proper type checkingswitch (valueType) {@@ -252,8 +254,8 @@ export function soupPropertyToProperty(soupProperty: SoupProperty): Property {}default: {- // Fallback for unknown types - treat as string with null value- return { ...baseProperty, valueType: 'STRING', value: null };+ const exhaustiveCheck: never = valueType;+ throw new Error(`Unsupported value type: ${String(exhaustiveCheck)}`);}}}diff --git a/js/app/packages/property/src/api/converters.ts b/js/app/packages/property/src/api/converters.tsindex 0c2d929bc4..63507338dc 100644--- a/js/app/packages/property/src/api/converters.ts+++ b/js/app/packages/property/src/api/converters.ts@@ -64,7 +64,11 @@ export function entityPropertyFromApi(};const propertyValue = apiProperty.value;- const valueType = apiProperty.definition.data_type as ValueType;+ const valueType = (+ apiProperty.definition.data_type === 'TAG'+ ? 'SELECT_STRING'+ : apiProperty.definition.data_type+ ) as ValueType;// Handle each value type with proper type checkingswitch (valueType) {diff --git a/js/app/packages/property/src/tags/TagDot.tsx b/js/app/packages/property/src/tags/TagDot.tsxnew file mode 100644index 0000000000..c9b43122b4--- /dev/null+++ b/js/app/packages/property/src/tags/TagDot.tsx@@ -0,0 +1,11 @@+import { cn } from '@ui';+import { DEFAULT_TAG_COLOR } from './tagColors';++export function TagDot(props: { color?: string; class?: string }) {+ return (+ <span+ class={cn('size-2.5 shrink-0 rounded-full', props.class)}+ style={{ 'background-color': props.color ?? DEFAULT_TAG_COLOR }}+ />+ );+}diff --git a/js/app/packages/property/src/tags/TagPicker.tsx b/js/app/packages/property/src/tags/TagPicker.tsxnew file mode 100644index 0000000000..80b8e0f25d--- /dev/null+++ b/js/app/packages/property/src/tags/TagPicker.tsx@@ -0,0 +1,447 @@+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 { useAddPropertyOptionMutation } from '@queries/properties/options';+import {+ invalidateTags,+ useDeletePropertyOptionMutation,+ useEnsureTagSetMutation,+ 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, cn, Dialog, Layer, SingleSelectCheck } from '@ui';+import {+ createMemo,+ createSignal,+ For,+ type JSX,+ Match,+ Show,+ Switch,+} from 'solid-js';+import { TagDot } from './TagDot';+import { DEFAULT_TAG_COLOR, TAG_COLORS } from './tagColors';+import type { useDocTags } from './useDocTags';++type DocTags = ReturnType<typeof useDocTags>;++function optionLabel(option: PropertyOptionResponse): string {+ return option.value.type === 'string' ? option.value.value : '';+}++function nextDisplayOrder(options: PropertyOptionResponse[]): number {+ return (+ options.reduce((max, option) => Math.max(max, option.displayOrder), -1) + 1+ );+}++const SCOPE_LABEL: Record<TagScope, string> = {+ user: 'My labels',+ team: 'Team labels',+};++export function TagPicker(props: {+ docTags: DocTags;+ triggerClass?: string;+ triggerLabel: string;+ children: JSX.Element;+}) {+ const [open, setOpen] = createSignal(false);+ 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 addOption = useAddPropertyOptionMutation();+ const ensureTagSet = useEnsureTagSetMutation();++ const hasTeamSet = createMemo(() =>+ props.docTags.tagSets().some((set) => set.scope === 'team')+ );++ 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 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 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(),+ },+ },+ });+ invalidateTags();+ await props.docTags.applyTag(scope, created.id);+ setSearch('');+ };++ const closePicker = () => {+ setOpen(false);+ setSearch('');+ setEditingId(null);+ };++ return (+ <Popover+ open={open()}+ onOpenChange={setOpen}+ placement="bottom-start"+ gutter={4}+ >+ <Popover.Trigger+ type="button"+ class={props.triggerClass}+ aria-label={props.triggerLabel}+ >+ {props.children}+ </Popover.Trigger>+ <Popover.Portal>+ <Layer depth={3}>+ <Popover.Content+ class="z-modal w-64 rounded-xl bg-surface text-sm shadow-lg ring-1 ring-edge-muted"+ onCloseAutoFocus={(event) => 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 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)}+ />+ )}+ </For>+ </Show>+ </Show>+ )}+ </For>++ <Show when={search().trim() && !exactMatchExists()}>+ <CreateRow+ label={search().trim()}+ scope={createScope()}+ color={createColor()}+ hasTeamSet={hasTeamSet()}+ pending={addOption.isPending || ensureTagSet.isPending}+ onScope={setCreateScope}+ onColor={setCreateColor}+ onCreate={handleCreate}+ onCancel={() => setSearch('')}+ />+ </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>+ </Popover.Content>+ </Layer>+ </Popover.Portal>+ </Popover>+ );+}++function TagPickerRow(props: {+ scope: TagScope;+ option: PropertyOptionResponse;+ docTags: DocTags;+ editing: boolean;+ onEdit: () => void;+ onEditClose: () => 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">+ <div class="flex items-center gap-2">+ <TagDot color={draftColor()} />+ <input+ class="w-full bg-transparent caret-accent outline-none"+ value={draftLabel()}+ autofocus+ 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>+ );+}++function CreateRow(props: {+ label: string;+ scope: TagScope;+ color: string;+ hasTeamSet: boolean;+ pending: boolean;+ onScope: (scope: TagScope) => void;+ onColor: (color: string) => void;+ onCreate: () => void;+ onCancel: () => void;+}) {+ return (+ <div class="mt-1 flex flex-col gap-2 rounded-lg border border-edge-muted p-2">+ <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>+ </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;+ label: string;+ onCancel: () => void;+ onConfirm: () => void;+}) {+ return (+ <Dialog open={props.open} position="center" onOpenChange={props.onCancel}>+ <div class="rounded-xl bg-surface p-4 text-sm ring-1 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>+ </Dialog>+ );+}diff --git a/js/app/packages/property/src/tags/TagsRow.tsx b/js/app/packages/property/src/tags/TagsRow.tsxnew file mode 100644index 0000000000..d3f9a3c4a2--- /dev/null+++ b/js/app/packages/property/src/tags/TagsRow.tsx@@ -0,0 +1,54 @@+import PencilSimpleIcon from '@phosphor/pencil-simple.svg';+import type { EntityType } from '@service-properties/generated/schemas/entityType';+import { cn, Layer } from '@ui';+import { For, Show } from 'solid-js';+import { TagDot } from './TagDot';+import { TagPicker } from './TagPicker';+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'+);++export function TagsRow(props: {+ entityId: string;+ entityType: EntityType;+ canEdit: boolean;+}) {+ const docTags = useDocTags(props.entityId, props.entityType);++ 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>+ )}+ </For>+ <Show+ when={props.canEdit}+ fallback={+ <Show when={docTags.appliedTags().length === 0}>+ <span class="text-ink-extra-muted">No tags</span>+ </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>+ </Show>+ </div>+ );+}diff --git a/js/app/packages/property/src/tags/index.ts b/js/app/packages/property/src/tags/index.tsnew file mode 100644index 0000000000..0b8aa264a9--- /dev/null+++ b/js/app/packages/property/src/tags/index.ts@@ -0,0 +1,4 @@+export { TagPicker } from './TagPicker';+export { TagsRow } from './TagsRow';+export { DEFAULT_TAG_COLOR, TAG_COLORS } from './tagColors';+export { type ResolvedTag, useDocTags } from './useDocTags';diff --git a/js/app/packages/property/src/tags/tagColors.ts b/js/app/packages/property/src/tags/tagColors.tsnew file mode 100644index 0000000000..9d020bf949--- /dev/null+++ b/js/app/packages/property/src/tags/tagColors.ts@@ -0,0 +1,16 @@+export const TAG_COLORS = [+ '#E5484D', // Red+ '#E54D2E', // Tomato+ '#F76B15', // Orange+ '#FFB224', // Amber+ '#F5D90A', // Yellow+ '#46A758', // Green+ '#12A594', // Teal+ '#0091FF', // Blue+ '#3E63DD', // Indigo+ '#8E4EC6', // Purple+ '#E93D82', // Pink+ '#889096', // Gray+] as const;++export const DEFAULT_TAG_COLOR: string = TAG_COLORS[11];diff --git a/js/app/packages/property/src/tags/useDocTags.ts b/js/app/packages/property/src/tags/useDocTags.tsnew file mode 100644index 0000000000..41e1ce942f--- /dev/null+++ b/js/app/packages/property/src/tags/useDocTags.ts@@ -0,0 +1,165 @@+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';+import {+ useEnsureTagSetMutation,+ useTagsQuery,+} from '@queries/properties/tags';+import type { EntityType } from '@service-properties/generated/schemas/entityType';+import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';+import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';+import type { TagScope } from '@service-properties/generated/schemas/tagScope';+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { createMemo } from 'solid-js';+import { useEntityProperties } from '../hooks';+import type { PropertyDefinitionDomain } from '../types';++export type ResolvedTag = {+ optionId: string;+ scope: TagScope;+ label: string;+ color?: string;+};++function optionLabel(option: PropertyOptionResponse): string {+ return option.value.type === 'string' ? option.value.value : '';+}++function definitionDomain(+ definition: PropertyDefinitionDetailResponse+): PropertyDefinitionDomain {+ return {+ id: definition.id,+ displayName: definition.displayName,+ valueType: 'SELECT_STRING',+ isMultiSelect: true,+ isMetadata: definition.isMetadata,+ isSystem: definition.isSystem,+ owner: definition,+ createdAt: definition.createdAt ?? new Date().toISOString(),+ updatedAt: definition.updatedAt ?? new Date().toISOString(),+ };+}++export function useDocTags(entityId: string, entityType: EntityType) {+ const tagsQuery = useTagsQuery();+ const ensureTagSet = useEnsureTagSetMutation();+ const saveMutation = useBulkSaveEntityPropertiesMutation();+ const { properties } = useEntityProperties(entityId, entityType, false);++ const tagSets = (): TagSetResponse[] => tagsQuery.data ?? [];++ const definitionByScope = createMemo(() => {+ const map = new Map<TagScope, PropertyDefinitionDetailResponse>();+ for (const set of tagSets()) {+ if (set.definition) map.set(set.scope, set.definition);+ }+ return map;+ });++ const optionById = createMemo(() => {+ const map = new Map<string, ResolvedTag>();+ for (const set of tagSets()) {+ for (const option of set.options) {+ map.set(option.id, {+ optionId: option.id,+ scope: set.scope,+ label: optionLabel(option),+ color: option.color ?? undefined,+ });+ }+ }+ return map;+ });++ const appliedOptionIdsForDefinition = (definitionId: string): string[] => {+ const property = properties().find(+ (prop) => prop.propertyDefinitionId === definitionId+ );+ if (!property) return [];+ return property.valueType === 'SELECT_STRING' && property.value+ ? property.value+ : [];+ };++ const appliedTags = createMemo((): ResolvedTag[] => {+ const resolved: ResolvedTag[] = [];+ const lookup = optionById();+ for (const definition of definitionByScope().values()) {+ for (const optionId of appliedOptionIdsForDefinition(definition.id)) {+ const tag = lookup.get(optionId);+ if (tag) resolved.push(tag);+ }+ }+ return resolved;+ });++ const isApplied = (optionId: string): boolean =>+ appliedTags().some((tag) => tag.optionId === optionId);++ const resolveDefinition = async (+ scope: TagScope+ ): Promise<PropertyDefinitionDetailResponse> => {+ const existing = definitionByScope().get(scope);+ if (existing) return existing;+ const provisioned = await ensureTagSet.mutateAsync({ scope });+ if (!provisioned.definition) {+ throw new Error(`Tag set for scope "${scope}" has no definition`);+ }+ return provisioned.definition;+ };++ const saveScope = async (+ definition: PropertyDefinitionDetailResponse,+ optionIds: string[]+ ) => {+ await saveMutation.mutateAsync({+ properties: [+ {+ entityId,+ entityType,+ property: definitionDomain(definition),+ apiValues: {+ valueType: 'SELECT_STRING',+ values: optionIds.length > 0 ? optionIds : null,+ },+ },+ ],+ });+ };++ const applyTag = async (scope: TagScope, optionId: string) => {+ const definition = await resolveDefinition(scope);+ const current = appliedOptionIdsForDefinition(definition.id);+ if (current.includes(optionId)) return;+ await saveScope(definition, [...current, optionId]);+ };++ const removeTag = async (scope: TagScope, optionId: string) => {+ const definition = definitionByScope().get(scope);+ if (!definition) return;+ const current = appliedOptionIdsForDefinition(definition.id);+ if (!current.includes(optionId)) return;+ await saveScope(+ definition,+ current.filter((id) => id !== optionId)+ );+ };++ const toggleTag = async (scope: TagScope, optionId: string) => {+ if (isApplied(optionId)) {+ await removeTag(scope, optionId);+ } else {+ await applyTag(scope, optionId);+ }+ };++ return {+ tagsQuery,+ tagSets,+ appliedTags,+ optionById,+ isApplied,+ applyTag,+ removeTag,+ toggleTag,+ };+}diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.tsindex 2c4d4ed5ab..0a47c451a1 100644--- a/js/app/packages/queries/properties/entity.ts+++ b/js/app/packages/queries/properties/entity.ts@@ -50,7 +50,14 @@ export function useEntityPropertiesQuery(query: { include_metadata: includeMetadata },}));- return data.properties.map(entityPropertyFromApi);+ return data.properties.flatMap((property) => {+ try {+ return [entityPropertyFromApi(property)];+ } catch (error) {+ console.warn('Skipping property with unsupported type', error);+ return [];+ }+ });},staleTime: 0,};diff --git a/js/app/packages/queries/properties/keys.ts b/js/app/packages/queries/properties/keys.tsindex 8f14930d76..e72f40a512 100644--- a/js/app/packages/queries/properties/keys.ts+++ b/js/app/packages/queries/properties/keys.ts@@ -4,6 +4,7 @@ import type { PropertyScope } from '../../service-clients/service-properties/genexport const propertiesKeys = createQueryKeys('properties', {all: null,+ tags: null,entity: (params: {entityType: EntityType;entityId: string;diff --git a/js/app/packages/queries/properties/tags.ts b/js/app/packages/queries/properties/tags.tsnew file mode 100644index 0000000000..551c57aa09--- /dev/null+++ b/js/app/packages/queries/properties/tags.ts@@ -0,0 +1,136 @@+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 { EnsureTagSetRequest } from '../../service-clients/service-properties/generated/schemas/ensureTagSetRequest';+import type { PropertyOption } from '../../service-clients/service-properties/generated/schemas/propertyOption';+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';+import { type MutationCallbacks, withCallbacks } from '../utils';+import { propertiesKeys } from './keys';++/** The caller's tag sets: their personal set, plus their team's set when on a team. */+export function useTagsQuery() {+ return useQuery(() => ({+ queryKey: propertiesKeys.tags.queryKey,+ queryFn: async () =>+ await throwOnErr(async () => await propertiesServiceClient.listTags()),+ staleTime: 1000 * 60 * 5,+ }));+}++export function invalidateTags() {+ queryClient.invalidateQueries({ queryKey: propertiesKeys.tags.queryKey });+}++function invalidatePropertyOptions(propertyDefinitionId: string) {+ queryClient.invalidateQueries({+ queryKey: propertiesKeys.options({ propertyDefinitionId }).queryKey,+ });+}++type EnsureTagSetParams = { scope: EnsureTagSetRequest['scope'] };++/** Provision (get-or-create) the caller's tag definition for a scope. */+export function useEnsureTagSetMutation(+ callbacks?: MutationCallbacks<TagSetResponse, Error, EnsureTagSetParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: EnsureTagSetParams) =>+ await throwOnErr(+ async () =>+ await propertiesServiceClient.ensureTagSet({+ body: { scope: vars.scope },+ })+ ),+ ...withCallbacks<TagSetResponse, Error, EnsureTagSetParams>(+ {+ onError(error) {+ console.error('Failed to provision tag set', error);+ toast.failure('Failed to set up tags');+ },+ onSuccess: () => invalidateTags(),+ },+ callbacks+ ),+ }));+}++type UpdatePropertyOptionParams = {+ propertyDefinitionId: string;+ optionId: string;+ body: UpdatePropertyOptionRequest;+};++/** Rename / recolor a label in place. The option id is preserved so the change propagates. */+export function useUpdatePropertyOptionMutation(+ callbacks?: MutationCallbacks<+ PropertyOption,+ Error,+ UpdatePropertyOptionParams+ >+) {+ return useMutation(() => ({+ mutationFn: async (vars: UpdatePropertyOptionParams) =>+ await throwOnErr(+ async () =>+ await propertiesServiceClient.updatePropertyOption({+ definition_id: vars.propertyDefinitionId,+ option_id: vars.optionId,+ body: vars.body,+ })+ ),+ ...withCallbacks<PropertyOption, Error, UpdatePropertyOptionParams>(+ {+ onError(error) {+ console.error('Failed to update label', error);+ toast.failure('Failed to update label');+ },+ onSuccess: (_data, variables) => {+ invalidatePropertyOptions(variables.propertyDefinitionId);+ invalidateTags();+ },+ },+ callbacks+ ),+ }));+}++type DeletePropertyOptionParams = {+ propertyDefinitionId: string;+ optionId: string;+};++/** Delete a label. */+export function useDeletePropertyOptionMutation(+ callbacks?: MutationCallbacks<+ { success: boolean },+ Error,+ DeletePropertyOptionParams+ >+) {+ return useMutation(() => ({+ mutationFn: async (vars: DeletePropertyOptionParams) =>+ await throwOnErr(+ async () =>+ await propertiesServiceClient.deletePropertyOption({+ definition_id: vars.propertyDefinitionId,+ option_id: vars.optionId,+ })+ ),+ ...withCallbacks<{ success: boolean }, Error, DeletePropertyOptionParams>(+ {+ onError(error) {+ console.error('Failed to delete label', error);+ toast.failure('Failed to delete label');+ },+ onSuccess: (_data, variables) => {+ invalidatePropertyOptions(variables.propertyDefinitionId);+ invalidateTags();+ },+ },+ callbacks+ ),+ }));+}diff --git a/js/app/packages/service-clients/service-properties/client.ts b/js/app/packages/service-clients/service-properties/client.tsindex 33e3b0ceaf..93950bc193 100644--- a/js/app/packages/service-clients/service-properties/client.ts+++ b/js/app/packages/service-clients/service-properties/client.ts@@ -10,6 +10,7 @@ import type { Result } from 'neverthrow';import type { AddPropertyOptionRequest } from './generated/schemas/addPropertyOptionRequest';import type { BulkEntityPropertiesRequest } from './generated/schemas/bulkEntityPropertiesRequest';import type { CreatePropertyDefinitionRequest } from './generated/schemas/createPropertyDefinitionRequest';+import type { EnsureTagSetRequest } from './generated/schemas/ensureTagSetRequest';import type { EntityPropertiesResponse } from './generated/schemas/entityPropertiesResponse';import type { EntityType } from './generated/schemas/entityType';import type { GetBulkEntityProperties200 } from './generated/schemas/getBulkEntityProperties200';@@ -19,6 +20,8 @@ import type { PropertyDefinition } from './generated/schemas/propertyDefinition'import type { PropertyDefinitionResponse } from './generated/schemas/propertyDefinitionResponse';import type { PropertyOption } from './generated/schemas/propertyOption';import type { SetEntityPropertyRequest } from './generated/schemas/setEntityPropertyRequest';+import type { TagSetResponse } from './generated/schemas/tagSetResponse';+import type { UpdatePropertyOptionRequest } from './generated/schemas/updatePropertyOptionRequest';type PropertiesEntityType = EntityType;@@ -61,6 +64,14 @@ type SetPropertyStatusCompleteArgs = {type GetBulkEntityPropertiesArgs = {body: BulkEntityPropertiesRequest;};+type EnsureTagSetArgs = {+ body: EnsureTagSetRequest;+};+type UpdatePropertyOptionArgs = {+ definition_id: string;+ option_id: string;+ body: UpdatePropertyOptionRequest;+};const propertiesHost: string = SERVER_HOSTS['document-storage-service'];@@ -205,6 +216,29 @@ export const propertiesServiceClient = {});},++ listTags: async () => {+ return await propertiesFetch<TagSetResponse[]>(`/properties/tags`, {+ method: 'GET',+ });+ },++ ensureTagSet: async (args: EnsureTagSetArgs) => {+ return await propertiesFetch<TagSetResponse>(`/properties/tags`, {+ method: 'POST',+ body: JSON.stringify(args.body),+ });+ },++ updatePropertyOption: async (args: UpdatePropertyOptionArgs) => {+ return await propertiesFetch<PropertyOption>(+ `/properties/definitions/${args.definition_id}/options/${args.option_id}`,+ {+ method: 'PATCH',+ body: JSON.stringify(args.body),+ }+ );+ },};registerClient('properties', propertiesServiceClient);