Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(soup): dynamic task filters in the top bar for asignee and status (#1522)

teo6b8f425b6fd4
diff --git a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
index a458e82f6e..30aff59cc7 100644
--- a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
+++ b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
@@ -1,6 +1,8 @@
import { toast } from '@core/component/Toast/Toast';
import {
type EntityData,
+ isCurrentUserAssigned,
+ isTaskClosed,
isTaskEntity,
type TaskEntityWithProperties,
} from '@entity';
@@ -11,11 +13,7 @@ import {
import { useSetPropertyStatusCompleteMutation } from '@queries/properties/entity';
import type { PropertiesEntityType } from '@service-properties/client';
import type { SoupState } from '../create-soup-state';
-import {
- archiveEmail,
- isCurrentUserAssigned,
- isTaskClosed,
-} from '@app/component/next-soup/utils';
+import { archiveEmail } from '@app/component/next-soup/utils';
type MakeMarkDoneOptions = {
userId: () => string | undefined;
diff --git a/js/app/packages/app/component/next-soup/filters/signal-filters.ts b/js/app/packages/app/component/next-soup/filters/signal-filters.ts
index dccb0591b5..c51ec533b2 100644
--- a/js/app/packages/app/component/next-soup/filters/signal-filters.ts
+++ b/js/app/packages/app/component/next-soup/filters/signal-filters.ts
@@ -1,4 +1,6 @@
import {
+ isCurrentUserAssigned,
+ isTaskClosed,
isTaskEntity,
type TaskEntityWithProperties,
type EntityData,
@@ -9,10 +11,6 @@ import {
DEPRIORITY_LABEL_SIGNAL_TOGGLES,
PRIORITY_LABEL_SIGNAL_TOGGLES,
} from '@app/component/next-soup/filters/signal-configs';
-import {
- isCurrentUserAssigned,
- isTaskClosed,
-} from '@app/component/next-soup/utils';
/** Labels that indicate priority emails (signal) */
const PRIORITY_LABELS = createMemo(
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx
index 4e08a9d3d6..8ec1d45d2e 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx
@@ -43,6 +43,10 @@ import { IS_MAC } from '@core/constant/isMac';
import type { SystemSortOption } from '@app/component/next-soup/soup-view/sort-options';
import { Dynamic } from 'solid-js/web';
import { SortDropdown } from '@app/component/next-soup/soup-view/sort-dropdown';
+import {
+ TaskStatusDropdown,
+ TaskAssigneeDropdown,
+} from '@app/component/next-soup/soup-view/task-sub-filters';
/**
* Keyboard shortcuts for entity type filters.
@@ -128,6 +132,8 @@ const SoupFilters = () => {
const emailActive = useEmailLinksStatus();
const [sortDropdownOpen, setSortDropdownOpen] = createSignal(false);
+ const [statusDropdownOpen, setStatusDropdownOpen] = createSignal(false);
+ const [assigneeDropdownOpen, setAssigneeDropdownOpen] = createSignal(false);
const toggleFocus = (id: 'signal' | 'noise') => {
if (soup.filters.isActive(id)) {
@@ -294,6 +300,31 @@ const SoupFilters = () => {
hotkeyDisposers.forEach((d) => d.dispose());
});
+ const taskSubFilterHotkeyDisposers = [
+ registerHotkey({
+ hotkey: ['shift+s'],
+ scopeId: panel.splitHotkeyScope,
+ condition: () => soup.filters.isActive('task'),
+ description: 'Open status filter',
+ keyDownHandler: () => {
+ setStatusDropdownOpen((prev) => !prev);
+ return true;
+ },
+ }),
+ registerHotkey({
+ hotkey: ['shift+a'],
+ scopeId: panel.splitHotkeyScope,
+ condition: () => soup.filters.isActive('task'),
+ description: 'Open assignee filter',
+ keyDownHandler: () => {
+ setAssigneeDropdownOpen((prev) => !prev);
+ return true;
+ },
+ }),
+ ];
+
+ onCleanup(() => taskSubFilterHotkeyDisposers.forEach((d) => d.dispose()));
+
return (
<>
{/* Inbox toggle */}
@@ -366,6 +397,19 @@ const SoupFilters = () => {
}}
</For>
</div>
+ <Show when={soup.filters.isActive('task')}>
+ <FilterDivider />
+ <div class="flex items-center gap-1 shrink-0">
+ <TaskStatusDropdown
+ open={statusDropdownOpen}
+ onOpenChange={setStatusDropdownOpen}
+ />
+ <TaskAssigneeDropdown
+ open={assigneeDropdownOpen}
+ onOpenChange={setAssigneeDropdownOpen}
+ />
+ </div>
+ </Show>
<div class="mx-0.5 w-px h-5 bg-edge-muted/50 shrink-0" />
{/* Preview toggle */}
<Tooltip
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
index c1854f658d..1c56068d76 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
@@ -6,14 +6,21 @@ import {
import { createSearchState } from '@app/component/next-soup/soup-view/create-search-state';
import { sortEntitiesForSearch } from '@app/component/next-soup/soup-view/sort-options';
import { deduplicateEntities } from '@app/component/next-soup/utils';
+import {
+ isTaskEntity,
+ isWithNotification,
+ type EntityData,
+ type TaskEntityWithProperties,
+ type WithNotification,
+ type WithSearch,
+} from '@entity';
import { ENABLE_FEATURED_SEARCH_RESULTS } from '@core/constant/featureFlags';
-import type { EntityData, WithNotification, WithSearch } from '@entity';
-import { isWithNotification } from '@entity';
import { useNotificationsForEntity } from '@notifications';
import type { SoupItemsQueryFilters } from '@queries/soup/items';
import {
type Accessor,
createContext,
+ createEffect,
createMemo,
createRenderEffect,
createSignal,
@@ -23,6 +30,7 @@ import {
Suspense,
useContext,
} from 'solid-js';
+import { matchesTaskSubFilters } from './task-sub-filter-matcher';
type Row<T> = {
original: T;
@@ -58,6 +66,10 @@ interface SoupViewContextValues {
rows: Accessor<SoupRow[]>;
queryFilters: Accessor<SoupItemsQueryFilters>;
setQueryFilters: Setter<SoupItemsQueryFilters>;
+ statusFilter: Accessor<string | undefined>;
+ setStatusFilter: Setter<string | undefined>;
+ assigneeFilter: Accessor<string | undefined>;
+ setAssigneeFilter: Setter<string | undefined>;
}
export const SoupViewContext = createContext<SoupViewContextValues>();
@@ -89,6 +101,19 @@ export const SoupViewContextProvider: FlowComponent<
const [internalQueryFilters, setQueryFilters] =
createSignal<SoupItemsQueryFilters>({});
+ const [statusFilter, setStatusFilter] = createSignal<string | undefined>();
+ const [assigneeFilter, setAssigneeFilter] = createSignal<
+ string | undefined
+ >();
+
+ // Clear sub-filters when task filter is deactivated
+ createEffect(() => {
+ if (!soup.filters.isActive('task')) {
+ setStatusFilter(undefined);
+ setAssigneeFilter(undefined);
+ }
+ });
+
const queryFilters = createMemo(() => {
const base = internalQueryFilters();
@@ -192,11 +217,30 @@ export const SoupViewContextProvider: FlowComponent<
const next = [];
+ const currentStatusFilter = statusFilter();
+ const currentAssigneeFilter = assigneeFilter();
+
for (const entity of transformed) {
if (!filters.every((f) => f.predicate(entity))) {
continue;
}
+ // Apply task sub-filters
+ if (
+ (currentStatusFilter || currentAssigneeFilter) &&
+ isTaskEntity(entity)
+ ) {
+ const taskEntity = entity as unknown as TaskEntityWithProperties;
+ if (
+ !matchesTaskSubFilters(taskEntity, {
+ statusFilter: currentStatusFilter,
+ assigneeFilter: currentAssigneeFilter,
+ })
+ ) {
+ continue;
+ }
+ }
+
next.push(entity);
}
@@ -294,6 +338,10 @@ export const SoupViewContextProvider: FlowComponent<
featuredCount,
queryFilters,
setQueryFilters,
+ statusFilter,
+ setStatusFilter,
+ assigneeFilter,
+ setAssigneeFilter,
};
return (
diff --git a/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.test.ts b/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.test.ts
new file mode 100644
index 0000000000..827e4f4093
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@core/component/Properties/constants';
+import type { SoupProperty } from '@service-storage/generated/schemas';
+import type { TaskEntityWithProperties } from '@entity/types/entity';
+import { matchesTaskSubFilters } from './task-sub-filter-matcher';
+
+const createSoupProperty = (
+ definitionId: string,
+ value: unknown
+): SoupProperty => {
+ return {
+ definition: { id: definitionId },
+ value,
+ } as unknown as SoupProperty;
+};
+
+const createTask = (props?: {
+ properties?: SoupProperty[];
+}): TaskEntityWithProperties => {
+ return {
+ id: 'task-1',
+ name: 'Task',
+ ownerId: 'owner-1',
+ type: 'document',
+ fileType: 'md',
+ subType: { type: 'task' },
+ ...(props?.properties ? { properties: props.properties } : {}),
+ };
+};
+
+describe('matchesTaskSubFilters', () => {
+ it('keeps tasks without properties when sub-filters are active', () => {
+ const task = createTask();
+
+ expect(
+ matchesTaskSubFilters(task, {
+ statusFilter: PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,
+ })
+ ).toBe(true);
+
+ expect(
+ matchesTaskSubFilters(task, {
+ assigneeFilter: 'user-1',
+ })
+ ).toBe(true);
+ });
+
+ it('filters out tasks with non-matching status when properties exist', () => {
+ const task = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.STATUS, {
+ type: 'SelectOption',
+ value: [PROPERTY_OPTION_IDS.STATUS.IN_REVIEW],
+ }),
+ ],
+ });
+
+ expect(
+ matchesTaskSubFilters(task, {
+ statusFilter: PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,
+ })
+ ).toBe(false);
+ });
+
+ it('filters out tasks with non-matching assignee when properties exist', () => {
+ const task = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [{ entity_type: 'USER', entity_id: 'user-2' }],
+ }),
+ ],
+ });
+
+ expect(
+ matchesTaskSubFilters(task, {
+ assigneeFilter: 'user-1',
+ })
+ ).toBe(false);
+ });
+
+ it('keeps tasks when status and assignee both match', () => {
+ const task = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.STATUS, {
+ type: 'SelectOption',
+ value: [PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS],
+ }),
+ createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [{ entity_type: 'USER', entity_id: 'user-1' }],
+ }),
+ ],
+ });
+
+ expect(
+ matchesTaskSubFilters(task, {
+ statusFilter: PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,
+ assigneeFilter: 'user-1',
+ })
+ ).toBe(true);
+ });
+});
diff --git a/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.ts b/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.ts
new file mode 100644
index 0000000000..f31646a173
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.ts
@@ -0,0 +1,40 @@
+import {
+ getTaskAssigneeIds,
+ getTaskStatusOptionId,
+} from '@entity/utils/task-properties';
+import type { TaskEntityWithProperties } from '@entity/types/entity';
+
+type TaskSubFilters = {
+ statusFilter?: string;
+ assigneeFilter?: string;
+};
+
+export const matchesTaskSubFilters = (
+ taskEntity: TaskEntityWithProperties,
+ filters: TaskSubFilters
+): boolean => {
+ const { statusFilter, assigneeFilter } = filters;
+
+ if (!statusFilter && !assigneeFilter) {
+ return true;
+ }
+
+ // Search-service task entities can be returned without properties.
+ // Keep them until property data is available so valid search hits aren't dropped.
+ if (!taskEntity.properties) {
+ return true;
+ }
+
+ if (statusFilter && getTaskStatusOptionId(taskEntity) !== statusFilter) {
+ return false;
+ }
+
+ if (
+ assigneeFilter &&
+ !getTaskAssigneeIds(taskEntity).includes(assigneeFilter)
+ ) {
+ return false;
+ }
+
+ return true;
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/task-sub-filters.tsx b/js/app/packages/app/component/next-soup/soup-view/task-sub-filters.tsx
new file mode 100644
index 0000000000..8553566f82
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/task-sub-filters.tsx
@@ -0,0 +1,194 @@
+import {
+ type Accessor,
+ type Component,
+ type ParentProps,
+ Show,
+} from 'solid-js';
+import { Popover } from '@kobalte/core/popover';
+import { TASK_STATUS_OPTIONS } from '@entity';
+import { PropertyValueIcon } from '@core/component/Properties/component/propertyValue/PropertyValueIcon';
+import { PropertyOptionSelector } from '@core/component/Properties/component/modal/shared/PropertyOptionSelector';
+import { PropertyEntitySelector } from '@core/component/Properties/component/modal/shared/PropertyEntitySelector';
+import type { SelectableOption } from '@core/component/Properties/component/modal/shared/types';
+import { UserIcon } from '@core/component/UserIcon';
+import { useContacts } from '@queries/contacts/contacts';
+import { useUserId } from '@core/context/user';
+import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';
+import UserCircleIcon from '@icon/regular/user-circle.svg';
+import CaretDownIcon from '@icon/regular/caret-down.svg';
+import XIcon from '@icon/regular/x.svg?component-solid';
+import CircleDashedIcon from '@icon/regular/circle-dashed.svg';
+
+type DropdownProps = {
+ open: () => boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+const statusOptions: SelectableOption[] = TASK_STATUS_OPTIONS.map((o) => ({
+ id: o.value,
+ label: o.label,
+}));
+
+function FilterTrigger<T>(
+ props: ParentProps<{
+ filter: Accessor<T>;
+ }>
+) {
+ return (
+ <Popover.Trigger
+ as="button"
+ type="button"
+ class="flex items-center gap-1 h-[22px] touch:mobile-width:h-9 px-2.5 shrink-0 rounded-full active:bg-accent/20 text-xs"
+ classList={{
+ 'bg-accent/20 text-accent': !!props.filter(),
+ 'text-ink-muted hover:text-accent hover:bg-accent/20': !props.filter(),
+ }}
+ >
+ {props.children}
+ </Popover.Trigger>
+ );
+}
+
+export const TaskStatusDropdown: Component<DropdownProps> = (props) => {
+ const { statusFilter, setStatusFilter } = useSoupView();
+ const open = () => props.open();
+ const setOpen = (v: boolean) => props.onOpenChange(v);
+
+ const activeLabel = () => {
+ if (!statusFilter()) return 'Status';
+ return (
+ TASK_STATUS_OPTIONS.find((o) => o.value === statusFilter())?.label ??
+ 'Status'
+ );
+ };
+
+ const selectOption = (id: string) => {
+ setStatusFilter(statusFilter() === id ? undefined : id);
+ setOpen(false);
+ };
+
+ return (
+ <Popover
+ open={open()}
+ onOpenChange={(isOpen) => {
+ setOpen(isOpen);
+ }}
+ placement="bottom-start"
+ gutter={4}
+ >
+ <FilterTrigger filter={statusFilter}>
+ <Show
+ when={statusFilter()}
+ fallback={<CircleDashedIcon class="size-3.5" />}
+ >
+ <PropertyValueIcon optionId={statusFilter()!} class="size-3.5" />
+ </Show>
+ <span class="leading-none">{activeLabel()}</span>
+ <Show
+ when={statusFilter()}
+ fallback={<CaretDownIcon class="size-3 opacity-60" />}
+ >
+ <span
+ class="ml-0.5 hover:text-accent/60"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ setStatusFilter(undefined);
+ }}
+ >
+ <XIcon class="size-3" />
+ </span>
+ </Show>
+ </FilterTrigger>
+ <Popover.Portal>
+ <Popover.Content class="z-50 bg-panel border border-edge-muted shadow-lg w-[300px]">
+ <PropertyOptionSelector
+ config={{ isMultiSelect: false, placeholder: 'Filter status...' }}
+ options={statusOptions}
+ isLoading={false}
+ error={null}
+ selectedOptions={() =>
+ statusFilter() ? new Set([statusFilter()!]) : new Set()
+ }
+ onToggleOption={(id) => selectOption(id)}
+ onClose={() => setOpen(false)}
+ />
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ );
+};
+
+export const TaskAssigneeDropdown: Component<DropdownProps> = (props) => {
+ const { assigneeFilter, setAssigneeFilter } = useSoupView();
+ const open = () => props.open();
+ const setOpen = (v: boolean) => props.onOpenChange(v);
+ const contacts = useContacts();
+ const userId = useUserId();
+
+ const activeAssigneeLabel = () => {
+ if (!assigneeFilter()) return 'Assignee';
+ const contact = contacts().find((c) => c.id === assigneeFilter());
+ if (contact && contact.id === userId())
+ return contact.name ? `${contact.name} (me)` : 'Me';
+ return contact?.name || assigneeFilter()!;
+ };
+
+ return (
+ <Popover
+ open={open()}
+ onOpenChange={(isOpen) => {
+ setOpen(isOpen);
+ }}
+ placement="bottom-start"
+ gutter={4}
+ >
+ <FilterTrigger filter={assigneeFilter}>
+ <Show
+ when={assigneeFilter()}
+ keyed
+ fallback={<UserCircleIcon class="size-3.5" />}
+ >
+ {(id) => (
+ <UserIcon id={id} size="xs" suppressClick showTooltip={false} />
+ )}
+ </Show>
+ <span class="leading-none">{activeAssigneeLabel()}</span>
+ <Show
+ when={assigneeFilter()}
+ fallback={<CaretDownIcon class="size-3 opacity-60" />}
+ >
+ <span
+ class="ml-0.5 hover:text-accent/60"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ setAssigneeFilter(undefined);
+ }}
+ >
+ <XIcon class="size-3" />
+ </span>
+ </Show>
+ </FilterTrigger>
+ <Popover.Portal>
+ <Popover.Content class="z-50 bg-panel border border-edge-muted shadow-lg w-[300px]">
+ <PropertyEntitySelector
+ config={{
+ isMultiSelect: false,
+ placeholder: 'Filter assignee...',
+ specificEntityType: 'USER',
+ }}
+ selectedOptions={() =>
+ assigneeFilter() ? new Set([assigneeFilter()!]) : new Set()
+ }
+ setSelectedOptions={(ids) => {
+ const newId = [...ids][0];
+ setAssigneeFilter(newId === assigneeFilter() ? undefined : newId);
+ }}
+ onClose={() => setOpen(false)}
+ />
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index 79ecb1376d..f4bd7bdbdb 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -12,16 +12,11 @@ import {
type EntityData,
isSearchEntity,
type SearchLocation,
- type TaskEntityWithProperties,
type WithSearch,
} from '@entity';
import { queryKeys } from '@macro-entity';
import { queryClient } from '@queries/client';
import { emailClient } from '@service-email/client';
-import {
- PROPERTY_OPTION_IDS,
- SYSTEM_PROPERTY_IDS,
-} from '@core/component/Properties/constants';
import {
removeSoupEntities,
getSoupEntityById,
@@ -430,82 +425,3 @@ export async function archiveEmail(
]);
}
}
-
-/**
- * extracts assignee user ids from task properties.
- */
-export const getTaskAssigneeIds = (
- entity: TaskEntityWithProperties
-): string[] => {
- const properties = entity.properties;
- if (!properties) return [];
- const assigneesProperty = properties.find(
- (p) => p.definition.id === SYSTEM_PROPERTY_IDS.ASSIGNEES
- );
- if (!assigneesProperty?.value) return [];
-
- const value = assigneesProperty.value;
- if (value.type === 'EntityReference' && Array.isArray(value.value)) {
- return value.value
- .filter((ref) => ref.entity_type === 'USER')
- .map((ref) => ref.entity_id);
- }
-
- return [];
-};
-
-/**
- * gets the status option id from task properties.
- */
-export const getTaskStatusOptionId = (
- entity: TaskEntityWithProperties
-): string | undefined => {
- const properties = entity.properties;
- if (!properties) return undefined;
-
- const statusProperty = properties.find(
- (p) => p.definition.id === SYSTEM_PROPERTY_IDS.STATUS
- );
- if (!statusProperty?.value) return undefined;
-
- const value = statusProperty.value;
- if (
- value.type === 'SelectOption' &&
- 'value' in value &&
- Array.isArray(value.value)
- ) {
- return value.value[0];
- }
-
- return undefined;
-};
-
-/**
- * checks if a task is in a "closed" state (completed or canceled).
- */
-export const isTaskClosed = (entity: TaskEntityWithProperties): boolean => {
- if (entity.subType?.is_completed === true) {
- return true;
- }
- const statusOptionId = getTaskStatusOptionId(entity);
- if (
- statusOptionId === PROPERTY_OPTION_IDS.STATUS.COMPLETED ||
- statusOptionId === PROPERTY_OPTION_IDS.STATUS.CANCELED
- ) {
- return true;
- }
- return false;
-};
-
-/**
- * checks if the current user is assigned to the task.
- */
-export const isCurrentUserAssigned = (
- entity: TaskEntityWithProperties,
- currentUserId: string | undefined
-): boolean => {
- if (!currentUserId) return false;
- const assigneeIds = getTaskAssigneeIds(entity);
- if (assigneeIds.length === 0) return true;
- return assigneeIds.includes(currentUserId);
-};
diff --git a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
index ef9235a8f6..fae596dfe4 100644
--- a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
@@ -1,3 +1,4 @@
+import { useMaybeBlockId } from '@core/block';
import { floatWithElement } from '@core/component/LexicalMarkdown/directive/floatWithElement';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
@@ -6,6 +7,7 @@ import { mergeRefs } from '@solid-primitives/refs';
import { createSignal, onMount, Show } from 'solid-js';
import { usePropertiesContext } from '../../context/PropertiesContext';
import { usePropertyEditor } from '../../hooks/usePropertyEditor';
+import { formatOptionValue } from '../../utils';
import type { PropertyApiValues, PropertyEditorProps } from '../../types';
false && floatWithElement;
@@ -46,7 +48,8 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
const isLoading = () =>
propertyOptionsQuery.isLoading || addPropertyOptionMutation.isPending;
- const { saveHandler } = usePropertiesContext();
+ const { saveHandler, entityType: currentEntityType } = usePropertiesContext();
+ const blockId = useMaybeBlockId();
let modalRef!: HTMLDivElement;
@@ -236,7 +239,15 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
}
>
<PropertyEntitySelector
- property={props.property}
+ config={{
+ isMultiSelect: props.property.isMultiSelect,
+ placeholder: `${props.property.isMultiSelect ? 'Add' : 'Change'} ${props.property.displayName.toLowerCase()}...`,
+ specificEntityType: props.property.specificEntityType,
+ selfFilter: {
+ entityType: currentEntityType,
+ blockId,
+ },
+ }}
selectedOptions={() => {
const refs = selectedEntityRefs();
return entityReferencesToIdSet(refs);
@@ -250,15 +261,35 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
);
setSelectedEntityRefs(updatedRefs);
}}
- setHasChanges={() => {}} // Not needed with new hook
onClose={handleClose}
/>
</Show>
}
>
<PropertyOptionSelector
- property={props.property}
- options={propertyOptions()}
+ config={{
+ isMultiSelect: props.property.isMultiSelect,
+ placeholder: `${props.property.isMultiSelect ? 'Add' : 'Change'} ${props.property.displayName.toLowerCase()}...`,
+ inputType:
+ props.property.valueType === 'SELECT_NUMBER'
+ ? 'number'
+ : 'text',
+ canAddOption: props.property.isSystemProperty
+ ? undefined
+ : (query) => {
+ if (props.property.valueType === 'SELECT_STRING')
+ return true;
+ if (props.property.valueType === 'SELECT_NUMBER') {
+ const n = parseFloat(query);
+ return !isNaN(n) && Number.isFinite(n);
+ }
+ return false;
+ },
+ }}
+ options={propertyOptions().map((opt) => ({
+ id: opt.id,
+ label: formatOptionValue(opt),
+ }))}
isLoading={false}
error={null}
selectedOptions={selectedOptions}
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
index e6dd0ff620..421743ecd5 100644
--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
@@ -1,4 +1,3 @@
-import { useMaybeBlockId } from '@core/block';
import { useChannelsContext } from '@core/context/channels';
import { EntityIcon, getEntityIconType } from '@core/component/EntityIcon';
import { UserIcon } from '@core/component/UserIcon';
@@ -30,8 +29,6 @@ import {
onMount,
Show,
} from 'solid-js';
-import { usePropertiesContext } from '../../../context/PropertiesContext';
-import type { Property } from '../../../types';
import { useSearchInputFocus } from '../../../utils';
import {
type CombinedEntity,
@@ -46,15 +43,15 @@ import {
} from './entityUtils';
import { OptionCheckBox } from './OptionCheckBox';
import { useKeyPressed } from '@core/util/useKeyPressed';
+import type { EntitySelectorConfig } from './types';
type EntityInputProps = {
- property: Property;
+ config: EntitySelectorConfig;
selectedOptions: () => Set<string>;
setSelectedOptions: (
options: Set<string>,
entityInfo?: { id: string; entity_type: string }[]
) => void;
- setHasChanges: (hasChanges: boolean) => void;
onClose?: () => void;
};
@@ -135,9 +132,9 @@ export function PropertyEntitySelector(props: EntityInputProps) {
let searchInputRef!: HTMLInputElement;
- // Get current entity context for self-filtering
- const blockId = useMaybeBlockId();
- const { entityType: currentEntityType } = usePropertiesContext();
+ // Get self-filter context from config
+ const selfFilterEntityType = () => props.config.selfFilter?.entityType;
+ const selfFilterBlockId = () => props.config.selfFilter?.blockId;
const historyQuery = useHistoryQuery();
const contacts = useContacts();
@@ -175,8 +172,8 @@ export function PropertyEntitySelector(props: EntityInputProps) {
// Fetch emails for browsing (only when THREAD type)
// Email queries for THREAD type or generic ENTITY (no specific type)
const needsEmailSearch = () =>
- props.property.specificEntityType === 'THREAD' ||
- !props.property.specificEntityType;
+ props.config.specificEntityType === 'THREAD' ||
+ !props.config.specificEntityType;
const emailsQuery = createEmailsInfiniteQuery(() => ({ view: 'all' }), {
disabled: () => !needsEmailSearch(),
@@ -231,7 +228,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
// Local entities (always available, used for instant results)
const entities = createMemo(() => {
- const { specificEntityType } = props.property;
+ const specificEntityType = props.config.specificEntityType;
if (!specificEntityType) {
return [
@@ -312,6 +309,8 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const MAX_SEARCH_RESULTS = 20;
// Filter out the current entity when selecting same entity type (e.g., parent task on a task)
+ const blockId = selfFilterBlockId();
+ const currentEntityType = selfFilterEntityType();
const excludeFilter = blockId
? (e: CombinedEntity) =>
!(getEntityType(e) === currentEntityType && e.id === blockId)
@@ -367,24 +366,15 @@ export function PropertyEntitySelector(props: EntityInputProps) {
}
}
- // Add missing selected entities from property value (handles pagination)
- if (
- props.property.valueType === 'ENTITY' &&
- props.property.value != null
- ) {
- const allAvailableEntities = entities();
-
- for (const ref of props.property.value) {
- if (
- selectedIds.has(ref.entity_id) &&
- !entityIdsInResults.has(ref.entity_id)
- ) {
- const actualEntity = allAvailableEntities.find(
- (e) => e.id === ref.entity_id
- );
- if (actualEntity) {
- selected.push(actualEntity);
- }
+ // Add missing selected entities that aren't in the visible results (handles pagination)
+ const allAvailableEntities = entities();
+ for (const selectedId of selectedIds) {
+ if (!entityIdsInResults.has(selectedId)) {
+ const actualEntity = allAvailableEntities.find(
+ (e) => e.id === selectedId
+ );
+ if (actualEntity) {
+ selected.push(actualEntity);
}
}
}
@@ -397,7 +387,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const newSelected = new Set(props.selectedOptions());
const isCurrentlySelected = newSelected.has(entity.id);
- if (props.property.isMultiSelect) {
+ if (props.config.isMultiSelect) {
if (isCurrentlySelected) {
newSelected.delete(entity.id);
} else {
@@ -414,11 +404,10 @@ export function PropertyEntitySelector(props: EntityInputProps) {
entity_type: getEntityType(entity),
},
]);
- props.setHasChanges(true);
- if (!props.property.isMultiSelect && props.onClose) {
+ if (!props.config.isMultiSelect && props.onClose) {
props.onClose();
- } else if (props.property.isMultiSelect && searchInputRef) {
+ } else if (props.config.isMultiSelect && searchInputRef) {
// Keep input focused when multiselect is enabled
setTimeout(() => searchInputRef.focus(), 0);
}
@@ -500,7 +489,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
}
}
}}
- placeholder={`${props.property.isMultiSelect ? 'Add' : 'Change'} ${props.property.displayName.toLowerCase()}...`}
+ placeholder={props.config.placeholder}
/>
</div>
</div>
@@ -538,7 +527,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
<div class="flex-shrink-0">
<OptionCheckBox
checked={isSelected()}
- multiselect={props.property.isMultiSelect}
+ multiselect={props.config.isMultiSelect}
/>
</div>
</div>
@@ -552,8 +541,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
<Show when={sortedEntities().length === 0}>
<div class="text-center py-4 text-ink-muted text-sm">
<Show when={!isLoadingEntities()} fallback={<span>Loading...</span>}>
- No {getEntityTypePluralLabel(props.property.specificEntityType)}{' '}
- found
+ No {getEntityTypePluralLabel(props.config.specificEntityType)} found
</Show>
</div>
</Show>
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx
index 866c09fd75..8bd2912619 100644
--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx
@@ -1,9 +1,10 @@
import { Hotkey } from '@core/component/Hotkey';
-import SearchIcon from '@icon/regular/magnifying-glass.svg';
+import { useKeyPressed } from '@core/util/useKeyPressed';
import PlusIcon from '@icon/regular/plus.svg';
import LoadingSpinner from '@icon/regular/spinner.svg';
-import type * as schemas from '@service-properties/generated/zod';
+import SearchIcon from '@icon/regular/magnifying-glass.svg';
import {
+ type Accessor,
createEffect,
createMemo,
createSignal,
@@ -12,19 +13,138 @@ import {
onMount,
Show,
} from 'solid-js';
-import type { z } from 'zod';
-import type { Property } from '../../../types';
-import { formatOptionValue, useSearchInputFocus } from '../../../utils';
+import type { JSX, ParentComponent } from 'solid-js';
+import { useSearchInputFocus } from '../../../utils';
import { ERROR_MESSAGES } from '../../../utils/errorHandling';
import { PropertyValueIcon } from '../../propertyValue';
import { OptionCheckBox } from './OptionCheckBox';
-import { useKeyPressed } from '@core/util/useKeyPressed';
+import type { SelectableOption, OptionSelectorConfig } from './types';
+
+type UseDropdownSearchOptions = {
+ itemCount: Accessor<number>;
+ onSelect: (index: number) => void;
+ onClose: () => void;
+};
+
+const useDropdownSearch = (options: UseDropdownSearchOptions) => {
+ const [searchQuery, setSearchQuery] = createSignal('');
+ const [selectedIndex, setSelectedIndex] = createSignal(0);
+ const keyboardMode = useKeyPressed(100);
+
+ createEffect(() => {
+ const count = options.itemCount();
+ if (count === 0) {
+ setSelectedIndex(0);
+ } else {
+ setSelectedIndex((prev) => Math.min(prev, count - 1));
+ }
+ });
+
+ const shouldShowHotkeys = () =>
+ !searchQuery().trim() && options.itemCount() <= 9;
+
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ options.onClose();
+ return;
+ }
+
+ const count = options.itemCount();
+ if (count === 0) return;
+
+ if (shouldShowHotkeys() && /^[1-9]$/.test(e.key)) {
+ e.preventDefault();
+ const idx = parseInt(e.key) - 1;
+ if (idx < count) options.onSelect(idx);
+ return;
+ }
-type PropertyOption = z.infer<typeof schemas.getPropertyOptionsResponseItem>;
+ if (e.key === 'ArrowDown' || (e.ctrlKey && e.key === 'j')) {
+ e.preventDefault();
+ setSelectedIndex((prev) => (prev + 1) % count);
+ } else if (e.key === 'ArrowUp' || (e.ctrlKey && e.key === 'k')) {
+ e.preventDefault();
+ setSelectedIndex((prev) => (prev - 1 + count) % count);
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ options.onSelect(selectedIndex());
+ }
+ };
+
+ return {
+ searchQuery,
+ setSearchQuery,
+ selectedIndex,
+ setSelectedIndex,
+ keyboardMode,
+ shouldShowHotkeys,
+ handleKeyDown,
+ };
+};
+
+type DropdownSearchInputProps = {
+ value: string;
+ placeholder: string;
+ onInput: (value: string) => void;
+ inputType?: string;
+ inputRef?: (element: HTMLInputElement) => void;
+};
+
+const DropdownSearchInput = (props: DropdownSearchInputProps) => {
+ return (
+ <div class="flex w-full items-center py-1 gap-2 px-2 border-b border-edge-muted">
+ <SearchIcon class="h-4 w-4 text-ink-muted" />
+ <input
+ class="w-full caret-accent"
+ ref={props.inputRef}
+ type={props.inputType ?? 'text'}
+ value={props.value}
+ onInput={(event) => props.onInput(event.currentTarget.value)}
+ placeholder={props.placeholder}
+ />
+ </div>
+ );
+};
+
+type DropdownSelectableRowProps = {
+ isSelected: boolean;
+ showHotkey?: boolean;
+ hotkeyShortcut?: string;
+ rightContent?: JSX.Element;
+ onClick?: JSX.EventHandlerUnion<HTMLDivElement, MouseEvent>;
+ onMouseEnter?: JSX.EventHandlerUnion<HTMLDivElement, MouseEvent>;
+};
+
+const DropdownSelectableRow: ParentComponent<DropdownSelectableRowProps> = (
+ props
+) => {
+ return (
+ <div
+ class="flex flex-row w-full justify-between items-center gap-2 py-1.5 px-2"
+ classList={{
+ 'bg-hover': props.isSelected,
+ }}
+ onClick={props.onClick}
+ onMouseEnter={props.onMouseEnter}
+ >
+ <div class="flex items-center gap-2 flex-1 min-w-0">{props.children}</div>
+ <div class="flex items-center gap-2 flex-shrink-0">
+ <Show when={props.showHotkey && props.hotkeyShortcut}>
+ <div class="text-[0.625rem] px-1.5 py-0.5 border border-edge-muted text-ink-muted font-mono rounded-xs">
+ <Hotkey shortcut={props.hotkeyShortcut!} />
+ </div>
+ </Show>
+ {props.rightContent}
+ </div>
+ </div>
+ );
+};
type SelectOptionsProps = {
- property: Property;
- options: PropertyOption[];
+ config: OptionSelectorConfig;
+ options: SelectableOption[];
isLoading: boolean;
error: string | null;
selectedOptions: () => Set<string>;
@@ -34,53 +154,20 @@ type SelectOptionsProps = {
};
export const PropertyOptionSelector = (props: SelectOptionsProps) => {
- const [searchQuery, setSearchQuery] = createSignal('');
const [isAddingOption, setIsAddingOption] = createSignal(false);
- const [selectedIndex, setSelectedIndex] = createSignal(0);
-
- const keyboardMode = useKeyPressed(100);
let searchInputRef!: HTMLInputElement;
const isOptionSelected = (value: string) =>
props.selectedOptions().has(value);
- const hasExactMatch = createMemo(() => {
- const query = searchQuery().trim();
- if (!query) return false;
-
- return props.options.some((option) => {
- const displayValue = formatOptionValue(option);
- return displayValue === query;
- });
- });
-
- const isValidNewOption = createMemo(() => {
- const query = searchQuery().trim();
-
- if (!query) return false;
-
- if (hasExactMatch()) return false;
-
- if (props.property.valueType === 'SELECT_STRING') {
- return true;
- }
-
- if (props.property.valueType === 'SELECT_NUMBER') {
- const num = parseFloat(query);
- return !isNaN(num) && Number.isFinite(num);
- }
-
- return false;
- });
-
const handleAddOption = async () => {
if (!props.onAddOption || !isValidNewOption()) return;
setIsAddingOption(true);
try {
- await props.onAddOption(searchQuery().trim());
- setSearchQuery('');
+ await props.onAddOption(dropdown.searchQuery().trim());
+ dropdown.setSearchQuery('');
} catch (error) {
console.error(
'PropertyOptionsList.handleAddOption:',
@@ -92,27 +179,62 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
}
};
+ const handleSelectableItem = (idx: number) => {
+ const item = selectableItems()[idx];
+ if (item?.type === 'add') {
+ handleAddOption();
+ } else if (item?.type === 'option' && item.option) {
+ props.onToggleOption(item.option.id);
+ if (!props.config.isMultiSelect && props.onClose) {
+ props.onClose();
+ }
+ }
+ };
+
+ const dropdown = useDropdownSearch({
+ itemCount: () => selectableItems().length,
+ onSelect: handleSelectableItem,
+ onClose: () => {
+ if (props.onClose) props.onClose();
+ },
+ });
+
+ const hasExactMatch = createMemo(() => {
+ const query = dropdown.searchQuery().trim();
+ if (!query) return false;
+
+ return props.options.some((option) => option.label === query);
+ });
+
+ const isValidNewOption = createMemo(() => {
+ const query = dropdown.searchQuery().trim();
+
+ if (!query) return false;
+
+ if (hasExactMatch()) return false;
+
+ return props.config.canAddOption?.(query) ?? false;
+ });
+
// Filter options based on search query and sort selected first, then alphabetically
const filteredOptions = createMemo(() => {
- const query = searchQuery().toLowerCase().trim();
+ const query = dropdown.searchQuery().toLowerCase().trim();
const selectedIds = props.selectedOptions();
const availableOptions = !query
? props.options
: props.options.filter((option) => {
- const displayValue = formatOptionValue(option).toLowerCase();
- return displayValue.includes(query);
+ return option.label.toLowerCase().includes(query);
});
// Only include missing selected options when there's no search query
let allOptions = availableOptions;
if (!query) {
const availableOptionIds = new Set(availableOptions.map((opt) => opt.id));
- const missingSelectedOptions: PropertyOption[] = [];
+ const missingSelectedOptions: SelectableOption[] = [];
for (const selectedId of selectedIds) {
if (!availableOptionIds.has(selectedId)) {
- // Find the actual option from props.options to get its value
const actualOption = props.options.find(
(opt) => opt.id === selectedId
);
@@ -131,7 +253,7 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
// Get selectable items (filtered options + add option if available)
const selectableItems = createMemo(() => {
const options = filteredOptions();
- const items: Array<{ type: 'option' | 'add'; option?: PropertyOption }> =
+ const items: Array<{ type: 'option' | 'add'; option?: SelectableOption }> =
[];
options.forEach((option) => {
@@ -145,73 +267,12 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
return items;
});
- // Reset selected index when filteredOptions change
- createEffect(() => {
- const items = selectableItems();
- if (items.length === 0) {
- setSelectedIndex(0);
- } else {
- setSelectedIndex(Math.min(selectedIndex(), items.length - 1));
- }
- });
-
- const shouldShowHotkeys = createMemo(() => {
- return !searchQuery().trim() && selectableItems().length <= 9;
- });
-
- const handleKeyDown = (e: KeyboardEvent) => {
- const items = selectableItems();
- if (items.length === 0) return;
-
- // Handle number keys (1-9) when no search term and 9 or fewer options
- if (shouldShowHotkeys() && /^[1-9]$/.test(e.key)) {
- e.preventDefault();
- const index = parseInt(e.key) - 1;
- if (index < items.length) {
- const selectedItem = items[index];
- if (selectedItem?.type === 'add') {
- handleAddOption();
- } else if (selectedItem?.type === 'option' && selectedItem.option) {
- props.onToggleOption(selectedItem.option.id);
-
- // If not multi-select, close the modal after selection
- if (!props.property.isMultiSelect && props.onClose) {
- props.onClose();
- }
- }
- }
- return;
- }
-
- if (e.key === 'ArrowDown' || (e.ctrlKey && e.key === 'j')) {
- e.preventDefault();
- setSelectedIndex((prev) => (prev + 1) % items.length);
- } else if (e.key === 'ArrowUp' || (e.ctrlKey && e.key === 'k')) {
- e.preventDefault();
- setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
- } else if (e.key === 'Enter') {
- e.preventDefault();
- const selectedItem = items[selectedIndex()];
-
- if (selectedItem?.type === 'add') {
- handleAddOption();
- } else if (selectedItem?.type === 'option' && selectedItem.option) {
- props.onToggleOption(selectedItem.option.id);
-
- // If not multi-select, close the modal after selection
- if (!props.property.isMultiSelect && props.onClose) {
- props.onClose();
- }
- }
- }
- };
-
onMount(() => {
- document.addEventListener('keydown', handleKeyDown);
+ document.addEventListener('keydown', dropdown.handleKeyDown);
});
onCleanup(() => {
- document.removeEventListener('keydown', handleKeyDown);
+ document.removeEventListener('keydown', dropdown.handleKeyDown);
});
useSearchInputFocus(
@@ -219,10 +280,7 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
() => !props.isLoading && !props.error
);
- const AddOptionButton = (props: {
- isSelected: boolean;
- hotkeyNumber?: number;
- }) => (
+ const AddOptionButton = (props: { isSelected: boolean }) => (
<div
onClick={handleAddOption}
class={`flex flex-row w-full justify-between items-center gap-2 py-1.5 px-2 ${
@@ -242,7 +300,7 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
<PlusIcon class="size-3" />
</Show>
</div>
- <p class="text-sm font-medium">Add "{searchQuery().trim()}"</p>
+ <p class="text-sm font-medium">Add "{dropdown.searchQuery().trim()}"</p>
</div>
</div>
);
@@ -262,30 +320,15 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
<Show when={!props.error}>
<div>
<div class="relative">
- <div class="flex w-full items-center py-1 gap-2 px-2 border-b border-edge-muted">
- <SearchIcon class="h-4 w-4 text-ink-muted" />
- <input
- class="w-full caret-accent"
- ref={searchInputRef}
- type={
- props.property.valueType === 'SELECT_NUMBER'
- ? 'number'
- : 'text'
- }
- value={searchQuery()}
- onInput={(e) => setSearchQuery(e.currentTarget.value)}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- e.preventDefault();
- e.stopPropagation();
- if (props.onClose) {
- props.onClose();
- }
- }
- }}
- placeholder={`${props.property.isMultiSelect ? 'Add' : 'Change'} ${props.property.displayName.toLowerCase()}...`}
- />
- </div>
+ <DropdownSearchInput
+ value={dropdown.searchQuery()}
+ inputRef={(element) => {
+ searchInputRef = element;
+ }}
+ inputType={props.config.inputType ?? 'text'}
+ onInput={dropdown.setSearchQuery}
+ placeholder={props.config.placeholder}
+ />
</div>
<Show
@@ -302,7 +345,9 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
>
<div class="p-1">
<AddOptionButton
- isSelected={selectedIndex() === filteredOptions().length}
+ isSelected={
+ dropdown.selectedIndex() === filteredOptions().length
+ }
/>
</div>
</Show>
@@ -324,16 +369,13 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
<Show
when={item.type === 'add'}
fallback={
- <div
- class={`flex flex-row w-full justify-between items-center gap-2 py-1.5 px-2 ${
- index() === selectedIndex() ? 'bg-hover' : ''
- }`}
+ <DropdownSelectableRow
+ isSelected={index() === dropdown.selectedIndex()}
onClick={() => {
if (item.option) {
props.onToggleOption(item.option.id);
- // If not multi-select, close the modal after selection
if (
- !props.property.isMultiSelect &&
+ !props.config.isMultiSelect &&
props.onClose
) {
props.onClose();
@@ -341,42 +383,41 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
}
}}
onMouseEnter={() => {
- if (!keyboardMode()) {
- setSelectedIndex(index());
+ if (!dropdown.keyboardMode()) {
+ dropdown.setSelectedIndex(index());
}
}}
- >
- <PropertyValueIcon optionId={item.option!.id} />
- <div class="flex-1 text-left">
- <p class="text-sm font-medium">
- {formatOptionValue(item.option!)}
- </p>
- </div>
- <div class="flex items-center gap-2 flex-shrink-0">
- <Show when={shouldShowHotkeys() && index() < 9}>
- <div class="text-[0.625rem] px-1.5 py-0.5 border border-edge-muted text-ink-muted font-mono rounded-xs">
- <Hotkey shortcut={`${index() + 1}`} />
- </div>
- </Show>
- <Show when={props.property.isMultiSelect}>
+ showHotkey={
+ dropdown.shouldShowHotkeys() && index() < 9
+ }
+ hotkeyShortcut={`${index() + 1}`}
+ rightContent={
+ <Show when={props.config.isMultiSelect}>
<OptionCheckBox
checked={isOptionSelected(item.option!.id)}
- multiselect={props.property.isMultiSelect}
+ multiselect={props.config.isMultiSelect}
/>
</Show>
+ }
+ >
+ <PropertyValueIcon optionId={item.option!.id} />
+ <div class="flex-1 min-w-0 text-left">
+ <p class="text-sm font-medium truncate">
+ {item.option!.label}
+ </p>
</div>
- </div>
+ </DropdownSelectableRow>
}
>
<div
onMouseEnter={() => {
- if (!keyboardMode()) {
- setSelectedIndex(index());
+ if (!dropdown.keyboardMode()) {
+ dropdown.setSelectedIndex(index());
}
}}
>
<AddOptionButton
- isSelected={index() === selectedIndex()}
+ isSelected={index() === dropdown.selectedIndex()}
/>
</div>
</Show>
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/types.ts b/js/app/packages/core/component/Properties/component/modal/shared/types.ts
new file mode 100644
index 0000000000..6da9704a47
--- /dev/null
+++ b/js/app/packages/core/component/Properties/component/modal/shared/types.ts
@@ -0,0 +1,17 @@
+import type { EntityType } from '@service-properties/generated/schemas/entityType';
+
+export type SelectableOption = { id: string; label: string };
+
+export type OptionSelectorConfig = {
+ isMultiSelect: boolean;
+ placeholder: string;
+ inputType?: 'text' | 'number';
+ canAddOption?: (query: string) => boolean;
+};
+
+export type EntitySelectorConfig = {
+ isMultiSelect: boolean;
+ placeholder: string;
+ specificEntityType?: EntityType | null;
+ selfFilter?: { entityType: EntityType; blockId?: string };
+};
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.tsx
index ec387f5aac..e8e3653d67 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
@@ -8,7 +8,6 @@ import type {
Property,
PropertyApiValues,
} from '@core/component/Properties/types';
-import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';
import { EntityType } from '@service-properties/generated/schemas/entityType';
import { For, Show, createMemo } from 'solid-js';
import { useSaveEntityPropertyMutation } from '@queries/properties/entity';
@@ -18,16 +17,10 @@ import {
type EntityWithProperties,
isTaskEntity,
} from '../types/entity';
-import { soupPropertyToProperty } from './property-helpers';
-
-/**
- * Key property definition IDs in display order: Status, Priority, Assignees
- */
-const KEY_PROPERTY_ORDER = [
- SYSTEM_PROPERTY_IDS.STATUS,
- SYSTEM_PROPERTY_IDS.PRIORITY,
- SYSTEM_PROPERTY_IDS.ASSIGNEES,
-] as const;
+import {
+ getSortedKeyProperties,
+ soupPropertyToProperty,
+} from './property-helpers';
function getEntityType(entity: EntityData): EntityType {
return match(entity)
@@ -67,24 +60,7 @@ export function EntityKeyProperties(props: EntityKeyPropertiesProps) {
const keyProperties = createMemo((): Property[] => {
const soupProperties = props.entity.properties ?? [];
-
- const converted = soupProperties
- .map(soupPropertyToProperty)
- .filter((prop) =>
- KEY_PROPERTY_ORDER.includes(
- prop.propertyDefinitionId as (typeof KEY_PROPERTY_ORDER)[number]
- )
- );
-
- return converted.sort((a, b) => {
- const aIndex = KEY_PROPERTY_ORDER.indexOf(
- a.propertyDefinitionId as (typeof KEY_PROPERTY_ORDER)[number]
- );
- const bIndex = KEY_PROPERTY_ORDER.indexOf(
- b.propertyDefinitionId as (typeof KEY_PROPERTY_ORDER)[number]
- );
- return aIndex - bIndex;
- });
+ return getSortedKeyProperties(soupProperties.map(soupPropertyToProperty));
});
const saveMutation = useSaveEntityPropertyMutation();
diff --git a/js/app/packages/entity/src/extractors-property/property-helpers.ts b/js/app/packages/entity/src/extractors-property/property-helpers.ts
index 76ff095b2b..b10feae691 100644
--- a/js/app/packages/entity/src/extractors-property/property-helpers.ts
+++ b/js/app/packages/entity/src/extractors-property/property-helpers.ts
@@ -10,6 +10,7 @@ import {
NUMBER_DECIMAL_PLACES,
} from '@core/component/Properties/constants';
import { nanoid } from 'nanoid';
+import { TASK_STATUS_OPTIONS } from '../utils/task-properties';
const EPOCH_ZERO = new Date(0);
@@ -28,49 +29,17 @@ export const PROPERTY_SORT_ORDER = [
* human-readable values without fetching options from the API.
*/
const SYSTEM_PROPERTY_OPTIONS: Record<string, PropertyOption[]> = {
- [SYSTEM_PROPERTY_IDS.STATUS]: [
- {
- id: PROPERTY_OPTION_IDS.STATUS.NOT_STARTED,
+ [SYSTEM_PROPERTY_IDS.STATUS]: TASK_STATUS_OPTIONS.map(
+ ({ value, label }, displayOrder) => ({
+ id: value,
property_definition_id: SYSTEM_PROPERTY_IDS.STATUS,
- value: { type: 'string', value: 'Not Started' },
- display_order: 0,
+ value: { type: 'string', value: label },
+ display_order: displayOrder,
// TODO: need to properly handle dates. does not seem like these are even used/upserted anywhere?
created_at: EPOCH_ZERO.toISOString(),
updated_at: EPOCH_ZERO.toISOString(),
- },
- {
- id: PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,
- property_definition_id: SYSTEM_PROPERTY_IDS.STATUS,
- value: { type: 'string', value: 'In Progress' },
- display_order: 1,
- created_at: EPOCH_ZERO.toISOString(),
- updated_at: EPOCH_ZERO.toISOString(),
- },
- {
- id: PROPERTY_OPTION_IDS.STATUS.IN_REVIEW,
- property_definition_id: SYSTEM_PROPERTY_IDS.STATUS,
- value: { type: 'string', value: 'In Review' },
- display_order: 2,
- created_at: EPOCH_ZERO.toISOString(),
- updated_at: EPOCH_ZERO.toISOString(),
- },
- {
- id: PROPERTY_OPTION_IDS.STATUS.COMPLETED,
- property_definition_id: SYSTEM_PROPERTY_IDS.STATUS,
- value: { type: 'string', value: 'Completed' },
- display_order: 3,
- created_at: EPOCH_ZERO.toISOString(),
- updated_at: EPOCH_ZERO.toISOString(),
- },
- {
- id: PROPERTY_OPTION_IDS.STATUS.CANCELED,
- property_definition_id: SYSTEM_PROPERTY_IDS.STATUS,
- value: { type: 'string', value: 'Canceled' },
- display_order: 4,
- created_at: EPOCH_ZERO.toISOString(),
- updated_at: EPOCH_ZERO.toISOString(),
- },
- ],
+ })
+ ),
[SYSTEM_PROPERTY_IDS.PRIORITY]: [
{
id: PROPERTY_OPTION_IDS.PRIORITY.LOW,
diff --git a/js/app/packages/entity/src/index.ts b/js/app/packages/entity/src/index.ts
index 7000e34357..6c18fb2bb8 100644
--- a/js/app/packages/entity/src/index.ts
+++ b/js/app/packages/entity/src/index.ts
@@ -24,5 +24,12 @@ export {
} from './utils/notification';
export { unreadFilterFn } from './utils/filter';
+export {
+ TASK_STATUS_OPTIONS,
+ getTaskAssigneeIds,
+ getTaskStatusOptionId,
+ isTaskClosed,
+ isCurrentUserAssigned,
+} from './utils/task-properties';
export { default as DebugEntityView } from './debug/DebugEntityView';
diff --git a/js/app/packages/entity/src/utils/task-properties.ts b/js/app/packages/entity/src/utils/task-properties.ts
new file mode 100644
index 0000000000..2d1856afa2
--- /dev/null
+++ b/js/app/packages/entity/src/utils/task-properties.ts
@@ -0,0 +1,132 @@
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@core/component/Properties/constants';
+import type { TaskEntityWithProperties } from '../types/entity';
+
+export const TASK_STATUS_OPTIONS = [
+ { value: PROPERTY_OPTION_IDS.STATUS.NOT_STARTED, label: 'Not Started' },
+ { value: PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS, label: 'In Progress' },
+ { value: PROPERTY_OPTION_IDS.STATUS.IN_REVIEW, label: 'In Review' },
+ { value: PROPERTY_OPTION_IDS.STATUS.COMPLETED, label: 'Completed' },
+ { value: PROPERTY_OPTION_IDS.STATUS.CANCELED, label: 'Canceled' },
+] as const;
+
+const getTaskPropertyByDefinitionId = (
+ entity: TaskEntityWithProperties,
+ definitionId: string
+) => {
+ return entity.properties?.find((property) => {
+ return property.definition.id === definitionId;
+ });
+};
+
+const isStringArray = (value: unknown): value is string[] => {
+ return (
+ Array.isArray(value) && value.every((item) => typeof item === 'string')
+ );
+};
+
+const isEntityReferenceArray = (
+ value: unknown
+): value is Array<{ entity_type: string; entity_id: string }> => {
+ return (
+ Array.isArray(value) &&
+ value.every((item) => {
+ return (
+ typeof item === 'object' &&
+ item !== null &&
+ 'entity_type' in item &&
+ 'entity_id' in item &&
+ typeof item.entity_type === 'string' &&
+ typeof item.entity_id === 'string'
+ );
+ })
+ );
+};
+
+/**
+ * Extracts assignee user ids from task properties.
+ */
+export const getTaskAssigneeIds = (
+ entity: TaskEntityWithProperties
+): string[] => {
+ const assigneesProperty = getTaskPropertyByDefinitionId(
+ entity,
+ SYSTEM_PROPERTY_IDS.ASSIGNEES
+ );
+
+ if (!assigneesProperty?.value) {
+ return [];
+ }
+
+ const value = assigneesProperty.value;
+ if (
+ value.type !== 'EntityReference' ||
+ !isEntityReferenceArray(value.value)
+ ) {
+ return [];
+ }
+
+ return value.value
+ .filter((reference) => reference.entity_type === 'USER')
+ .map((reference) => reference.entity_id);
+};
+
+/**
+ * Gets the status option id from task properties.
+ */
+export const getTaskStatusOptionId = (
+ entity: TaskEntityWithProperties
+): string | undefined => {
+ const statusProperty = getTaskPropertyByDefinitionId(
+ entity,
+ SYSTEM_PROPERTY_IDS.STATUS
+ );
+
+ if (!statusProperty?.value) {
+ return undefined;
+ }
+
+ const value = statusProperty.value;
+ if (value.type !== 'SelectOption' || !isStringArray(value.value)) {
+ return undefined;
+ }
+
+ return value.value[0];
+};
+
+/**
+ * Checks if a task is in a closed state.
+ */
+export const isTaskClosed = (entity: TaskEntityWithProperties): boolean => {
+ if (entity.subType?.is_completed === true) {
+ return true;
+ }
+
+ const statusOptionId = getTaskStatusOptionId(entity);
+ return (
+ statusOptionId === PROPERTY_OPTION_IDS.STATUS.COMPLETED ||
+ statusOptionId === PROPERTY_OPTION_IDS.STATUS.CANCELED
+ );
+};
+
+/**
+ * Checks if the current user is assigned to the task.
+ * If a task has no assignees, it is treated as visible to everyone.
+ */
+export const isCurrentUserAssigned = (
+ entity: TaskEntityWithProperties,
+ currentUserId: string | undefined
+): boolean => {
+ if (!currentUserId) {
+ return false;
+ }
+
+ const assigneeIds = getTaskAssigneeIds(entity);
+ if (assigneeIds.length === 0) {
+ return true;
+ }
+
+ return assigneeIds.includes(currentUserId);
+};
diff --git a/js/app/packages/entity/tests/task-properties.test.ts b/js/app/packages/entity/tests/task-properties.test.ts
new file mode 100644
index 0000000000..aa0ac63ee3
--- /dev/null
+++ b/js/app/packages/entity/tests/task-properties.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, it } from 'vitest';
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@core/component/Properties/constants';
+import type { SoupProperty } from '@service-storage/generated/schemas';
+import type { TaskEntityWithProperties } from '../src/types/entity';
+import {
+ getTaskAssigneeIds,
+ getTaskStatusOptionId,
+ isCurrentUserAssigned,
+ isTaskClosed,
+} from '../src/utils/task-properties';
+
+const createSoupProperty = (
+ definitionId: string,
+ value: unknown
+): SoupProperty => {
+ return {
+ definition: { id: definitionId },
+ value,
+ } as unknown as SoupProperty;
+};
+
+const createTask = (props?: {
+ isCompleted?: boolean;
+ properties?: SoupProperty[];
+}): TaskEntityWithProperties => {
+ return {
+ id: 'task-1',
+ name: 'Task',
+ ownerId: 'owner-1',
+ type: 'document',
+ fileType: 'md',
+ subType: {
+ type: 'task',
+ is_completed: props?.isCompleted,
+ },
+ properties: props?.properties ?? [],
+ };
+};
+
+describe('task property helpers', () => {
+ describe('getTaskAssigneeIds', () => {
+ it('returns only USER entity ids from assignees property', () => {
+ const entity = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [
+ { entity_type: 'USER', entity_id: 'user-1' },
+ { entity_type: 'CHANNEL', entity_id: 'channel-1' },
+ { entity_type: 'USER', entity_id: 'user-2' },
+ ],
+ }),
+ ],
+ });
+
+ expect(getTaskAssigneeIds(entity)).toEqual(['user-1', 'user-2']);
+ });
+
+ it('returns empty array when assignees property is missing', () => {
+ const entity = createTask();
+ expect(getTaskAssigneeIds(entity)).toEqual([]);
+ });
+ });
+
+ describe('getTaskStatusOptionId', () => {
+ it('returns first selected status option id', () => {
+ const entity = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.STATUS, {
+ type: 'SelectOption',
+ value: [
+ PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,
+ PROPERTY_OPTION_IDS.STATUS.IN_REVIEW,
+ ],
+ }),
+ ],
+ });
+
+ expect(getTaskStatusOptionId(entity)).toBe(
+ PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS
+ );
+ });
+
+ it('returns undefined when status property is missing', () => {
+ const entity = createTask();
+ expect(getTaskStatusOptionId(entity)).toBeUndefined();
+ });
+ });
+
+ describe('isTaskClosed', () => {
+ it('returns true when subtype is marked completed', () => {
+ const entity = createTask({ isCompleted: true });
+ expect(isTaskClosed(entity)).toBe(true);
+ });
+
+ it('returns true for completed status option', () => {
+ const entity = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.STATUS, {
+ type: 'SelectOption',
+ value: [PROPERTY_OPTION_IDS.STATUS.COMPLETED],
+ }),
+ ],
+ });
+
+ expect(isTaskClosed(entity)).toBe(true);
+ });
+
+ it('returns false for in-progress status option', () => {
+ const entity = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.STATUS, {
+ type: 'SelectOption',
+ value: [PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS],
+ }),
+ ],
+ });
+
+ expect(isTaskClosed(entity)).toBe(false);
+ });
+ });
+
+ describe('isCurrentUserAssigned', () => {
+ it('returns false when current user is undefined', () => {
+ const entity = createTask();
+ expect(isCurrentUserAssigned(entity, undefined)).toBe(false);
+ });
+
+ it('returns true when task has no assignees', () => {
+ const entity = createTask();
+ expect(isCurrentUserAssigned(entity, 'user-1')).toBe(true);
+ });
+
+ it('returns true when current user is assigned', () => {
+ const entity = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [{ entity_type: 'USER', entity_id: 'user-1' }],
+ }),
+ ],
+ });
+
+ expect(isCurrentUserAssigned(entity, 'user-1')).toBe(true);
+ });
+
+ it('returns false when current user is not assigned', () => {
+ const entity = createTask({
+ properties: [
+ createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [{ entity_type: 'USER', entity_id: 'user-2' }],
+ }),
+ ],
+ });
+
+ expect(isCurrentUserAssigned(entity, 'user-1')).toBe(false);
+ });
+ });
+});