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(properties): custom properties ui (#5457)

Seamus02b92f5da7b3
diff --git a/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx b/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx
index eb00d32c71..e259f1d1b5 100644
--- a/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx
+++ b/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx
@@ -4,6 +4,7 @@ import {
createEffect,
createSelector,
createSignal,
+ For,
type JSX,
type ParentProps,
type Setter,
@@ -170,6 +171,89 @@ export const CommandMenuShell = Object.assign(CommandMenuShellRoot, {
Footer: CommandMenuFooter,
});
+export function CommandMenuList<T>(props: {
+ items: readonly T[];
+ selectedIndex: number;
+ scrollSelectedIntoView?: boolean;
+ class?: string;
+ itemId?: (item: T, index: number) => string;
+ itemDisabled?: (item: T, index: number) => boolean;
+ beforeItem?: (item: T, index: number) => JSX.Element;
+ onSelect: (item: T, index: number, event: MouseEvent) => void;
+ onItemMouseMove?: (index: number, item: T) => void;
+ children: (item: T, index: Accessor<number>) => JSX.Element;
+}) {
+ let listRef: HTMLDivElement | undefined;
+ let lastMousePosition: { x: number; y: number } | undefined;
+ let suppressPointerSelectionUntil = 0;
+
+ const isSelected = createSelector(() => props.selectedIndex);
+
+ const itemId = (item: T, index: number) =>
+ props.itemId?.(item, index) ?? `command-menu-list-item-${index}`;
+
+ createEffect(() => {
+ const index = props.selectedIndex;
+ const item = props.items[index];
+
+ if (!props.scrollSelectedIntoView || !listRef || !item) return;
+
+ suppressPointerSelectionUntil = performance.now() + 250;
+ const elem = document.getElementById(itemId(item, index));
+ elem?.scrollIntoView({ block: 'nearest' });
+ });
+
+ const handleMouseMove = (event: MouseEvent, item: T, index: number) => {
+ const mousePosition = { x: event.clientX, y: event.clientY };
+ const isFirstMouseMove = lastMousePosition === undefined;
+ const moved =
+ lastMousePosition !== undefined &&
+ (lastMousePosition.x !== mousePosition.x ||
+ lastMousePosition.y !== mousePosition.y);
+
+ lastMousePosition = mousePosition;
+
+ if (performance.now() < suppressPointerSelectionUntil) return;
+
+ if (moved || isFirstMouseMove) {
+ props.onItemMouseMove?.(index, item);
+ }
+ };
+
+ return (
+ <div
+ ref={listRef}
+ role="listbox"
+ class={cn(
+ 'max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden p-2',
+ props.class
+ )}
+ onScroll={() => {
+ suppressPointerSelectionUntil = performance.now() + 120;
+ }}
+ >
+ <For each={props.items}>
+ {(item, index) => (
+ <>
+ {props.beforeItem?.(item, index())}
+ <CommandMenuListItem
+ as="div"
+ id={itemId(item, index())}
+ selected={isSelected(index())}
+ disabled={props.itemDisabled?.(item, index())}
+ class="scroll-m-2"
+ onClick={(event) => props.onSelect(item, index(), event)}
+ onMouseMove={(event) => handleMouseMove(event, item, index())}
+ >
+ {props.children(item, index)}
+ </CommandMenuListItem>
+ </>
+ )}
+ </For>
+ </div>
+ );
+}
+
export function CommandMenuSearchInput(
props: JSX.InputHTMLAttributes<HTMLInputElement>
) {
@@ -202,9 +286,11 @@ export function CommandMenuListItem(
component={props.as ?? 'button'}
type={props.as === 'div' ? undefined : 'button'}
id={props.id}
- disabled={props.disabled}
+ disabled={props.as === 'div' ? undefined : props.disabled}
+ aria-disabled={props.disabled || undefined}
class={cn(
'rounded-md group w-full flex items-center h-10 px-2 gap-2 text-sm font-semibold relative scroll-m-1 text-left disabled:opacity-50 disabled:pointer-events-none',
+ props.disabled && 'opacity-50 pointer-events-none',
props.selected && 'bg-active',
props.class
)}
diff --git a/apps/web/src/components/ui/components/Dropdown.tsx b/apps/web/src/components/ui/components/Dropdown.tsx
index dcf1691c76..3659815456 100644
--- a/apps/web/src/components/ui/components/Dropdown.tsx
+++ b/apps/web/src/components/ui/components/Dropdown.tsx
@@ -73,7 +73,7 @@ export type DropdownItemProps = ComponentProps<typeof KobalteDropdownMenu.Item>;
export type DropdownSubProps = ComponentProps<typeof KobalteDropdownMenu.Sub>;
const ROW_CLASS =
- 'group rounded-lg w-full flex items-center gap-1.5 p-1.5 px-2 text-left font-normal text-sm cursor-default outline-none hover:bg-ink/5 data-highlighted:bg-ink/5 data-disabled:opacity-50 data-disabled:cursor-not-allowed';
+ 'group rounded-lg w-full flex items-center gap-1.5 p-1.5 px-2 text-left font-normal text-sm cursor-default outline-none data-highlighted:bg-ink/5 data-disabled:opacity-50 data-disabled:cursor-not-allowed';
function resolvePortalMount(
searchRef: HTMLElement | undefined,
@@ -272,7 +272,7 @@ function DropdownGroupLabel(props: DropdownGroupLabelProps) {
const CHECKBOX_ITEM_BOX_CLASS = cn(
'inline-flex items-center justify-center size-3.5 shrink-0 rounded-sm',
'border border-transparent text-surface',
- 'group-hover:not-hover:border-edge-muted group-data-highlighted:not-hover:border-edge-muted',
+ 'group-data-highlighted:not-hover:border-edge-muted',
'hover:border-accent',
'group-data-checked:bg-accent group-data-checked:border-accent'
);
diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.ts
index 0964a01c46..6d1ef3f879 100644
--- a/apps/web/src/components/ui/index.ts
+++ b/apps/web/src/components/ui/index.ts
@@ -26,6 +26,7 @@ export {
type CommandListController,
CommandMenuEmptyState,
CommandMenuHotkeyHint,
+ CommandMenuList,
CommandMenuListItem,
CommandMenuSearchInput,
CommandMenuShell,
@@ -68,4 +69,5 @@ export {
addCtrlJKMenuNavigation,
ctrlJKMenuNavigation,
handleCtrlJKMenuNavigation,
+ wrapIndex,
} from './utils/menuKeyboardNavigation';
diff --git a/apps/web/src/components/ui/utils/menuKeyboardNavigation.ts b/apps/web/src/components/ui/utils/menuKeyboardNavigation.ts
index a2d9145472..86ffd415ea 100644
--- a/apps/web/src/components/ui/utils/menuKeyboardNavigation.ts
+++ b/apps/web/src/components/ui/utils/menuKeyboardNavigation.ts
@@ -4,8 +4,27 @@ import { type Accessor, onCleanup } from 'solid-js';
export type CtrlJKMenuNavigationOptions = {
enabled?: boolean;
macOnly?: boolean;
+ /**
+ * When `true`, vertical navigation wraps around the ends of the list:
+ * pressing down on the last item jumps to the first, and up on the first
+ * jumps to the last.
+ *
+ * Kobalte's Select/menu components don't expose a focus-wrap prop, so this
+ * is implemented by dispatching `Home`/`End` (which Kobalte does handle)
+ * when the highlighted item is already at an edge. Defaults to `false` to
+ * preserve existing (clamping) behavior.
+ */
+ wrap?: boolean;
};
+/**
+ * Elements Kobalte marks as navigable in its listbox/menu collections. The
+ * highlighted one carries `data-highlighted`; disabled ones carry
+ * `data-disabled`.
+ */
+const NAVIGABLE_ITEM_SELECTOR =
+ '[role="option"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"]';
+
declare module 'solid-js' {
namespace JSX {
interface Directives {
@@ -18,15 +37,36 @@ function resolveOptions(
options: CtrlJKMenuNavigationOptions | boolean | undefined
): Required<CtrlJKMenuNavigationOptions> {
if (typeof options === 'boolean') {
- return { enabled: options, macOnly: true };
+ return { enabled: options, macOnly: true, wrap: false };
}
return {
enabled: options?.enabled ?? true,
macOnly: options?.macOnly ?? true,
+ wrap: options?.wrap ?? false,
};
}
+/**
+ * Wraps an index within `[0, length)`, cycling around the ends.
+ *
+ * Moving past the last item lands on the first, and moving before the first
+ * lands on the last. Useful for manual (non-Kobalte) list navigation that
+ * would otherwise clamp with `Math.min`/`Math.max`.
+ *
+ * Starting from `-1` (nothing focused) with a positive `delta` selects the
+ * first item; with a negative `delta` it selects the last.
+ *
+ * @param index - The current index (may be `-1` for "no selection").
+ * @param length - The number of items in the list.
+ * @param delta - How far to move (e.g. `1` for down, `-1` for up).
+ * @returns The wrapped index, or `-1` when the list is empty.
+ */
+export function wrapIndex(index: number, length: number, delta: number) {
+ if (length <= 0) return -1;
+ return (((index + delta) % length) + length) % length;
+}
+
function translatedArrowKey(e: KeyboardEvent, macOnly: boolean) {
if (macOnly && !isMac) return;
if (!e.ctrlKey || e.metaKey || e.altKey) return;
@@ -43,6 +83,38 @@ function translatedArrowKey(e: KeyboardEvent, macOnly: boolean) {
}
}
+/**
+ * When wrapping is enabled and the highlighted item sits at an edge, returns
+ * the key that jumps to the opposite end (`Home`/`End`) instead of the arrow
+ * key that would otherwise do nothing. Returns the original `key` when no
+ * wrap is needed or the list state can't be determined.
+ */
+function wrappedEdgeKey(e: KeyboardEvent, key: 'ArrowDown' | 'ArrowUp') {
+ const root =
+ (e.currentTarget instanceof Element ? e.currentTarget : null) ??
+ (e.target instanceof Element
+ ? e.target.closest('[role="listbox"], [role="menu"]')
+ : null);
+ if (!root) return key;
+
+ const items = Array.from(
+ root.querySelectorAll<HTMLElement>(NAVIGABLE_ITEM_SELECTOR)
+ ).filter(
+ (el) =>
+ !el.hasAttribute('data-disabled') &&
+ el.getAttribute('aria-disabled') !== 'true'
+ );
+ if (items.length === 0) return key;
+
+ const currentIndex = items.findIndex((el) =>
+ el.hasAttribute('data-highlighted')
+ );
+
+ if (key === 'ArrowDown' && currentIndex === items.length - 1) return 'Home';
+ if (key === 'ArrowUp' && currentIndex === 0) return 'End';
+ return key;
+}
+
export function handleCtrlJKMenuNavigation(
e: KeyboardEvent,
options?: CtrlJKMenuNavigationOptions | boolean
@@ -59,10 +131,15 @@ export function handleCtrlJKMenuNavigation(
const target = e.target instanceof Element ? e.target : e.currentTarget;
if (!(target instanceof Element)) return true;
+ const dispatchedKey =
+ resolved.wrap && (key === 'ArrowDown' || key === 'ArrowUp')
+ ? wrappedEdgeKey(e, key)
+ : key;
+
target.dispatchEvent(
new KeyboardEvent('keydown', {
- key,
- code: key,
+ key: dispatchedKey,
+ code: dispatchedKey,
bubbles: true,
cancelable: true,
composed: true,
diff --git a/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx b/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx
index 711bf04325..1e02ed4b0c 100644
--- a/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx
+++ b/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx
@@ -113,6 +113,7 @@ export function TaskGridLayout(props: LayoutProps) {
return (
<PropertiesProvider
+ entityId={props.entity.id}
entityType={EntityType.TASK}
canEdit={true}
properties={properties}
diff --git a/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx b/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx
index 69d5a073c4..131f085ad2 100644
--- a/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx
+++ b/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx
@@ -1,25 +1,44 @@
-import { useBlockId } from '@core/block';
+import { useMaybeBlockId } from '@core/block';
+import { TabsInset } from '@core/component/TabsInset';
import { useUserId } from '@core/context/user';
+import type { CollectionNode } from '@kobalte/core';
+import { Select } from '@kobalte/core/select';
import CaretDownIcon from '@phosphor/caret-down.svg';
import CheckIcon from '@phosphor/check.svg';
+import SlidersIcon from '@phosphor/sliders-horizontal.svg';
import LoadingSpinner from '@phosphor/spinner.svg';
import XIcon from '@phosphor/x.svg';
import { useCreatePropertyDefinitionMutation } from '@queries/properties/definitions';
import { useAddEntityPropertyMutation } from '@queries/properties/entity';
+import { useCurrentTeamQuery } from '@queries/team/teams';
+import type { CreatePropertyScope } from '@service-properties/generated/schemas/createPropertyScope';
+import type { DataType } from '@service-properties/generated/schemas/dataType';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import type { PropertyDataType } from '@service-properties/generated/schemas/propertyDataType';
-import { Button, Dialog, Dropdown, SegmentedControl, Surface } from '@ui';
+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
+import {
+ addCtrlJKMenuNavigation,
+ Button,
+ CommandMenuShell,
+ cn,
+ Dialog,
+ Hotkey,
+ Layer,
+} from '@ui';
import {
type Component,
+ createEffect,
createMemo,
createSignal,
- For,
Index,
+ type JSX,
+ onCleanup,
Show,
} from 'solid-js';
-import { usePropertiesContext } from '../../context/PropertiesContext';
+import { useMaybePropertiesContext } from '../../context/PropertiesContext';
import {
getPropertyDataTypeDropdownOptions,
+ PropertyDataTypeIcon,
usePropertyNameFocus,
} from '../../utils';
import { ERROR_MESSAGES } from '../../utils/errorHandling';
@@ -28,6 +47,9 @@ import { ERROR_MESSAGES } from '../../utils/errorHandling';
type DataTypeValue = ReturnType<
typeof getPropertyDataTypeDropdownOptions
>[number]['value'];
+type DataTypeOption = ReturnType<
+ typeof getPropertyDataTypeDropdownOptions
+>[number];
type Option<T> = {
id: string;
@@ -38,32 +60,61 @@ type Option<T> = {
type OptionInputProps<T extends string | number> = {
options: () => Option<T>[];
type: 'string' | 'number';
- onAdd: () => string;
onRemove: (id: string) => void;
onUpdate: (id: string, value: T) => void;
placeholder?: string;
};
+function EditorRow(props: {
+ label: string;
+ children: JSX.Element;
+ align?: 'center' | 'start';
+}) {
+ return (
+ <div
+ class={cn(
+ 'flex min-h-12 gap-5 px-4 py-3',
+ props.align === 'start' ? 'items-start' : 'items-center'
+ )}
+ >
+ <div
+ class={cn(
+ 'w-22 shrink-0 text-xs font-medium text-ink-extra-muted',
+ props.align === 'start' && 'pt-2'
+ )}
+ >
+ {props.label}
+ </div>
+ <div class="min-w-0 flex-1">{props.children}</div>
+ </div>
+ );
+}
+
+const inputClass =
+ 'h-9 min-w-0 w-full flex-1 rounded-md border border-edge-muted bg-surface px-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:border-accent';
+
+const hasOptionValue = (value: string | number) =>
+ typeof value === 'string' ? value.trim() !== '' : !isNaN(value);
+
const OptionInput: Component<OptionInputProps<string | number>> = (props) => {
const handleKeyDown = (
e: KeyboardEvent,
- _optionId: string,
+ optionId: string,
currentValue: string | number
) => {
if (e.key === 'Enter') {
e.preventDefault();
- const hasValue =
- props.type === 'string'
- ? !!(currentValue as string).trim()
- : props.type === 'number';
-
- if (hasValue) {
- const newOptionId = props.onAdd();
+ if (hasOptionValue(currentValue)) {
+ const currentIndex = props
+ .options()
+ .findIndex((option) => option.id === optionId);
+ const nextOptionId = props.options()[currentIndex + 1]?.id;
+ if (!nextOptionId) return;
setTimeout(() => {
const newInput = document.querySelector(
- `input[data-option-id="${newOptionId}"]`
+ `input[data-option-id="${nextOptionId}"]`
) as HTMLInputElement;
if (newInput) {
newInput.focus();
@@ -74,7 +125,7 @@ const OptionInput: Component<OptionInputProps<string | number>> = (props) => {
};
return (
- <div class="space-y-2 max-h-40 overflow-y-auto">
+ <div class="max-h-40 space-y-2 overflow-y-auto">
<Index each={props.options()}>
{(option) => (
<div class="flex items-center gap-2">
@@ -85,29 +136,28 @@ const OptionInput: Component<OptionInputProps<string | number>> = (props) => {
const value =
props.type === 'string'
? e.currentTarget.value
- : Number(e.currentTarget.value);
+ : e.currentTarget.value === ''
+ ? ''
+ : Number(e.currentTarget.value);
props.onUpdate(option().id, value as string | number);
}}
onKeyDown={(e) => handleKeyDown(e, option().id, option().value)}
placeholder={props.placeholder}
- class="flex-1 p-1.5 border border-edge-muted text-sm rounded-sm bg-surface placeholder:text-ink-placeholder"
+ class={inputClass}
data-option-id={option().id}
/>
- <button
- type="button"
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Remove option"
onClick={() => props.onRemove(option().id)}
- class="text-failure-ink hover:text-failure-ink text-md px-1"
+ class="shrink-0 rounded-lg text-failure-ink"
>
- ×
- </button>
+ <XIcon />
+ </Button>
</div>
)}
</Index>
- <Show when={props.options().length === 0}>
- <div class="text-center py-4 text-ink-muted text-sm">
- No options added yet
- </div>
- </Show>
</div>
);
};
@@ -115,44 +165,55 @@ const OptionInput: Component<OptionInputProps<string | number>> = (props) => {
interface CreatePropertyModalProps {
isOpen: boolean;
onClose: () => void;
- onPropertyCreated?: (propertyDefinitionId?: string) => void;
+ onPropertyCreated?: (
+ propertyDefinitionId?: string,
+ propertyDefinition?: PropertyDefinition
+ ) => void;
autoPinOnCreate?: boolean;
+ initialName?: string;
+ entityId?: string;
+ entityType?: EntityType;
}
export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
props
) => {
- const blockId = useBlockId();
- const { entityType } = usePropertiesContext();
+ const context = useMaybePropertiesContext();
+ const blockId = useMaybeBlockId();
+ const entityId = () => props.entityId ?? blockId;
+ const entityType = () => props.entityType ?? context?.entityType;
const [newPropertyName, setNewPropertyName] = createSignal('');
const [selectedDataType, setSelectedDataType] =
createSignal<DataTypeValue>('string');
+ const [propertyScope, setPropertyScope] =
+ createSignal<CreatePropertyScope>('team');
const [isMultiSelect, setIsMultiSelect] = createSignal(false);
const [newStringOptions, setNewStringOptions] = createSignal<
Array<{ id: string; value: string; display_order: number }>
>([]);
const [newNumberOptions, setNewNumberOptions] = createSignal<
- Array<{ id: string; value: number; display_order: number }>
+ Array<{ id: string; value: number | ''; display_order: number }>
>([]);
const [error, setError] = createSignal<string | null>(null);
const addMutation = useAddEntityPropertyMutation();
+ const currentTeamQuery = useCurrentTeamQuery();
const createPropertyMutation = useCreatePropertyDefinitionMutation({
onSuccess: async (propertyDefinition) => {
// Add the property to the current entity if autoPinOnCreate is true
- if (props.autoPinOnCreate && blockId) {
+ if (props.autoPinOnCreate && entityId() && entityType()) {
try {
await addMutation.mutateAsync({
- entityId: blockId,
- entityType,
+ entityId: entityId()!,
+ entityType: entityType()!,
propertyDefinitionId: propertyDefinition.id,
});
resetCreateForm();
// Pass the property definition ID so parent can pin it after refresh
- props.onPropertyCreated?.(propertyDefinition.id);
+ props.onPropertyCreated?.(propertyDefinition.id, propertyDefinition);
props.onClose();
} catch (error) {
console.error('Failed to add property to entity', error);
@@ -160,7 +221,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
}
} else {
resetCreateForm();
- props.onPropertyCreated?.();
+ props.onPropertyCreated?.(propertyDefinition.id, propertyDefinition);
props.onClose();
}
},
@@ -169,40 +230,44 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
},
});
- // Unified option management helpers
- type Option<T> = { id: string; value: T; display_order: number };
+ createEffect(() => {
+ if (props.isOpen) {
+ setNewPropertyName(props.initialName ?? '');
+ }
+ });
- const addOption = <T extends string | number>(
- options: () => Option<T>[],
- setOptions: (options: Option<T>[]) => void,
- defaultValue: T
- ): string => {
- const newOption: Option<T> = {
- id: crypto.randomUUID(),
- value: defaultValue,
- display_order: options().length,
- };
- setOptions([...options(), newOption]);
- return newOption.id;
- };
+ const createOption = <T extends string | number>(
+ value: T,
+ displayOrder: number
+ ): Option<T> => ({
+ id: crypto.randomUUID(),
+ value,
+ display_order: displayOrder,
+ });
const removeOption = <T extends string | number>(
options: () => Option<T>[],
setOptions: (options: Option<T>[]) => void,
- optionId: string
+ optionId: string,
+ defaultValue: T
) => {
- setOptions(options().filter((opt) => opt.id !== optionId));
+ const nextOptions = options()
+ .filter((opt) => opt.id !== optionId)
+ .map((option, index) => ({ ...option, display_order: index }));
+ setOptions(ensureTrailingEmptyOption(nextOptions, defaultValue));
};
const updateOption = <T extends string | number>(
options: () => Option<T>[],
setOptions: (options: Option<T>[]) => void,
optionId: string,
- value: T
+ value: T,
+ defaultValue: T
) => {
- setOptions(
- options().map((opt) => (opt.id === optionId ? { ...opt, value } : opt))
+ const nextOptions = options().map((opt) =>
+ opt.id === optionId ? { ...opt, value } : opt
);
+ setOptions(ensureTrailingEmptyOption(nextOptions, defaultValue));
};
const hasDuplicateOptions = <T extends string | number>(
@@ -217,18 +282,32 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
return new Set(nonEmptyValues).size !== nonEmptyValues.length;
};
+ const ensureTrailingEmptyOption = <T extends string | number>(
+ options: Option<T>[],
+ defaultValue: T
+ ): Option<T>[] => {
+ if (options.length === 0) return [createOption(defaultValue, 0)];
+
+ const lastOption = options[options.length - 1];
+ if (!lastOption || !hasOptionValue(lastOption.value)) return options;
+
+ return [...options, createOption(defaultValue, options.length)];
+ };
+
let propertyNameInputRef!: HTMLInputElement;
const userId = useUserId();
const dataTypeDropdownOptions = getPropertyDataTypeDropdownOptions();
- const selectedDataTypeLabel = createMemo(() => {
- const option = dataTypeDropdownOptions.find(
- (opt) => opt.value === selectedDataType()
- );
- return option?.label ?? 'Select type';
- });
+ const selectedDataTypeOption = createMemo(
+ () =>
+ dataTypeDropdownOptions.find((opt) => opt.value === selectedDataType()) ??
+ dataTypeDropdownOptions[0]
+ );
+ const hasTeam = () => Boolean(currentTeamQuery.data?.team);
+ const selectedPropertyScope = (): CreatePropertyScope =>
+ propertyScope() === 'team' && hasTeam() ? 'team' : 'user';
// Helper to parse selected value back to type and specificType
const parseDataTypeValue = (
@@ -264,6 +343,18 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
};
};
+ // Adapt a dropdown value to the shape `PropertyDataTypeIcon` expects, so the
+ // type icons here stay in sync with the property list / tooltip icons.
+ const dataTypeIconProperty = (value: DataTypeValue) => {
+ const { type, specificType } = parseDataTypeValue(value);
+ return {
+ valueType: (type === 'entity'
+ ? 'ENTITY'
+ : type.toUpperCase()) as DataType,
+ specificEntityType: specificType ?? null,
+ };
+ };
+
const buildDataType = (): PropertyDataType => {
const { type, specificType } = parseDataTypeValue(selectedDataType());
@@ -300,9 +391,9 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
case 'select_number':
// Filter out empty options and deduplicate
const numberOptions = newNumberOptions()
- .filter((opt) => !isNaN(opt.value))
+ .filter((opt) => opt.value !== '' && !isNaN(opt.value))
.map((opt, idx) => ({
- value: opt.value,
+ value: Number(opt.value),
display_order: idx,
}));
@@ -327,6 +418,27 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
}
};
+ const hasOptionsForCurrentType = () => {
+ const { type } = parseDataTypeValue(selectedDataType());
+ if (type === 'select_string') {
+ return newStringOptions().some((opt) => opt.value.trim() !== '');
+ }
+ if (type === 'select_number') {
+ return newNumberOptions().some(
+ (opt) => opt.value !== '' && !isNaN(opt.value)
+ );
+ }
+ return true;
+ };
+
+ const resetOptionsForType = (dataType: DataTypeValue) => {
+ const { type } = parseDataTypeValue(dataType);
+ setNewStringOptions(type === 'select_string' ? [createOption('', 0)] : []);
+ setNewNumberOptions(
+ type === 'select_number' ? [createOption<number | ''>('', 0)] : []
+ );
+ };
+
const handleCreateProperty = () => {
const currentUserId = userId();
@@ -352,7 +464,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
if (
(selectedDataType() === 'select_string' ||
selectedDataType() === 'select_number') &&
- getOptionsForCurrentType().length === 0
+ !hasOptionsForCurrentType()
) {
setError(ERROR_MESSAGES.VALIDATION_MIN_OPTIONS);
return;
@@ -367,7 +479,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
setError(null);
const bodyData = {
- scope: 'user' as const,
+ scope: selectedPropertyScope(),
display_name: newPropertyName().trim(),
data_type: buildDataType(),
};
@@ -378,6 +490,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
const resetCreateForm = () => {
setNewPropertyName('');
setSelectedDataType('string');
+ setPropertyScope('team');
setIsMultiSelect(false);
setNewStringOptions([]);
setNewNumberOptions([]);
@@ -399,150 +512,204 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
return type === 'select_string' || type === 'select_number';
});
- const getOptionsForCurrentType = () => {
- const { type } = parseDataTypeValue(selectedDataType());
- return type === 'select_string' ? newStringOptions() : newNumberOptions();
- };
-
usePropertyNameFocus(
() => propertyNameInputRef,
() => props.isOpen
);
+ const pending = () =>
+ createPropertyMutation.isPending || addMutation.isPending;
+
+ const canSubmit = () => newPropertyName().trim().length > 0 && !pending();
+
+ const close = () => {
+ if (pending()) return;
+ resetCreateForm();
+ props.onClose();
+ };
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
+ event.preventDefault();
+ if (canSubmit()) handleCreateProperty();
+ }
+ };
+
return (
<Dialog
open={props.isOpen}
onOpenChange={(open) => {
- if (!open) props.onClose();
+ if (!open) close();
}}
>
- <Surface depth={2} class="*:max-h-[75vh] rounded-xl">
- <div class="flex flex-col text-sm">
- <div class="flex items-center justify-between gap-2 bg-surface px-2 h-10 border-b border-edge-muted shrink-0">
- <Dialog.Title class="pl-2 text-sm font-medium">
- Create New Property
- </Dialog.Title>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => props.onClose()}
- >
- <XIcon />
- </Button>
- </div>
-
- <div class="min-h-0 overflow-y-auto scrollbar-hidden p-4">
- <div class="space-y-3">
- <Show when={error()}>
- <div class="text-failure-ink text-sm p-2 bg-failure-bg">
- {error()}
- </div>
- </Show>
-
- <div>
- <label
- for="property-name"
- class="block text-xs font-medium text-ink mb-1"
- >
- Property Name
- </label>
- <input
- id="property-name"
- ref={propertyNameInputRef}
- type="text"
- value={newPropertyName()}
- onInput={(e) => setNewPropertyName(e.currentTarget.value)}
- placeholder="Enter property name"
- class="w-full p-1.5 border border-edge-muted text-sm rounded-sm bg-surface placeholder:text-ink-placeholder"
- />
+ <CommandMenuShell depth={2} class="text-sm" onKeyDown={handleKeyDown}>
+ <CommandMenuShell.Header class="my-0 h-13 gap-3 border-b-0 px-4">
+ <span class="text-ink-muted">
+ <SlidersIcon class="size-3.5" />
+ </span>
+ <Dialog.Title
+ as="span"
+ class="min-w-0 flex-1 truncate text-sm font-semibold text-ink-extra-muted"
+ >
+ Create property
+ </Dialog.Title>
+ <Dialog.CloseButton
+ as={Button}
+ variant="ghost"
+ size="icon-sm"
+ disabled={pending()}
+ label="Close"
+ >
+ <XIcon />
+ </Dialog.CloseButton>
+ </CommandMenuShell.Header>
+
+ <CommandMenuShell.Body>
+ <div class="bg-surface">
+ <Show when={error()}>
+ <div class="mx-4 mb-1 rounded-md bg-failure-bg px-3 py-2 text-sm text-failure-ink">
+ {error()}
</div>
-
- <div>
- <label class="block text-xs font-medium text-ink mb-1">
- Data Type
- </label>
- <Dropdown>
- <Dropdown.Trigger class="w-full p-1.5 border border-edge-muted bg-surface text-sm text-ink text-left flex items-center gap-2 hover:bg-hover rounded-sm justify-between">
- <span class="truncate">{selectedDataTypeLabel()}</span>
- <CaretDownIcon class="size-3 text-ink-muted shrink-0" />
- </Dropdown.Trigger>
- <Dropdown.Content class="max-h-64 overflow-y-auto min-w-48">
- <Dropdown.Group>
- <For each={dataTypeDropdownOptions}>
- {(option) => (
- <Dropdown.Item
- class="justify-between"
- onSelect={() => {
- setSelectedDataType(option.value);
- setNewStringOptions([]);
- setNewNumberOptions([]);
- setIsMultiSelect(false);
- }}
- >
- <span>{option.label}</span>
- <Show when={option.value === selectedDataType()}>
- <CheckIcon class="size-3 shrink-0" />
- </Show>
- </Dropdown.Item>
+ </Show>
+
+ <EditorRow label="Name">
+ <input
+ id="property-name"
+ ref={propertyNameInputRef}
+ type="text"
+ value={newPropertyName()}
+ onInput={(e) => setNewPropertyName(e.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && canSubmit()) {
+ handleCreateProperty();
+ }
+ }}
+ placeholder="Property name"
+ class={inputClass}
+ />
+ </EditorRow>
+
+ <EditorRow label="Type">
+ <Select<DataTypeOption>
+ options={dataTypeDropdownOptions}
+ value={selectedDataTypeOption()}
+ onChange={(option) => {
+ if (!option) return;
+ setSelectedDataType(option.value);
+ resetOptionsForType(option.value);
+ setIsMultiSelect(false);
+ }}
+ optionValue="value"
+ optionTextValue="label"
+ gutter={4}
+ placement="bottom-start"
+ itemComponent={(itemProps: {
+ item: CollectionNode<DataTypeOption>;
+ }) => (
+ <Select.Item
+ item={itemProps.item}
+ class="flex w-full cursor-default items-center justify-between gap-2 rounded-lg p-1.5 px-2 text-left text-sm font-normal text-ink outline-none data-highlighted:bg-ink/5 data-disabled:cursor-not-allowed data-disabled:opacity-50"
+ >
+ <div class="flex min-w-0 items-center gap-2">
+ <PropertyDataTypeIcon
+ property={dataTypeIconProperty(
+ itemProps.item.rawValue.value
)}
- </For>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- </div>
-
- <Show when={shouldShowMultiSelect()}>
- <div>
- <label class="block text-xs font-medium text-ink mb-1">
- Selection Type
- </label>
- <SegmentedControl
- value={isMultiSelect() ? 'multi' : 'single'}
- onChange={(v) => setIsMultiSelect(v === 'multi')}
- options={[
- { value: 'single', label: 'Single Select' },
- { value: 'multi', label: 'Multi Select' },
- ]}
- />
- </div>
- </Show>
-
- <Show when={shouldShowOptions()}>
- <div>
- <div class="flex items-center justify-between mb-2">
- <label class="block text-xs font-medium text-ink">
- Options
- </label>
- <Button
- variant="base"
- size="sm"
- class="rounded-xs"
- onClick={() => {
- const { type } = parseDataTypeValue(selectedDataType());
- if (type === 'select_string') {
- addOption(newStringOptions, setNewStringOptions, '');
- } else {
- addOption(newNumberOptions, setNewNumberOptions, 0);
- }
+ class="size-4 shrink-0 text-ink-muted"
+ />
+ <Select.ItemLabel class="truncate">
+ {itemProps.item.rawValue.label}
+ </Select.ItemLabel>
+ </div>
+ <Select.ItemIndicator>
+ <CheckIcon class="size-3 shrink-0" />
+ </Select.ItemIndicator>
+ </Select.Item>
+ )}
+ >
+ <Select.Trigger class="flex h-9 w-full items-center justify-between gap-2 rounded-md border border-edge-muted bg-surface px-3 text-left text-sm text-ink outline-none hover:bg-hover focus-visible:border-accent data-expanded:bg-hover">
+ <Select.Value<DataTypeOption>>
+ {(state) => (
+ <span class="flex min-w-0 items-center gap-2">
+ <PropertyDataTypeIcon
+ property={dataTypeIconProperty(
+ state.selectedOption().value
+ )}
+ class="size-4 shrink-0 text-ink-muted"
+ />
+ <span class="truncate">
+ {state.selectedOption().label}
+ </span>
+ </span>
+ )}
+ </Select.Value>
+ <CaretDownIcon class="size-3 shrink-0 text-ink-muted" />
+ </Select.Trigger>
+ <Select.Portal>
+ <Layer depth={3}>
+ <Select.Content
+ class="z-action-menu min-w-56 overflow-y-auto rounded-xl border border-edge bg-surface p-1.5 shadow-menu menu-open-animation"
+ ref={(el) => {
+ const clean = addCtrlJKMenuNavigation(el, () => ({
+ wrap: true,
+ }));
+ onCleanup(clean);
}}
>
- + Add Option
- </Button>
- </div>
+ <Select.Listbox class="flex flex-col gap-(--app-border-width)" />
+ </Select.Content>
+ </Layer>
+ </Select.Portal>
+ </Select>
+ </EditorRow>
+
+ <Show when={hasTeam()}>
+ <EditorRow label="Owner">
+ <TabsInset
+ depth={0}
+ list={[
+ { value: 'team', label: 'Team' },
+ { value: 'user', label: 'Personal' },
+ ]}
+ value={selectedPropertyScope()}
+ onChange={(value) => {
+ if (value === 'user' || value === 'team') {
+ setPropertyScope(value);
+ }
+ }}
+ />
+ </EditorRow>
+ </Show>
+
+ <Show when={shouldShowMultiSelect()}>
+ <EditorRow label="Selection">
+ <TabsInset
+ depth={0}
+ list={[
+ { value: 'single', label: 'Single' },
+ { value: 'multi', label: 'Multi' },
+ ]}
+ value={isMultiSelect() ? 'multi' : 'single'}
+ onChange={(value) => setIsMultiSelect(value === 'multi')}
+ />
+ </EditorRow>
+ </Show>
+
+ <Show when={shouldShowOptions()}>
+ <EditorRow label="Options" align="start">
+ <div>
<Show
when={selectedDataType() === 'select_string'}
fallback={
<OptionInput
options={newNumberOptions}
type="number"
- onAdd={() =>
- addOption(newNumberOptions, setNewNumberOptions, 0)
- }
onRemove={(id) =>
removeOption(
newNumberOptions,
setNewNumberOptions,
- id
+ id,
+ ''
)
}
onUpdate={(id, value) =>
@@ -550,75 +717,79 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
newNumberOptions,
setNewNumberOptions,
id,
- value as number
+ value as number | '',
+ ''
)
}
- placeholder="Enter number"
+ placeholder="Number"
/>
}
>
<OptionInput
options={newStringOptions}
type="string"
- onAdd={() =>
- addOption(newStringOptions, setNewStringOptions, '')
- }
onRemove={(id) =>
- removeOption(newStringOptions, setNewStringOptions, id)
+ removeOption(
+ newStringOptions,
+ setNewStringOptions,
+ id,
+ ''
+ )
}
onUpdate={(id, value) =>
updateOption(
newStringOptions,
setNewStringOptions,
id,
- value as string
+ value as string,
+ ''
)
}
- placeholder="Enter option value"
+ placeholder="Option value"
/>
</Show>
</div>
- </Show>
- </div>
+ </EditorRow>
+ </Show>
</div>
+ </CommandMenuShell.Body>
- <div class="flex items-center justify-end gap-2 px-2 py-1.5 border-t border-edge-muted shrink-0">
+ <CommandMenuShell.Footer class="gap-2 border-t-0 py-3">
+ <div class="ml-auto flex items-center gap-2">
<Button
variant="ghost"
- class="rounded-xs"
- onClick={() => {
- resetCreateForm();
- props.onClose();
- }}
- disabled={createPropertyMutation.isPending}
+ size="sm"
+ class="rounded-lg"
+ onClick={close}
+ disabled={pending()}
>
Cancel
</Button>
<Button
- variant="base"
- class="rounded-xs"
+ variant={canSubmit() ? 'active' : 'ghost'}
+ depth={3}
+ class={cn('gap-3 rounded-lg border-0', pending() && 'gap-1.5')}
onClick={handleCreateProperty}
- disabled={
- !newPropertyName().trim() || createPropertyMutation.isPending
- }
+ disabled={!canSubmit()}
>
<Show
- when={!createPropertyMutation.isPending}
+ when={!pending()}
fallback={
- <div class="flex items-center gap-1.5">
- <div class="size-3 animate-spin">
+ <>
+ <span class="size-3 animate-spin">
<LoadingSpinner />
- </div>
- Creating...
- </div>
+ </span>
+ Creating
+ </>
}
>
- Create Property
+ Create
+ <Hotkey shortcut="cmd+enter" theme="current" />
</Show>
</Button>
</div>
- </div>
- </Surface>
+ </CommandMenuShell.Footer>
+ </CommandMenuShell>
</Dialog>
);
};
diff --git a/apps/web/src/features/property/component/modal/Modals.tsx b/apps/web/src/features/property/component/modal/Modals.tsx
index 45cad19755..bd6b92dbac 100644
--- a/apps/web/src/features/property/component/modal/Modals.tsx
+++ b/apps/web/src/features/property/component/modal/Modals.tsx
@@ -1,21 +1,13 @@
-import {
- type Component,
- createEffect,
- createMemo,
- createSignal,
-} from 'solid-js';
+import { type Component, createEffect, createSignal } from 'solid-js';
import { Show } from 'solid-js/web';
import { usePropertiesContext } from '../../context/PropertiesContext';
import { CreatePropertyModal } from './CreatePropertyModal';
-import { SelectPropertyModal } from './SelectPropertyModal';
export const Modals: Component = () => {
const {
onPropertyAdded,
properties,
- propertySelectorModal,
createPropertyModal,
- closePropertySelector,
closeCreateProperty,
onPropertyPinned,
} = usePropertiesContext();
@@ -39,10 +31,6 @@ export const Modals: Component = () => {
}
});
- const existingPropertyIds = createMemo(() => {
- return properties().map((prop) => prop.propertyDefinitionId);
- });
-
const handlePropertyCreated = (propertyDefinitionId?: string) => {
if (propertyDefinitionId) {
onPropertyAdded([propertyDefinitionId]);
@@ -54,25 +42,16 @@ export const Modals: Component = () => {
};
return (
- <>
- <Show when={propertySelectorModal()}>
- <SelectPropertyModal
+ <Show when={createPropertyModal()}>
+ {(state) => (
+ <CreatePropertyModal
isOpen={true}
- onClose={closePropertySelector}
- existingPropertyIds={existingPropertyIds}
+ onClose={closeCreateProperty}
+ onPropertyCreated={handlePropertyCreated}
+ autoPinOnCreate={state().autoPinOnCreate}
+ initialName={state().initialName}
/>
- </Show>
-
- <Show when={createPropertyModal()}>
- {(state) => (
- <CreatePropertyModal
- isOpen={true}
- onClose={closeCreateProperty}
- onPropertyCreated={handlePropertyCreated}
- autoPinOnCreate={state().autoPinOnCreate}
- />
- )}
- </Show>
- </>
+ )}
+ </Show>
);
};
diff --git a/apps/web/src/features/property/component/modal/SelectPropertyModal.tsx b/apps/web/src/features/property/component/modal/SelectPropertyModal.tsx
deleted file mode 100644
index baced88e88..0000000000
--- a/apps/web/src/features/property/component/modal/SelectPropertyModal.tsx
+++ /dev/null
@@ -1,272 +0,0 @@
-import { useBlockId } from '@core/block';
-import { ENABLE_CREATE_PROPERTY } from '@core/constant/featureFlags';
-import { useListKeyBindings } from '@core/util/useListKeyBindings';
-import PlusIcon from '@phosphor/plus.svg';
-import LoadingSpinner from '@phosphor/spinner.svg';
-import { CRM_TEAM_STAGE_DEFINITION_NAME } from '@property/constants';
-import { useListPropertiesQuery } from '@queries/properties/definitions';
-import { useAddEntityPropertyMutation } from '@queries/properties/entity';
-import { useTagsQuery } from '@queries/properties/tags';
-import { cn, Dialog, Surface } from '@ui';
-import {
- createEffect,
- createMemo,
- createSelector,
- createSignal,
- For,
- Show,
-} from 'solid-js';
-import { usePropertiesContext } from '../../context/PropertiesContext';
-import { usePropertySelection } from '../../hooks/usePropertySelection';
-import type {
- PropertyDefinitionDomain,
- PropertySelectorProps,
-} from '../../types';
-import {
- getPropertyDefinitionTypeDisplay,
- PropertyDataTypeIcon,
- toPropertyDefinitionDomain,
- useSearchInputFocus,
-} from '../../utils';
-
-export function SelectPropertyModal(props: PropertySelectorProps) {
- const blockId = useBlockId();
- const { entityType, onPropertyAdded, openCreateProperty } =
- usePropertiesContext();
-
- const [searchQuery, setSearchQuery] = createSignal('');
- const [focusedIndex, setFocusedIndex] = createSignal(0);
-
- const [dialogRef, setDialogRef] = createSignal<HTMLDivElement | undefined>();
-
- const addMutation = useAddEntityPropertyMutation();
- const tagsQuery = useTagsQuery();
-
- const listPropertiesQuery = useListPropertiesQuery(() => ({
- scope: 'all',
- includeOptions: true,
- forEntityType: entityType,
- }));
-
- const availableProperties = createMemo((): PropertyDefinitionDomain[] => {
- if (
- listPropertiesQuery.isLoading ||
- listPropertiesQuery.isError ||
- !listPropertiesQuery.data
- ) {
- return [];
- }
-
- const data = listPropertiesQuery.data;
- const tagDefinitionIds = new Set(
- (tagsQuery.data ?? [])
- .map((set) => set.definition?.id)
- .filter((id): id is string => !!id)
- );
-
- const properties = Array.isArray(data) ? data : [];
- return properties
- .map((item) => {
- if ('definition' in item) {
- return toPropertyDefinitionDomain(
- item.definition,
- item.property_options || []
- );
- }
- return toPropertyDefinitionDomain(item);
- })
- .filter(
- // The CRM-managed team Stage definition must never surface in
- // property pickers. Tags have their own top-level sidepanel section
- // and picker, so exclude the backing tag definitions here too. The
- // value-type check covers the initial render before the tags query
- // has returned definition ids.
- (property) =>
- property.valueType !== 'TAG' &&
- !tagDefinitionIds.has(property.id) &&
- !(
- property.displayName === CRM_TEAM_STAGE_DEFINITION_NAME &&
- !property.isSystem
- )
- );
- });
-
- let searchInputRef!: HTMLInputElement;
-
- const { filteredProperties } = usePropertySelection(
- props.existingPropertyIds,
- availableProperties,
- () => searchQuery()
- );
-
- const createLabel = createMemo(() => {
- const query = searchQuery().trim();
- return query ? `Create Property "${query}"` : 'Create New Property';
- });
-
- const createIndex = createMemo(() => filteredProperties().length);
-
- const canCreateProperty = ENABLE_CREATE_PROPERTY;
-
- const addProperty = async (propertyDefinitionId: string) => {
- try {
- await addMutation.mutateAsync({
- entityId: blockId,
- entityType,
- propertyDefinitionId,
- });
- onPropertyAdded([propertyDefinitionId]);
- } catch {
- // Error toast is shown by mutation's onError callback
- } finally {
- props.onClose();
- }
- };
-
- const handleCreate = () => {
- props.onClose();
- openCreateProperty(true);
- };
-
- useSearchInputFocus(
- () => searchInputRef,
- () => props.isOpen && availableProperties().length > 0
- );
-
- createEffect(() => {
- if (props.isOpen) {
- setSearchQuery('');
- }
- });
-
- createEffect(() => {
- searchQuery();
- setFocusedIndex(0);
- });
-
- createEffect(() => {
- const index = focusedIndex();
- const elem = document.getElementById(`select-property-option-${index}`);
- if (elem) {
- elem.scrollIntoView({ block: 'nearest' });
- }
- });
-
- const setKeybindings = useListKeyBindings(dialogRef);
-
- createEffect(() => {
- const items = filteredProperties();
- const totalLen = canCreateProperty ? items.length + 1 : items.length; // +1 for Create row if enabled
- const noop = () => setFocusedIndex(0);
- setKeybindings({
- next:
- totalLen === 0
- ? noop
- : () => setFocusedIndex((prev) => (prev + 1) % totalLen),
- previous:
- totalLen === 0
- ? noop
- : () => setFocusedIndex((prev) => (prev - 1 + totalLen) % totalLen),
- select: () => {
- const idx = focusedIndex();
- if (canCreateProperty && idx >= items.length) {
- handleCreate();
- } else if (idx < items.length) {
- addProperty(items[idx].id);
- }
- },
- });
- });
-
- const isFocused = createSelector(focusedIndex);
-
- return (
- <Dialog
- open={props.isOpen}
- onOpenChange={(open) => {
- if (!open) props.onClose();
- }}
- contentRef={setDialogRef}
- >
- <Surface depth={2} class="*:max-h-[75vh] rounded-xl">
- <div class="flex flex-col text-sm">
- <div class="flex items-center gap-2 bg-surface px-2 h-10 border-b border-edge-muted shrink-0">
- <span class="pl-2 pointer-events-none text-ink-extra-muted">❯</span>
- <input
- ref={searchInputRef}
- type="text"
- value={searchQuery()}
- onInput={(e) => setSearchQuery(e.currentTarget.value)}
- placeholder="Add a property..."
- class="flex-1 text-base border-0 outline-none! focus:outline-none ring-0! focus:ring-0 bg-transparent"
- autofocus
- />
- </div>
-
- <div class="min-h-0 overflow-y-auto scrollbar-hidden">
- <Show
- when={!listPropertiesQuery.isLoading}
- fallback={
- <div class="flex items-center justify-center py-8">
- <div class="size-5 animate-spin">
- <LoadingSpinner />
- </div>
- <span class="ml-2 text-ink-muted">Loading properties...</span>
- </div>
- }
- >
- <div class="p-1">
- <For each={filteredProperties()}>
- {(property, index) => (
- <button
- type="button"
- id={`select-property-option-${index()}`}
- class={cn(
- 'flex flex-row w-full items-center gap-2 py-1.5 px-2 scroll-my-1',
- isFocused(index()) && 'bg-active'
- )}
- onClick={() => addProperty(property.id)}
- onMouseEnter={() => setFocusedIndex(index())}
- >
- <PropertyDataTypeIcon
- property={property}
- class="opacity-50 shrink-0"
- />
- <p class="text-sm font-medium truncate text-left grow">
- {property.displayName}
- </p>
- <p class="text-sm text-ink-extra-muted/50 shrink-0">
- {getPropertyDefinitionTypeDisplay({
- dataType: property.valueType,
- specificEntityType: property.specificEntityType,
- isMultiSelect: property.isMultiSelect,
- })}
- </p>
- </button>
- )}
- </For>
- <Show when={canCreateProperty}>
- <button
- type="button"
- id={`select-property-option-${createIndex()}`}
- class={cn(
- 'flex flex-row w-full items-center gap-2 py-1.5 px-2 scroll-my-1',
- isFocused(createIndex()) && 'bg-hover'
- )}
- onClick={handleCreate}
- onMouseEnter={() => setFocusedIndex(createIndex())}
- >
- <PlusIcon class="size-4 shrink-0" />
- <p class="text-sm font-medium truncate flex-1 text-left">
- {createLabel()}
- </p>
- </button>
- </Show>
- </div>
- </Show>
- </div>
- </div>
- </Surface>
- </Dialog>
- );
-}
diff --git a/apps/web/src/features/property/context/PropertiesContext.tsx b/apps/web/src/features/property/context/PropertiesContext.tsx
index 8d91ca2efc..5ce5debde1 100644
--- a/apps/web/src/features/property/context/PropertiesContext.tsx
+++ b/apps/web/src/features/property/context/PropertiesContext.tsx
@@ -8,13 +8,9 @@ import {
type ParentProps,
useContext,
} from 'solid-js';
+import { openPropertyEditor } from '../editor/state/propertyEditor';
import type { Property, PropertyApiValues } from '../types';
-// Specific modal state types with proper typing
-interface PropertySelectorModalState {
- isOpen: boolean;
-}
-
interface DatePickerModalState {
property: Property & { valueType: 'DATE' };
anchor?: HTMLElement;
@@ -23,6 +19,7 @@ interface DatePickerModalState {
interface CreatePropertyModalState {
isOpen: boolean;
autoPinOnCreate?: boolean;
+ initialName?: string;
}
export interface PropertySaveHandler {
@@ -37,20 +34,21 @@ interface PropertiesContextValue {
properties: () => Property[];
onRefresh: () => void;
onPropertyAdded: (addedDefinitionIds?: string[]) => void;
+ onPropertyAddFailed?: (definitionId: string) => void;
onPropertyDeleted: () => void;
onPropertyPinned?: (propertyId: string) => void;
onPropertyUnpinned?: (propertyId: string) => void;
pinnedPropertyIds?: () => string[];
+ addProperty?: (propertyDefinitionId: string) => Promise<void>;
+ removeProperty?: (propertyId: string) => Promise<void>;
saveHandler: PropertySaveHandler;
// Specific modal state accessors
- propertySelectorModal: Accessor<PropertySelectorModalState | null>;
datePickerModal: Accessor<DatePickerModalState | null>;
createPropertyModal: Accessor<CreatePropertyModalState | null>;
// Specific modal actions
openPropertySelector: () => void;
- closePropertySelector: () => void;
openDatePicker: (
property: Property & { valueType: 'DATE' },
@@ -58,7 +56,7 @@ interface PropertiesContextValue {
) => void;
closeDatePicker: () => void;
- openCreateProperty: (autoPinOnCreate?: boolean) => void;
+ openCreateProperty: (autoPinOnCreate?: boolean, initialName?: string) => void;
closeCreateProperty: () => void;
// Convenience function to close all modals
@@ -66,16 +64,20 @@ interface PropertiesContextValue {
}
interface PropertiesProviderProps extends ParentProps {
+ entityId?: string;
entityType: EntityType;
canEdit: boolean;
documentName?: string;
properties: () => Property[];
onRefresh: () => void;
onPropertyAdded: (addedDefinitionIds?: string[]) => void;
+ onPropertyAddFailed?: (definitionId: string) => void;
onPropertyDeleted: () => void;
onPropertyPinned?: (propertyId: string) => void;
onPropertyUnpinned?: (propertyId: string) => void;
pinnedPropertyIds?: () => string[];
+ addProperty?: (propertyDefinitionId: string) => Promise<void>;
+ removeProperty?: (propertyId: string) => Promise<void>;
saveHandler: PropertySaveHandler;
}
@@ -83,8 +85,6 @@ const PropertiesContext = createContext<PropertiesContextValue>();
export function PropertiesProvider(props: PropertiesProviderProps) {
// Modal state signals
- const [propertySelectorModal, setPropertySelectorModal] =
- createSignal<PropertySelectorModalState | null>(null);
const [datePickerModal, setDatePickerModal] =
createSignal<DatePickerModalState | null>(null);
const [createPropertyModal, setCreatePropertyModal] =
@@ -92,11 +92,49 @@ export function PropertiesProvider(props: PropertiesProviderProps) {
// Property Selector actions
const openPropertySelector = () => {
- setPropertySelectorModal({ isOpen: true });
- };
-
- const closePropertySelector = () => {
- setPropertySelectorModal(null);
+ if (!props.canEdit) return;
+ if (!props.entityId) return;
+ openPropertyEditor(
+ [
+ {
+ id: props.entityId,
+ name: props.documentName ?? 'Entity',
+ entityType: props.entityType,
+ },
+ ],
+ 'selector',
+ undefined,
+ {
+ onPropertyAdded: async (definitionIds) => {
+ if (!definitionIds?.length) {
+ props.onPropertyAdded();
+ return;
+ }
+
+ for (const definitionId of definitionIds) {
+ const existingProperty = props
+ .properties()
+ .find(
+ (property) => property.propertyDefinitionId === definitionId
+ );
+
+ if (existingProperty) {
+ props.onPropertyPinned?.(existingProperty.propertyId);
+ continue;
+ }
+
+ props.onPropertyAdded([definitionId]);
+ try {
+ await props.addProperty?.(definitionId);
+ props.onPropertyAdded([definitionId]);
+ } catch (error) {
+ props.onPropertyAddFailed?.(definitionId);
+ console.error('Failed to add property to entity', error);
+ }
+ }
+ },
+ }
+ );
};
// Date Picker actions
@@ -112,8 +150,11 @@ export function PropertiesProvider(props: PropertiesProviderProps) {
};
// Create Property actions
- const openCreateProperty = (autoPinOnCreate?: boolean) => {
- setCreatePropertyModal({ isOpen: true, autoPinOnCreate });
+ const openCreateProperty = (
+ autoPinOnCreate?: boolean,
+ initialName?: string
+ ) => {
+ setCreatePropertyModal({ isOpen: true, autoPinOnCreate, initialName });
};
const closeCreateProperty = () => {
@@ -122,7 +163,6 @@ export function PropertiesProvider(props: PropertiesProviderProps) {
// Convenience function to close all modals
const closeAllModals = () => {
- setPropertySelectorModal(null);
setDatePickerModal(null);
setCreatePropertyModal(null);
};
@@ -131,9 +171,7 @@ export function PropertiesProvider(props: PropertiesProviderProps) {
// Use capture phase listener to intercept before hotkey system's capture phase handlers
createEffect(() => {
const isAnyModalOpen =
- propertySelectorModal() !== null ||
- datePickerModal() !== null ||
- createPropertyModal() !== null;
+ datePickerModal() !== null || createPropertyModal() !== null;
let handleKeyDown: (e: KeyboardEvent) => void;
@@ -168,18 +206,19 @@ export function PropertiesProvider(props: PropertiesProviderProps) {
properties: props.properties,
onRefresh: props.onRefresh,
onPropertyAdded: props.onPropertyAdded,
+ onPropertyAddFailed: props.onPropertyAddFailed,
onPropertyDeleted: props.onPropertyDeleted,
onPropertyPinned: props.onPropertyPinned,
onPropertyUnpinned: props.onPropertyUnpinned,
pinnedPropertyIds: props.pinnedPropertyIds,
+ addProperty: props.addProperty,
+ removeProperty: props.removeProperty,
saveHandler: props.saveHandler,
// Specific modal state
- propertySelectorModal,
datePickerModal,
createPropertyModal,
// Specific modal actions
openPropertySelector,
- closePropertySelector,
openDatePicker,
closeDatePicker,
openCreateProperty,
@@ -203,3 +242,7 @@ export function usePropertiesContext() {
}
return context;
}
+
+export function useMaybePropertiesContext() {
+ return useContext(PropertiesContext);
+}
diff --git a/apps/web/src/features/property/editor/PropertyEditorModal.tsx b/apps/web/src/features/property/editor/PropertyEditorModal.tsx
index 2680cb05b5..fc4f18d44a 100644
--- a/apps/web/src/features/property/editor/PropertyEditorModal.tsx
+++ b/apps/web/src/features/property/editor/PropertyEditorModal.tsx
@@ -9,12 +9,13 @@ import {
type ListNavActions,
useListKeyBindings,
} from '@core/util/useListKeyBindings';
-import { type EntityData, InlineEntity } from '@entity';
+import { type EntityData, InlineEntity, isTaskEntity } from '@entity';
import CircleDashedEmpty from '@phosphor/circle-dashed.svg';
import PencilIcon from '@phosphor/pencil-simple.svg';
import PropertiesIcon from '@phosphor/sliders-horizontal.svg';
import TagIcon from '@phosphor/tag-simple.svg';
import { type CombinedEntity, getEntityName, getEntityType } from '@property';
+import { CreatePropertyModal } from '@property/component/modal/CreatePropertyModal';
import { PropertyValueIcon } from '@property/component/propertyValue';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import { OptionCheckBox } from '@property/editors/selectors/OptionCheckBox';
@@ -35,7 +36,9 @@ import {
macroEntityToPropertyEntityType,
PropertyDataTypeIcon,
toPropertyApiValue,
+ toPropertyDefinitionDomain,
} from '@property/utils';
+import { fetchPropertyDefinitionWithOptions } from '@queries/properties/definitions';
import {
useBulkUpdateEntityPropertyOptionsMutation,
useEntityPropertiesQuery,
@@ -44,16 +47,18 @@ import { useTagsQuery } from '@queries/properties/tags';
import { useCurrentTeamQuery } from '@queries/team/teams';
import type { EntityReference } from '@service-properties/generated/schemas/entityReference';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
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 { mergeRefs } from '@solid-primitives/refs';
import {
CommandMenuEmptyState,
- CommandMenuListItem,
+ CommandMenuList,
CommandMenuSearchInput,
CommandMenuShell,
cn,
+ createCommandListController,
Dialog,
Hotkey,
} from '@ui';
@@ -61,10 +66,8 @@ import {
type Accessor,
createEffect,
createMemo,
- createSelector,
createSignal,
For,
- type JSX,
Match,
on,
onCleanup,
@@ -78,6 +81,9 @@ import { useEntitiesForProperty } from './hooks/useEntitiesForProperty';
import { useSavePropertyForMultiEntitites } from './hooks/useSaveProperties';
import {
closePropertyEditor,
+ hasPropertyEditorPropertyAddedHandler,
+ notifyPropertyEditorPropertyAdded,
+ type PropertyEditorEntity,
propertyEditorOpen,
propertyEditorState,
setPropertyEditorMode,
@@ -85,32 +91,6 @@ import {
togglePropertyEditor,
} from './state/propertyEditor';
-/* Styled wrapper for list items in each menu. */
-function ListItem(props: {
- id: string;
- isSelected: boolean;
- as?: 'button' | 'div';
- disabled?: boolean;
- onClick: (event: MouseEvent) => void;
- onMouseEnter: () => void;
- children: JSX.Element;
- class?: string;
-}) {
- return (
- <CommandMenuListItem
- as={props.as}
- id={props.id}
- selected={props.isSelected}
- disabled={props.disabled}
- onClick={props.onClick}
- onMouseMove={props.onMouseEnter}
- class={props.class}
- >
- {props.children}
- </CommandMenuListItem>
- );
-}
-
type TagOptionItem = {
scope: TagScope;
definition: PropertyDefinitionDetailResponse;
@@ -141,7 +121,7 @@ function tagDefinitionDomain(
}
function entityTagIdsByDefinition(
- entities: EntityData[],
+ entities: PropertyEditorEntity[],
fetchedProperties?: { entityId: string; properties: Property[] }
): EntityTagIdsByDefinition {
const byEntity = new Map<string, Map<string, string[]>>();
@@ -190,45 +170,131 @@ function docTagIdsByDefinition(
return new Map([[entityId, byDefinition]]);
}
-function tagAssignmentEntityType(entity: EntityData): EntityType {
- return getEntityType({ kind: 'entity', id: entity.id, data: entity });
+function propertyIdentity(property: Property | PropertyDefinitionDomain) {
+ return 'propertyDefinitionId' in property
+ ? property.propertyDefinitionId
+ : property.id;
}
-function canAssignTags(entity: EntityData): boolean {
+function selectedOptionIds(
+ property: Property | PropertyDefinitionDomain
+): Set<string> {
+ if (!('value' in property)) return new Set();
+ if (
+ property.valueType !== 'SELECT_STRING' &&
+ property.valueType !== 'SELECT_NUMBER'
+ ) {
+ return new Set();
+ }
+
+ return new Set(property.value ?? []);
+}
+
+function selectedEntityRefs(
+ property: Property | PropertyDefinitionDomain
+): EntityReference[] {
+ if (!('value' in property) || property.valueType !== 'ENTITY') return [];
+ return property.value ?? [];
+}
+
+function propertyEditorEntityType(entity: PropertyEditorEntity): EntityType {
+ if ('entityType' in entity) return entity.entityType;
+ if (isTaskEntity(entity)) return 'TASK';
+ return macroEntityToPropertyEntityType(entity);
+}
+
+function canAssignTags(entity: PropertyEditorEntity): boolean {
try {
- macroEntityToPropertyEntityType(entity);
+ propertyEditorEntityType(entity);
return true;
} catch {
return false;
}
}
+function propertyEditorEntityName(entity: PropertyEditorEntity): string {
+ return entity.name || 'Entity';
+}
+
export function PropertyEditorModal() {
const [dialogRef, setDialogRef] = createSignal<HTMLElement | undefined>();
const [attach, hotkeyScope] = useHotkeyDOMScope('property-editor');
const [searchValue, setSearchValue] = createSignal('');
const [selectedIndex, setSelectedIndex] = createSignal(0);
const [inputType, setInputType] = createSignal<'text' | 'number'>('text');
+ const [createPropertyInitialName, setCreatePropertyInitialName] =
+ createSignal<string | null>(null);
const defaultPlaceholder = 'Choose a property...';
const [placeholder, setPlaceholder] = createSignal('');
const saveProperties = useSavePropertyForMultiEntitites();
-
- const handlePropertySave = (value: PropertyApiValues) => {
+ const handlePropertySave = (
+ value: PropertyApiValues,
+ event?: KeyboardEvent | MouseEvent
+ ) => {
const { selectedEntities, targetProperty } = propertyEditorState;
if (!selectedEntities.length || !targetProperty) return;
// Snapshot before closing — closing resets selectedEntities.
const count = selectedEntities.length;
const message = `Set ${targetProperty.displayName} for ${
- count === 1 ? selectedEntities[0].name : count + ' entities'
+ count === 1
+ ? propertyEditorEntityName(selectedEntities[0])
+ : count + ' entities'
}`;
saveProperties(selectedEntities, targetProperty, value).then((success) => {
if (success) toast.success(message);
});
- closePropertyEditor();
+ if (!event?.shiftKey) closePropertyEditor();
+ };
+
+ const openCreateProperty = (initialName: string) => {
+ setCreatePropertyInitialName(initialName);
+ };
+
+ const handlePropertyCreated = async (
+ _propertyDefinitionId?: string,
+ propertyDefinition?: PropertyDefinition
+ ) => {
+ setCreatePropertyInitialName(null);
+ if (!propertyDefinition) return;
+
+ const createdDefinitionId = propertyDefinition.id;
+ const shouldNotifySelectedEntity = Boolean(
+ hasPropertyEditorPropertyAddedHandler() &&
+ propertyEditorState.selectedEntities.length === 1
+ );
+
+ if (shouldNotifySelectedEntity) {
+ try {
+ await notifyPropertyEditorPropertyAdded([createdDefinitionId]);
+ } catch (error) {
+ console.error('Failed to add created property to entity', error);
+ }
+ }
+
+ try {
+ const propertyWithOptions =
+ await fetchPropertyDefinitionWithOptions(createdDefinitionId);
+
+ if (propertyWithOptions && 'definition' in propertyWithOptions) {
+ setPropertyEditorMode('direct');
+ setPropertyEditorTarget(
+ toPropertyDefinitionDomain(
+ propertyWithOptions.definition,
+ propertyWithOptions.property_options
+ )
+ );
+ return;
+ }
+ } catch (error) {
+ console.error('Failed to fetch created property options', error);
+ }
+
+ setPropertyEditorMode('direct');
+ setPropertyEditorTarget(toPropertyDefinitionDomain(propertyDefinition));
};
const { dispose: disposeHotkey } = registerHotkey({
@@ -251,10 +317,6 @@ export function PropertyEditorModal() {
})
);
- const setSelectedIndexFromMouse = (index: number) => {
- setSelectedIndex(index);
- };
-
const keybindings = useListKeyBindings(() => dialogRef());
return (
@@ -290,8 +352,18 @@ export function PropertyEditorModal() {
searchTerm={searchValue()}
focusedIndex={selectedIndex}
setFocusedIndex={setSelectedIndex}
- setFocusedIndexFromMouse={setSelectedIndexFromMouse}
setKeybindings={keybindings}
+ onCreateProperty={openCreateProperty}
+ onPropertySelected={async (property) => {
+ if (
+ hasPropertyEditorPropertyAddedHandler() &&
+ propertyEditorState.selectedEntities.length === 1
+ ) {
+ await notifyPropertyEditorPropertyAdded([
+ propertyIdentity(property),
+ ]);
+ }
+ }}
/>
</div>
</Match>
@@ -302,11 +374,11 @@ export function PropertyEditorModal() {
setSearchValue={setSearchValue}
selectedIndex={selectedIndex}
setSelectedIndex={setSelectedIndex}
- setSelectedIndexFromMouse={setSelectedIndexFromMouse}
setKeybindings={keybindings}
setPlaceholder={setPlaceholder}
setInputType={setInputType}
onSave={handlePropertySave}
+ selectedEntities={propertyEditorState.selectedEntities}
/>
</Match>
<Match when={propertyEditorState.mode === 'tag'}>
@@ -315,7 +387,6 @@ export function PropertyEditorModal() {
searchValue={searchValue}
selectedIndex={selectedIndex}
setSelectedIndex={setSelectedIndex}
- setSelectedIndexFromMouse={setSelectedIndexFromMouse}
setKeybindings={keybindings}
setPlaceholder={setPlaceholder}
/>
@@ -323,6 +394,17 @@ export function PropertyEditorModal() {
</Switch>
</CommandMenuShell.Body>
</CommandMenuShell>
+ <Show when={createPropertyInitialName()}>
+ {(initialName) => (
+ <CreatePropertyModal
+ isOpen
+ initialName={initialName()}
+ autoPinOnCreate={false}
+ onClose={() => setCreatePropertyInitialName(null)}
+ onPropertyCreated={handlePropertyCreated}
+ />
+ )}
+ </Show>
</Dialog>
);
}
@@ -364,11 +446,13 @@ function PropertyList(props: {
searchTerm: string;
focusedIndex: Accessor<number>;
setFocusedIndex: Setter<number>;
- setFocusedIndexFromMouse: (index: number) => void;
setKeybindings: (navAction: ListNavActions) => void;
+ onCreateProperty: (initialName: string) => void;
+ onPropertySelected?: (
+ property: Property | PropertyDefinitionDomain
+ ) => void | Promise<void>;
}) {
const properties = useAllProperties();
- let containerRef: HTMLDivElement | undefined;
const { filteredProperties } = usePropertySelection(
() => [],
@@ -377,67 +461,103 @@ function PropertyList(props: {
);
const showTagAssignmentOption = createMemo(() => {
+ if (hasPropertyEditorPropertyAddedHandler()) return false;
+
const query = props.searchTerm.toLowerCase().trim();
return (
propertyEditorState.selectedEntities.every(canAssignTags) &&
(!query || 'tags'.includes(query) || 'label'.includes(query))
);
});
+ const createPropertyName = () => props.searchTerm.trim();
+ const exactPropertyMatchExists = () => {
+ const name = createPropertyName().toLowerCase();
+ if (!name) return false;
+ return properties().some(
+ (property) => property.displayName.trim().toLowerCase() === name
+ );
+ };
+ const showCreatePropertyOption = () =>
+ createPropertyName().length > 0 && !exactPropertyMatchExists();
const rowCount = () =>
- filteredProperties().length + (showTagAssignmentOption() ? 1 : 0);
+ filteredProperties().length +
+ (showTagAssignmentOption() ? 1 : 0) +
+ (showCreatePropertyOption() ? 1 : 0);
+
+ type PropertyListRow =
+ | { type: 'create'; name: string }
+ | { type: 'tags' }
+ | { type: 'property'; property: Property | PropertyDefinitionDomain };
+
+ const rows = createMemo(() => {
+ const nextRows: PropertyListRow[] = [];
+
+ if (showTagAssignmentOption()) {
+ nextRows.push({ type: 'tags' });
+ }
+
+ for (const property of filteredProperties()) {
+ nextRows.push({ type: 'property', property });
+ }
+
+ if (showCreatePropertyOption()) {
+ nextRows.push({ type: 'create', name: createPropertyName() });
+ }
+
+ return nextRows;
+ });
createEffect(() => {
props.searchTerm;
props.setFocusedIndex(0);
});
+ const setProperty = async (property: Property | PropertyDefinitionDomain) => {
+ await props.onPropertySelected?.(property);
+ setPropertyEditorMode('direct');
+ setPropertyEditorTarget(property);
+ };
+
+ const selectRow = async (row: PropertyListRow) => {
+ if (row.type === 'create') {
+ props.onCreateProperty(row.name);
+ return;
+ }
+
+ if (row.type === 'tags') {
+ setPropertyEditorMode('tag');
+ return;
+ }
+
+ await setProperty(row.property);
+ };
+
+ const listController = createCommandListController({
+ items: rows,
+ selectedIndex: props.focusedIndex,
+ setSelectedIndex: props.setFocusedIndex,
+ onSelect: selectRow,
+ });
+
props.setKeybindings({
+ select: () => {
+ void listController.selectSelected();
+ },
next: () => {
- const len = rowCount();
- if (len === 0) return;
- props.setFocusedIndex((prev) => (prev + 1) % len);
+ listController.selectNext();
},
previous: () => {
- const len = rowCount();
- if (len === 0) return;
- props.setFocusedIndex((prev) => (prev - 1 + len) % len);
+ listController.selectPrevious();
},
- select: () => {
- if (showTagAssignmentOption() && props.focusedIndex() === 0) {
- setPropertyEditorMode('tag');
- return;
- }
-
- const focusedProperty =
- filteredProperties()[
- props.focusedIndex() - (showTagAssignmentOption() ? 1 : 0)
- ];
- if (focusedProperty) {
- setProperty(focusedProperty);
- }
- },
- });
-
- createEffect(() => {
- const index = props.focusedIndex();
- const elem = document.getElementById(
- showTagAssignmentOption() && index === 0
- ? 'property-editor-option-tags'
- : `property-editor-option-${index}`
- );
- if (elem) {
- elem.scrollIntoView({ block: 'nearest' });
- }
});
- const setProperty = (property: Property | PropertyDefinitionDomain) => {
- setPropertyEditorMode('direct');
- setPropertyEditorTarget(property);
+ const rowId = (row: PropertyListRow, index: number) => {
+ if (row.type === 'create') return 'property-editor-option-create';
+ if (row.type === 'tags') return 'property-editor-option-tags';
+ return `property-editor-option-${index}`;
};
- const selector = createSelector(props.focusedIndex);
-
return (
<Show
when={rowCount() > 0}
@@ -447,52 +567,53 @@ function PropertyList(props: {
</CommandMenuEmptyState>
}
>
- <div
- ref={containerRef}
- class="max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden p-2"
+ <CommandMenuList
+ items={rows()}
+ selectedIndex={props.focusedIndex()}
+ scrollSelectedIntoView={listController.shouldScrollSelectedIntoView()}
+ itemId={rowId}
+ onSelect={selectRow}
+ onItemMouseMove={(index) =>
+ listController.setSelectedIndexFromPointer(index)
+ }
>
- <Show when={showTagAssignmentOption()}>
- <ListItem
- id="property-editor-option-tags"
- isSelected={selector(0)}
- onClick={() => setPropertyEditorMode('tag')}
- onMouseEnter={() => props.setFocusedIndexFromMouse(0)}
- class="scroll-m-2"
- >
- <TagIcon class="size-4 text-ink-muted opacity-50" />
- <div class="flex-1 text-left flex">
- <p class="text-sm font-medium">Tags</p>
- </div>
- </ListItem>
- </Show>
- <For each={filteredProperties()}>
- {(property, index) => (
- <ListItem
- id={`property-editor-option-${index() + (showTagAssignmentOption() ? 1 : 0)}`}
- isSelected={selector(
- index() + (showTagAssignmentOption() ? 1 : 0)
- )}
- onClick={() => setProperty(property)}
- onMouseEnter={() =>
- props.setFocusedIndexFromMouse(
- index() + (showTagAssignmentOption() ? 1 : 0)
- )
- }
- class="scroll-m-2"
- >
- <PropertyDataTypeIcon property={property} class="opacity-50" />
+ {(row) => (
+ <Switch>
+ <Match when={row.type === 'create'}>
+ <PencilIcon class="size-4 text-ink-muted opacity-50" />
<div class="flex-1 text-left flex">
- <p class="text-sm font-medium">{property.displayName}</p>
+ <p class="text-sm font-medium">
+ Create property "{createPropertyName()}"
+ </p>
</div>
- </ListItem>
- )}
- </For>
- </div>
+ </Match>
+ <Match when={row.type === 'tags'}>
+ <TagIcon class="size-4 text-ink-muted opacity-50" />
+ <div class="flex-1 text-left flex">
+ <p class="text-sm font-medium">Tags</p>
+ </div>
+ </Match>
+ <Match when={row.type === 'property' && row.property}>
+ {(property) => (
+ <>
+ <PropertyDataTypeIcon
+ property={property()}
+ class="opacity-50"
+ />
+ <div class="flex-1 text-left flex">
+ <p class="text-sm font-medium">{property().displayName}</p>
+ </div>
+ </>
+ )}
+ </Match>
+ </Switch>
+ )}
+ </CommandMenuList>
</Show>
);
}
-function EditingEntityPreview(props: { entities: EntityData[] }) {
+function EditingEntityPreview(props: { entities: PropertyEditorEntity[] }) {
const displayEntities = () => props.entities.slice(0, 2);
const remainingCount = () => Math.max(0, props.entities.length - 2);
return (
@@ -508,7 +629,12 @@ function EditingEntityPreview(props: { entities: EntityData[] }) {
}
)}
>
- <InlineEntity entity={entity} />
+ <Show
+ when={!('entityType' in entity)}
+ fallback={propertyEditorEntityName(entity)}
+ >
+ <InlineEntity entity={entity as EntityData} />
+ </Show>
</div>
);
}}
@@ -523,11 +649,10 @@ function EditingEntityPreview(props: { entities: EntityData[] }) {
}
function TagAssignmentEditor(props: {
- entities: EntityData[];
+ entities: PropertyEditorEntity[];
searchValue: Accessor<string>;
selectedIndex: Accessor<number>;
setSelectedIndex: Setter<number>;
- setSelectedIndexFromMouse: (index: number) => void;
setKeybindings: (binding: ListNavActions) => void;
setPlaceholder: Setter<string>;
}) {
@@ -552,7 +677,7 @@ function TagAssignmentEditor(props: {
const singleDocTags = singleEntityForDocTags
? useDocTags(
singleEntityForDocTags.id,
- tagAssignmentEntityType(singleEntityForDocTags)
+ propertyEditorEntityType(singleEntityForDocTags)
)
: undefined;
const singleDocTagsSource = () =>
@@ -684,21 +809,49 @@ function TagAssignmentEditor(props: {
const showClearAllRow = () => hadAnyAppliedTagsWhenOpened();
const showClearAllAtTop = () => showClearAllRow() && !hasSearch();
const showClearAllAtBottom = () => showClearAllRow() && hasSearch();
- const itemRowIndex = (index: number) => index + (showClearAllAtTop() ? 1 : 0);
- const createRowIndex = () =>
- filteredItems().length + (showClearAllAtTop() ? 1 : 0);
- const clearAllRowIndex = () =>
- showClearAllAtTop()
- ? 0
- : filteredItems().length + (showCreateRow() ? 1 : 0);
- const rowCount = () =>
- filteredItems().length +
- (showClearAllRow() ? 1 : 0) +
- (showCreateRow() ? 1 : 0);
const selectedGroupSize = createMemo(
() => filteredItems().filter(wasFullyAppliedWhenOpened).length
);
+ type TagAssignmentRow =
+ | { type: 'clear'; separatorBefore: boolean }
+ | { type: 'tag'; item: TagOptionItem; separatorBefore: boolean }
+ | { type: 'create'; separatorBefore: boolean };
+
+ const rows = createMemo(() => {
+ const nextRows: TagAssignmentRow[] = [];
+
+ if (showClearAllAtTop()) {
+ nextRows.push({ type: 'clear', separatorBefore: false });
+ }
+
+ for (const [index, item] of filteredItems().entries()) {
+ nextRows.push({
+ type: 'tag',
+ item,
+ separatorBefore: index === selectedGroupSize() && index > 0,
+ });
+ }
+
+ if (showCreateRow()) {
+ nextRows.push({
+ type: 'create',
+ separatorBefore: filteredItems().length > 0,
+ });
+ }
+
+ if (showClearAllAtBottom()) {
+ nextRows.push({
+ type: 'clear',
+ separatorBefore: filteredItems().length > 0 || showCreateRow(),
+ });
+ }
+
+ return nextRows;
+ });
+
+ const rowCount = () => rows().length;
+
createEffect(() => {
props.searchValue();
props.setSelectedIndex(0);
@@ -763,7 +916,7 @@ function TagAssignmentEditor(props: {
try {
const update = Promise.all(
props.entities.map(async (entity) => {
- const entityType = tagAssignmentEntityType(entity);
+ const entityType = propertyEditorEntityType(entity);
const current = getTagIds(
previousTagIds,
entity.id,
@@ -855,7 +1008,7 @@ function TagAssignmentEditor(props: {
try {
const updates: Promise<unknown>[] = [];
for (const entity of props.entities) {
- const entityType = tagAssignmentEntityType(entity);
+ const entityType = propertyEditorEntityType(entity);
const byDefinition = previousTagIds.get(entity.id) ?? new Map();
const properties = [...byDefinition].flatMap(
([definitionId, optionIds]) => {
@@ -930,7 +1083,7 @@ function TagAssignmentEditor(props: {
try {
await Promise.all(
props.entities.map(async (entity) => {
- const entityType = tagAssignmentEntityType(entity);
+ const entityType = propertyEditorEntityType(entity);
const current = getTagIds(previousTagIds, entity.id, definition.id);
if (current.includes(optionId)) return;
@@ -954,48 +1107,42 @@ function TagAssignmentEditor(props: {
}
};
+ const selectRow = (
+ row: TagAssignmentRow,
+ event?: KeyboardEvent | MouseEvent
+ ) => {
+ if (row.type === 'clear') {
+ void clearAllTags(event);
+ return;
+ }
+
+ if (row.type === 'create') {
+ openCreateTag();
+ return;
+ }
+
+ void toggleTag(row.item, event);
+ };
+
+ const listController = createCommandListController({
+ items: rows,
+ selectedIndex: props.selectedIndex,
+ setSelectedIndex: props.setSelectedIndex,
+ });
+
props.setKeybindings({
next: () => {
- const len = rowCount();
- if (len === 0) return;
- props.setSelectedIndex((prev) => (prev + 1) % len);
+ listController.selectNext();
},
previous: () => {
- const len = rowCount();
- if (len === 0) return;
- props.setSelectedIndex((prev) => (prev - 1 + len) % len);
+ listController.selectPrevious();
},
select: (event) => {
- if (showClearAllRow() && props.selectedIndex() === clearAllRowIndex()) {
- void clearAllTags(event);
- return;
- }
-
- if (showCreateRow() && props.selectedIndex() === createRowIndex()) {
- openCreateTag();
- return;
- }
-
- const item =
- filteredItems()[props.selectedIndex() - (showClearAllAtTop() ? 1 : 0)];
- if (item) void toggleTag(item, event);
+ const row = rows()[props.selectedIndex()];
+ if (row) selectRow(row, event);
},
});
- const selector = createSelector(props.selectedIndex);
- const renderClearAllRow = () => (
- <ListItem
- id={`tag-assignment-option-${clearAllRowIndex()}`}
- isSelected={selector(clearAllRowIndex())}
- onClick={(event) => void clearAllTags(event)}
- onMouseEnter={() => props.setSelectedIndexFromMouse(clearAllRowIndex())}
- class="scroll-m-2"
- >
- <CircleDashedEmpty class="size-4 text-ink-muted opacity-50" />
- <span class="min-w-0 flex-1 truncate text-ink-muted">Clear all tags</span>
- </ListItem>
- );
-
return (
<Show
when={!tagsQuery.isLoading}
@@ -1011,84 +1158,73 @@ function TagAssignmentEditor(props: {
</CommandMenuEmptyState>
}
>
- <div class="max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden p-2">
- <Show when={showClearAllAtTop()}>{renderClearAllRow()}</Show>
- <For each={filteredItems()}>
- {(item, index) => (
- <>
- <Show
- when={
- index() === selectedGroupSize() && selectedGroupSize() > 0
- }
- >
- <div class="mx-2 my-1 h-px bg-edge-muted/50" />
- </Show>
- <ListItem
- as="div"
- id={`tag-assignment-option-${itemRowIndex(index())}`}
- isSelected={selector(itemRowIndex(index()))}
- onClick={(event) => void toggleTag(item, event)}
- onMouseEnter={() =>
- props.setSelectedIndexFromMouse(itemRowIndex(index()))
- }
- class="scroll-m-2"
- >
- <OptionCheckBox checked={isFullyApplied(item)} multiselect />
- <TagDot color={item.option.color ?? undefined} />
- <span class="min-w-0 flex-1 truncate">
- {tagOptionLabel(item.option)}
- </span>
- <Show when={item.scope === 'team'}>
- <span class="max-w-30 shrink-0 truncate rounded-full border border-ink/5 px-1.5 py-0.5 text-[10px] leading-none text-ink-extra-muted">
- {teamName()}
- </span>
- </Show>
- <button
- type="button"
- aria-label={`Edit ${tagOptionLabel(item.option)}`}
- class="ml-1 flex size-5 shrink-0 items-center justify-center rounded text-ink-extra-muted opacity-0 outline-none hover:bg-hover hover:text-ink group-hover:opacity-100 focus-visible:opacity-100"
- onMouseDown={(event) => {
- event.preventDefault();
- event.stopPropagation();
- }}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- openEditTag(item);
- }}
- >
- <PencilIcon class="size-3.5" />
- </button>
- </ListItem>
- </>
- )}
- </For>
- <Show when={showCreateRow()}>
- <Show when={filteredItems().length > 0}>
- <div class="mx-2 my-1 h-px bg-edge-muted/50" />
- </Show>
- <ListItem
- id={`tag-assignment-option-${createRowIndex()}`}
- isSelected={selector(createRowIndex())}
- onClick={openCreateTag}
- onMouseEnter={() =>
- props.setSelectedIndexFromMouse(createRowIndex())
- }
- class="scroll-m-2"
- >
- <TagIcon class="size-4 text-ink-muted opacity-50" />
- <span class="min-w-0 flex-1 truncate">
- Create new tag "{createLabel()}"
- </span>
- </ListItem>
- </Show>
- <Show when={showClearAllAtBottom()}>
- <Show when={filteredItems().length > 0 || showCreateRow()}>
+ <CommandMenuList
+ items={rows()}
+ selectedIndex={props.selectedIndex()}
+ scrollSelectedIntoView={listController.shouldScrollSelectedIntoView()}
+ itemId={(_, index) => `tag-assignment-option-${index}`}
+ beforeItem={(row) =>
+ row.separatorBefore ? (
<div class="mx-2 my-1 h-px bg-edge-muted/50" />
- </Show>
- {renderClearAllRow()}
- </Show>
- </div>
+ ) : null
+ }
+ onSelect={(row, _, event) => selectRow(row, event)}
+ onItemMouseMove={(index) =>
+ listController.setSelectedIndexFromPointer(index)
+ }
+ >
+ {(row) => (
+ <Switch>
+ <Match when={row.type === 'clear'}>
+ <CircleDashedEmpty class="size-4 text-ink-muted opacity-50" />
+ <span class="min-w-0 flex-1 truncate text-ink-muted">
+ Clear all tags
+ </span>
+ </Match>
+ <Match when={row.type === 'create'}>
+ <TagIcon class="size-4 text-ink-muted opacity-50" />
+ <span class="min-w-0 flex-1 truncate">
+ Create new tag "{createLabel()}"
+ </span>
+ </Match>
+ <Match when={row.type === 'tag' && row.item}>
+ {(item) => (
+ <>
+ <OptionCheckBox
+ checked={isFullyApplied(item())}
+ multiselect
+ />
+ <TagDot color={item().option.color ?? undefined} />
+ <span class="min-w-0 flex-1 truncate">
+ {tagOptionLabel(item().option)}
+ </span>
+ <Show when={item().scope === 'team'}>
+ <span class="max-w-30 shrink-0 truncate rounded-full border border-ink/5 px-1.5 py-0.5 text-[10px] leading-none text-ink-extra-muted">
+ {teamName()}
+ </span>
+ </Show>
+ <button
+ type="button"
+ aria-label={`Edit ${tagOptionLabel(item().option)}`}
+ class="ml-1 flex size-5 shrink-0 items-center justify-center rounded text-ink-extra-muted opacity-0 outline-none hover:bg-hover hover:text-ink group-hover:opacity-100 focus-visible:opacity-100"
+ onMouseDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openEditTag(item());
+ }}
+ >
+ <PencilIcon class="size-3.5" />
+ </button>
+ </>
+ )}
+ </Match>
+ </Switch>
+ )}
+ </CommandMenuList>
</Show>
<TagEditorDialog
open={tagEditorOpen()}
@@ -1129,13 +1265,39 @@ function PropertyValueEditor(props: {
setSearchValue: Setter<string>;
selectedIndex: Accessor<number>;
setSelectedIndex: Setter<number>;
- setSelectedIndexFromMouse: (index: number) => void;
setKeybindings: (binding: ListNavActions) => void;
setPlaceholder: Setter<string>;
setInputType: Setter<'text' | 'number'>;
- onSave: (apiValues: PropertyApiValues) => void;
+ onSave: (
+ apiValues: PropertyApiValues,
+ event?: KeyboardEvent | MouseEvent
+ ) => void;
+ selectedEntities: PropertyEditorEntity[];
}) {
const propertyType = () => props.property?.valueType;
+ const singleEntity = () =>
+ props.selectedEntities.length === 1 ? props.selectedEntities[0] : null;
+
+ const entityPropertiesQuery = useEntityPropertiesQuery(
+ () => {
+ const entity = singleEntity();
+ return entity ? propertyEditorEntityType(entity) : 'DOCUMENT';
+ },
+ () => singleEntity()?.id ?? '',
+ false
+ );
+
+ const resolvedProperty = createMemo(() => {
+ const property = props.property;
+ if (!property) return undefined;
+ if ('value' in property) return property;
+
+ return (
+ entityPropertiesQuery.data?.find(
+ (entityProperty) => entityProperty.propertyDefinitionId === property.id
+ ) ?? property
+ );
+ });
const handleSubmit = (
value: string | number | boolean | Date | EntityReference
@@ -1156,27 +1318,29 @@ function PropertyValueEditor(props: {
}
>
<SelectPropertyEditor
- property={props.property!}
+ property={resolvedProperty()!}
searchValue={props.searchValue}
selectedIndex={props.selectedIndex}
setSelectedIndex={props.setSelectedIndex}
- setSelectedIndexFromMouse={props.setSelectedIndexFromMouse}
onSubmit={handleSubmit}
setKeybindings={props.setKeybindings}
setPlaceholder={props.setPlaceholder}
+ selectedEntityCount={props.selectedEntities.length}
+ onSave={props.onSave}
/>
</Match>
<Match when={propertyType() === 'ENTITY'}>
<EntityPropertyEditor
- property={props.property}
+ property={resolvedProperty()}
searchValue={props.searchValue}
setSearchValue={props.setSearchValue}
selectedIndex={props.selectedIndex}
setSelectedIndex={props.setSelectedIndex}
- setSelectedIndexFromMouse={props.setSelectedIndexFromMouse}
onSubmit={handleSubmit}
setKeybindings={props.setKeybindings}
setPlaceholder={props.setPlaceholder}
+ selectedEntityCount={props.selectedEntities.length}
+ onSave={props.onSave}
/>
</Match>
<Match
@@ -1188,12 +1352,11 @@ function PropertyValueEditor(props: {
}
>
<DirectEditPropertyEditor
- property={props.property}
+ property={resolvedProperty()}
searchValue={props.searchValue}
setSearchValue={props.setSearchValue}
selectedIndex={props.selectedIndex}
setSelectedIndex={props.setSelectedIndex}
- setSelectedIndexFromMouse={props.setSelectedIndexFromMouse}
onSubmit={handleSubmit}
setKeybindings={props.setKeybindings}
setPlaceholder={props.setPlaceholder}
@@ -1214,11 +1377,27 @@ function SelectPropertyEditor(props: {
searchValue: Accessor<string>;
selectedIndex: Accessor<number>;
setSelectedIndex: Setter<number>;
- setSelectedIndexFromMouse: (index: number) => void;
onSubmit: (value: string) => void;
+ onSave: (
+ apiValues: PropertyApiValues,
+ event?: KeyboardEvent | MouseEvent
+ ) => void;
setKeybindings: (binding: ListNavActions) => void;
setPlaceholder: Setter<string>;
+ selectedEntityCount: number;
}) {
+ const [localSelectedIds, setLocalSelectedIds] = createSignal(
+ selectedOptionIds(props.property)
+ );
+ const [orderedSelectedIds, setOrderedSelectedIds] = createSignal(
+ selectedOptionIds(props.property)
+ );
+ let syncedPropertyId = propertyIdentity(props.property);
+ let syncedSelectionKey = [...selectedOptionIds(props.property)]
+ .sort()
+ .join('\0');
+ const [openOrderFrozen, setOpenOrderFrozen] = createSignal(false);
+
createEffect(() => {
if (props.property.isMultiSelect) {
props.setPlaceholder(
@@ -1229,6 +1408,32 @@ function SelectPropertyEditor(props: {
props.setPlaceholder(`Set ${props.property.displayName.toLowerCase()}...`);
});
+ createEffect(() => {
+ const propertyId = propertyIdentity(props.property);
+ const nextSelectedIds = selectedOptionIds(props.property);
+ const nextSelectionKey = [...nextSelectedIds].sort().join('\0');
+
+ if (propertyId !== syncedPropertyId) {
+ syncedPropertyId = propertyId;
+ syncedSelectionKey = nextSelectionKey;
+ setOpenOrderFrozen(false);
+ setLocalSelectedIds(nextSelectedIds);
+ setOrderedSelectedIds(nextSelectedIds);
+ return;
+ }
+
+ if (openOrderFrozen() || nextSelectionKey === syncedSelectionKey) return;
+
+ syncedSelectionKey = nextSelectionKey;
+ setLocalSelectedIds(nextSelectedIds);
+ setOrderedSelectedIds(nextSelectedIds);
+ });
+
+ const canGroupMultiValues = () =>
+ props.property.isMultiSelect &&
+ props.selectedEntityCount === 1 &&
+ 'value' in props.property;
+
const filteredOptions = createMemo(() => {
const options = props.property?.options || [];
const search = props.searchValue().trim();
@@ -1236,60 +1441,212 @@ function SelectPropertyEditor(props: {
return fuzzyFilter(search, options, (opt) => String(opt.value.value));
});
+ const orderedOptions = createMemo(() => {
+ if (!canGroupMultiValues()) return filteredOptions();
+
+ const selectedAtOpen = orderedSelectedIds();
+ const selected = filteredOptions().filter((option) =>
+ selectedAtOpen.has(option.id)
+ );
+ const remaining = filteredOptions().filter(
+ (option) => !selectedAtOpen.has(option.id)
+ );
+
+ return [...selected, ...remaining];
+ });
+
+ const selectedGroupSize = createMemo(() =>
+ canGroupMultiValues()
+ ? orderedOptions().filter((option) => orderedSelectedIds().has(option.id))
+ .length
+ : 0
+ );
+
+ const searchQuery = () => props.searchValue().trim();
+ const showClearAllRow = () =>
+ canGroupMultiValues() && orderedSelectedIds().size > 0;
+ const showClearAllAtTop = () => showClearAllRow() && !searchQuery();
+ const showClearAllAtBottom = () => showClearAllRow() && !!searchQuery();
+
+ type SelectPropertyRow =
+ | { type: 'clear'; separatorBefore: boolean }
+ | {
+ type: 'option';
+ option: NonNullable<
+ (Property | PropertyDefinitionDomain)['options']
+ >[number];
+ separatorBefore: boolean;
+ };
+
+ const rows = createMemo(() => {
+ const nextRows: SelectPropertyRow[] = [];
+
+ if (showClearAllAtTop()) {
+ nextRows.push({ type: 'clear', separatorBefore: false });
+ }
+
+ for (const [index, option] of orderedOptions().entries()) {
+ nextRows.push({
+ type: 'option',
+ option,
+ separatorBefore:
+ canGroupMultiValues() && index === selectedGroupSize() && index > 0,
+ });
+ }
+
+ if (showClearAllAtBottom()) {
+ nextRows.push({
+ type: 'clear',
+ separatorBefore: orderedOptions().length > 0,
+ });
+ }
+
+ return nextRows;
+ });
+
const shouldShowHotkeys = createMemo(() => {
- return !props.searchValue().trim() && filteredOptions().length <= 9;
+ return !props.searchValue().trim() && rows().length <= 9;
+ });
+
+ const buildApiValue = (
+ selectedIds: Set<string>
+ ): PropertyApiValues | null => {
+ if (
+ props.property.valueType !== 'SELECT_STRING' &&
+ props.property.valueType !== 'SELECT_NUMBER'
+ ) {
+ return null;
+ }
+
+ return {
+ valueType: props.property.valueType,
+ values: selectedIds.size > 0 ? [...selectedIds] : null,
+ };
+ };
+
+ const toggleOption = (
+ optionId: string,
+ event?: KeyboardEvent | MouseEvent
+ ) => {
+ if (!canGroupMultiValues()) {
+ props.onSubmit(optionId);
+ return;
+ }
+
+ const nextSelectedIds = new Set(localSelectedIds());
+ setOpenOrderFrozen(true);
+ if (nextSelectedIds.has(optionId)) {
+ nextSelectedIds.delete(optionId);
+ } else {
+ nextSelectedIds.add(optionId);
+ }
+
+ setLocalSelectedIds(nextSelectedIds);
+ const apiValue = buildApiValue(nextSelectedIds);
+ if (apiValue) props.onSave(apiValue, event);
+ };
+
+ const clearAllOptions = (event?: KeyboardEvent | MouseEvent) => {
+ if (!showClearAllRow()) return;
+
+ const nextSelectedIds = new Set<string>();
+ setOpenOrderFrozen(true);
+ setLocalSelectedIds(nextSelectedIds);
+ const apiValue = buildApiValue(nextSelectedIds);
+ if (apiValue) props.onSave(apiValue, event);
+ };
+
+ const selectRow = (
+ row: SelectPropertyRow,
+ event?: KeyboardEvent | MouseEvent
+ ) => {
+ if (row.type === 'clear') {
+ clearAllOptions(event);
+ return;
+ }
+
+ toggleOption(row.option.id, event);
+ };
+
+ const listController = createCommandListController({
+ items: rows,
+ selectedIndex: props.selectedIndex,
+ setSelectedIndex: props.setSelectedIndex,
});
props.setKeybindings({
- select: () => {
- const selected = filteredOptions()[props.selectedIndex()];
- props.onSubmit(selected.id);
+ select: (event) => {
+ const row = rows()[props.selectedIndex()];
+ if (row) selectRow(row, event);
},
next: () => {
- const len = filteredOptions().length;
- props.setSelectedIndex((prev) => (prev + 1) % len);
+ listController.selectNext();
},
previous: () => {
- const len = filteredOptions().length;
- props.setSelectedIndex((prev) => (prev - 1 + len) % len);
+ listController.selectPrevious();
},
});
- const selector = createSelector(props.selectedIndex);
-
return (
- <div class="max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden p-2">
- <Show
- when={filteredOptions().length > 0}
- fallback={
- <CommandMenuEmptyState>
- No matching options found
- </CommandMenuEmptyState>
+ <Show
+ when={rows().length > 0}
+ fallback={
+ <CommandMenuEmptyState>No matching options found</CommandMenuEmptyState>
+ }
+ >
+ <CommandMenuList
+ items={rows()}
+ selectedIndex={props.selectedIndex()}
+ scrollSelectedIntoView={listController.shouldScrollSelectedIntoView()}
+ itemId={(_, index) => `property-value-option-${index}`}
+ beforeItem={(row) =>
+ row.separatorBefore ? (
+ <div class="mx-2 my-1 h-px bg-edge-muted/50" />
+ ) : null
+ }
+ onSelect={(row, _, event) => selectRow(row, event)}
+ onItemMouseMove={(index) =>
+ listController.setSelectedIndexFromPointer(index)
}
>
- <For each={filteredOptions()}>
- {(option, index) => (
- <ListItem
- id={`property-value-option-${index()}`}
- isSelected={selector(index())}
- onClick={() => props.onSubmit(option.id)}
- onMouseEnter={() => props.setSelectedIndexFromMouse(index())}
- class="scroll-m-2"
- >
- <PropertyValueIcon optionId={option.id} />
- <div class="flex-1 text-left">
- <p class="text-sm font-medium">{String(option.value.value)}</p>
- </div>
- <Show when={shouldShowHotkeys() && index() < 9}>
- <div class="text-xxs px-1.5 py-0.5 border border-edge-muted text-ink-muted font-mono rounded-xs">
- <Hotkey shortcut={`${index() + 1}`} />
- </div>
- </Show>
- </ListItem>
- )}
- </For>
- </Show>
- </div>
+ {(row, index) => (
+ <Switch>
+ <Match when={row.type === 'clear'}>
+ <CircleDashedEmpty class="size-4 text-ink-muted opacity-50" />
+ <span class="min-w-0 flex-1 truncate text-ink-muted">
+ Clear all {props.property.displayName.toLowerCase()}
+ </span>
+ </Match>
+ <Match when={row.type === 'option' && row.option}>
+ {(option) => (
+ <>
+ <Show
+ when={canGroupMultiValues()}
+ fallback={<PropertyValueIcon optionId={option().id} />}
+ >
+ <OptionCheckBox
+ checked={localSelectedIds().has(option().id)}
+ multiselect
+ />
+ <PropertyValueIcon optionId={option().id} />
+ </Show>
+ <div class="flex-1 text-left">
+ <p class="text-sm font-medium">
+ {String(option().value.value)}
+ </p>
+ </div>
+ <Show when={shouldShowHotkeys() && index() < 9}>
+ <div class="text-xxs px-1.5 py-0.5 border border-edge-muted text-ink-muted font-mono rounded-xs">
+ <Hotkey shortcut={`${index() + 1}`} />
+ </div>
+ </Show>
+ </>
+ )}
+ </Match>
+ </Switch>
+ )}
+ </CommandMenuList>
+ </Show>
);
}
@@ -1299,10 +1656,14 @@ function EntityPropertyEditor(props: {
setSearchValue: Setter<string>;
selectedIndex: Accessor<number>;
setSelectedIndex: Setter<number>;
- setSelectedIndexFromMouse: (index: number) => void;
onSubmit: (value: EntityReference) => void;
+ onSave: (
+ apiValues: PropertyApiValues,
+ event?: KeyboardEvent | MouseEvent
+ ) => void;
setKeybindings: (binding: ListNavActions) => void;
setPlaceholder: Setter<string>;
+ selectedEntityCount: number;
}) {
// Company owners are always teammates, so the owner picker offers the
// team roster instead of the default quick-access people pool (same as
@@ -1329,6 +1690,48 @@ function EntityPropertyEditor(props: {
props.searchValue,
{ users: () => (isCompanyOwner() ? teamMembers() : undefined) }
);
+ const [localSelectedRefs, setLocalSelectedRefs] = createSignal(
+ props.property ? selectedEntityRefs(props.property) : []
+ );
+ const [orderedSelectedIds, setOrderedSelectedIds] = createSignal(
+ new Set(
+ props.property
+ ? selectedEntityRefs(props.property).map((ref) => ref.entity_id)
+ : []
+ )
+ );
+ let syncedPropertyId = props.property ? propertyIdentity(props.property) : '';
+ let syncedSelectionKey = props.property
+ ? selectedEntityRefs(props.property)
+ .map((ref) => ref.entity_id)
+ .sort()
+ .join('\0')
+ : '';
+ const [openOrderFrozen, setOpenOrderFrozen] = createSignal(false);
+
+ createEffect(() => {
+ const propertyId = props.property ? propertyIdentity(props.property) : '';
+ const refs = props.property ? selectedEntityRefs(props.property) : [];
+ const nextSelectionKey = refs
+ .map((ref) => ref.entity_id)
+ .sort()
+ .join('\0');
+
+ if (propertyId !== syncedPropertyId) {
+ syncedPropertyId = propertyId;
+ syncedSelectionKey = nextSelectionKey;
+ setOpenOrderFrozen(false);
+ setLocalSelectedRefs(refs);
+ setOrderedSelectedIds(new Set(refs.map((ref) => ref.entity_id)));
+ return;
+ }
+
+ if (openOrderFrozen() || nextSelectionKey === syncedSelectionKey) return;
+
+ syncedSelectionKey = nextSelectionKey;
+ setLocalSelectedRefs(refs);
+ setOrderedSelectedIds(new Set(refs.map((ref) => ref.entity_id)));
+ });
createEffect(() => {
const entityTypeLabel =
@@ -1341,74 +1744,214 @@ function EntityPropertyEditor(props: {
props.setSelectedIndex(0);
});
+ const selectEntity = (entity: CombinedEntity) => {
+ const entityRef: EntityReference = {
+ entity_id: entity.id,
+ entity_type: getEntityType(entity),
+ };
+ props.onSubmit(entityRef);
+ };
+
+ const canGroupMultiValues = () =>
+ Boolean(
+ props.property?.isMultiSelect &&
+ props.selectedEntityCount === 1 &&
+ props.property &&
+ 'value' in props.property
+ );
+
+ const localSelectedIds = createMemo(
+ () => new Set(localSelectedRefs().map((ref) => ref.entity_id))
+ );
+
+ const orderedEntities = createMemo(() => {
+ if (!canGroupMultiValues()) return entities();
+
+ const selectedAtOpen = orderedSelectedIds();
+ const selected = entities().filter((entity) =>
+ selectedAtOpen.has(entity.id)
+ );
+ const remaining = entities().filter(
+ (entity) => !selectedAtOpen.has(entity.id)
+ );
+
+ return [...selected, ...remaining];
+ });
+
+ const selectedGroupSize = createMemo(() =>
+ canGroupMultiValues()
+ ? orderedEntities().filter((entity) =>
+ orderedSelectedIds().has(entity.id)
+ ).length
+ : 0
+ );
+
+ const searchQuery = () => props.searchValue().trim();
+ const showClearAllRow = () =>
+ canGroupMultiValues() && orderedSelectedIds().size > 0;
+ const showClearAllAtTop = () => showClearAllRow() && !searchQuery();
+ const showClearAllAtBottom = () => showClearAllRow() && !!searchQuery();
+
+ type EntityPropertyRow =
+ | { type: 'clear'; separatorBefore: boolean }
+ | {
+ type: 'entity';
+ entity: CombinedEntity;
+ separatorBefore: boolean;
+ };
+
+ const rows = createMemo(() => {
+ const nextRows: EntityPropertyRow[] = [];
+
+ if (showClearAllAtTop()) {
+ nextRows.push({ type: 'clear', separatorBefore: false });
+ }
+
+ for (const [index, entity] of orderedEntities().entries()) {
+ nextRows.push({
+ type: 'entity',
+ entity,
+ separatorBefore:
+ canGroupMultiValues() && index === selectedGroupSize() && index > 0,
+ });
+ }
+
+ if (showClearAllAtBottom()) {
+ nextRows.push({
+ type: 'clear',
+ separatorBefore: orderedEntities().length > 0,
+ });
+ }
+
+ return nextRows;
+ });
+
+ const toggleEntity = (
+ entity: CombinedEntity,
+ event?: KeyboardEvent | MouseEvent
+ ) => {
+ if (!canGroupMultiValues()) {
+ selectEntity(entity);
+ return;
+ }
+
+ const selectedIds = localSelectedIds();
+ setOpenOrderFrozen(true);
+ const nextRefs = selectedIds.has(entity.id)
+ ? localSelectedRefs().filter((ref) => ref.entity_id !== entity.id)
+ : [
+ ...localSelectedRefs(),
+ {
+ entity_id: entity.id,
+ entity_type: getEntityType(entity),
+ },
+ ];
+
+ setLocalSelectedRefs(nextRefs);
+ props.onSave(
+ {
+ valueType: 'ENTITY',
+ refs: nextRefs.length > 0 ? nextRefs : null,
+ },
+ event
+ );
+ };
+
+ const clearAllEntities = (event?: KeyboardEvent | MouseEvent) => {
+ if (!showClearAllRow()) return;
+
+ setOpenOrderFrozen(true);
+ setLocalSelectedRefs([]);
+ props.onSave({ valueType: 'ENTITY', refs: null }, event);
+ };
+
+ const selectRow = (
+ row: EntityPropertyRow,
+ event?: KeyboardEvent | MouseEvent
+ ) => {
+ if (row.type === 'clear') {
+ clearAllEntities(event);
+ return;
+ }
+
+ toggleEntity(row.entity, event);
+ };
+
+ const listController = createCommandListController({
+ items: rows,
+ selectedIndex: props.selectedIndex,
+ setSelectedIndex: props.setSelectedIndex,
+ });
+
props.setKeybindings({
- select: () => {
- const selected = entities()[props.selectedIndex()];
- if (selected) {
- const entityRef: EntityReference = {
- entity_id: selected.id,
- entity_type: getEntityType(selected),
- };
- props.onSubmit(entityRef);
- }
+ select: (event) => {
+ const row = rows()[props.selectedIndex()];
+ if (row) selectRow(row, event);
},
next: () => {
- const len = entities().length;
- props.setSelectedIndex((prev) => (prev + 1) % len);
+ listController.selectNext();
},
previous: () => {
- const len = entities().length;
- props.setSelectedIndex((prev) => (prev - 1 + len) % len);
+ listController.selectPrevious();
},
});
- createEffect(() => {
- const index = props.selectedIndex();
- const elem = document.getElementById(`entity-option-${index}`);
- if (elem) {
- elem.scrollIntoView({ block: 'nearest' });
- }
- });
-
- const selector = createSelector(props.selectedIndex);
-
return (
- <div class="max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden p-2">
- <Show
- when={entities().length > 0}
- fallback={
- <CommandMenuEmptyState>
- {props.searchValue().trim()
- ? 'No matching entities found'
- : 'No entities available'}
- </CommandMenuEmptyState>
+ <Show
+ when={rows().length > 0}
+ fallback={
+ <CommandMenuEmptyState>
+ {props.searchValue().trim()
+ ? 'No matching entities found'
+ : 'No entities available'}
+ </CommandMenuEmptyState>
+ }
+ >
+ <CommandMenuList
+ items={rows()}
+ selectedIndex={props.selectedIndex()}
+ scrollSelectedIntoView={listController.shouldScrollSelectedIntoView()}
+ itemId={(_, index) => `entity-option-${index}`}
+ beforeItem={(row) =>
+ row.separatorBefore ? (
+ <div class="mx-2 my-1 h-px bg-edge-muted/50" />
+ ) : null
+ }
+ onSelect={(row, _, event) => selectRow(row, event)}
+ onItemMouseMove={(index) =>
+ listController.setSelectedIndexFromPointer(index)
}
>
- <For each={entities()}>
- {(entity, index) => (
- <ListItem
- id={`entity-option-${index()}`}
- isSelected={selector(index())}
- class="scroll-m-2"
- onClick={() => {
- const entityRef: EntityReference = {
- entity_id: entity.id,
- entity_type: getEntityType(entity),
- };
- props.onSubmit(entityRef);
- }}
- onMouseEnter={() => props.setSelectedIndexFromMouse(index())}
- >
- <EntityRowContent entity={entity} />
- </ListItem>
- )}
- </For>
- </Show>
- </div>
+ {(row) => (
+ <Switch>
+ <Match when={row.type === 'clear'}>
+ <CircleDashedEmpty class="size-4 text-ink-muted opacity-50" />
+ <span class="min-w-0 flex-1 truncate text-ink-muted">
+ Clear all{' '}
+ {props.property?.displayName.toLowerCase() ?? 'entities'}
+ </span>
+ </Match>
+ <Match when={row.type === 'entity' && row.entity}>
+ {(entity) => (
+ <EntityRowContent
+ entity={entity()}
+ multiselect={canGroupMultiValues()}
+ selected={localSelectedIds().has(entity().id)}
+ />
+ )}
+ </Match>
+ </Switch>
+ )}
+ </CommandMenuList>
+ </Show>
);
}
-function EntityRowContent(props: { entity: CombinedEntity }) {
+function EntityRowContent(props: {
+ entity: CombinedEntity;
+ multiselect?: boolean;
+ selected?: boolean;
+}) {
const { icon } = usePropertyEntityDisplay(
() => props.entity.id,
() => getEntityType(props.entity)
@@ -1416,6 +1959,9 @@ function EntityRowContent(props: { entity: CombinedEntity }) {
return (
<>
+ <Show when={props.multiselect}>
+ <OptionCheckBox checked={Boolean(props.selected)} multiselect />
+ </Show>
<span class="size-4 flex items-center justify-center shrink-0">
{icon()}
</span>
@@ -1432,7 +1978,6 @@ function DirectEditPropertyEditor(props: {
setSearchValue: Setter<string>;
selectedIndex: Accessor<number>;
setSelectedIndex: Setter<number>;
- setSelectedIndexFromMouse: (index: number) => void;
onSubmit: (value: string | number | boolean | Date) => void;
setKeybindings: (binding: ListNavActions) => void;
setPlaceholder: Setter<string>;
@@ -1446,7 +1991,6 @@ function DirectEditPropertyEditor(props: {
searchValue={props.searchValue}
selectedIndex={props.selectedIndex}
setSelectedIndex={props.setSelectedIndex}
- setSelectedIndexFromMouse={props.setSelectedIndexFromMouse}
onSubmit={props.onSubmit as (value: Date) => void}
setKeybindings={props.setKeybindings}
setPlaceholder={props.setPlaceholder}
@@ -1454,40 +1998,14 @@ function DirectEditPropertyEditor(props: {
);
}
- // Fetch existing property value for single entity
- const singleEntity = () => {
- const entities = propertyEditorState.selectedEntities;
- return entities.length === 1 ? entities[0] : null;
- };
-
- const entityPropertiesQuery = useEntityPropertiesQuery(
- () => {
- const entity = singleEntity();
- return entity ? macroEntityToPropertyEntityType(entity) : 'DOCUMENT';
- },
- () => singleEntity()?.id ?? '',
- false
- );
-
const existingValue = createMemo(() => {
- const entity = singleEntity();
- if (!entity || !props.property) return null;
-
- const propertyDefId =
- 'propertyDefinitionId' in props.property
- ? props.property.propertyDefinitionId
- : props.property.id;
-
- const entityProperties = entityPropertiesQuery.data;
- if (!entityProperties) return null;
-
- const prop = entityProperties.find(
- (p) => p.propertyDefinitionId === propertyDefId
- );
- if (!prop) return null;
-
- if (prop.valueType === 'STRING' || prop.valueType === 'NUMBER') {
- return prop.value;
+ const property = props.property;
+ if (
+ property &&
+ 'value' in property &&
+ (property.valueType === 'STRING' || property.valueType === 'NUMBER')
+ ) {
+ return property.value;
}
return null;
});
@@ -1564,26 +2082,29 @@ function DirectEditPropertyEditor(props: {
};
return (
- <div class="max-h-50 overflow-y-auto overflow-x-hidden scrollbar-hidden p-2">
- <ListItem
- id="property-value-option-0"
- isSelected={true}
- disabled={!isValidInput()}
- onClick={handleSubmit}
- onMouseEnter={() => {}}
- >
- <PropertyDataTypeIcon property={props.property!} class="opacity-50" />
- <div class="flex-1 text-left">
- <p class="text-sm font-medium">
- Set {props.property?.displayName}
- <Show when={displayValue()}>
- {' '}
- to <span class="text-ink-muted">{displayValue()}</span>
- </Show>
- </p>
- </div>
- </ListItem>
- </div>
+ <CommandMenuList
+ items={props.property ? [props.property] : []}
+ selectedIndex={0}
+ class="max-h-50"
+ itemId={() => 'property-value-option-0'}
+ itemDisabled={() => !isValidInput()}
+ onSelect={handleSubmit}
+ >
+ {() => (
+ <>
+ <PropertyDataTypeIcon property={props.property!} class="opacity-50" />
+ <div class="flex-1 text-left">
+ <p class="text-sm font-medium">
+ Set {props.property?.displayName}
+ <Show when={displayValue()}>
+ {' '}
+ to <span class="text-ink-muted">{displayValue()}</span>
+ </Show>
+ </p>
+ </div>
+ </>
+ )}
+ </CommandMenuList>
);
}
@@ -1592,7 +2113,6 @@ function DatePropertyEditor(props: {
searchValue: Accessor<string>;
selectedIndex: Accessor<number>;
setSelectedIndex: Setter<number>;
- setSelectedIndexFromMouse: (index: number) => void;
onSubmit: (value: Date) => void;
setKeybindings: (binding: ListNavActions) => void;
setPlaceholder: Setter<string>;
@@ -1617,65 +2137,64 @@ function DatePropertyEditor(props: {
})
);
+ const listController = createCommandListController({
+ items: dateOptions,
+ selectedIndex: props.selectedIndex,
+ setSelectedIndex: props.setSelectedIndex,
+ onSelect: (option) => props.onSubmit(option.date),
+ });
+
props.setKeybindings({
select: () => {
- const selected = dateOptions()[props.selectedIndex()];
- if (selected) {
- props.onSubmit(selected.date);
- }
+ listController.selectSelected();
},
next: () => {
- const len = dateOptions().length;
- props.setSelectedIndex((prev) => (prev + 1) % len);
+ listController.selectNext();
},
previous: () => {
- const len = dateOptions().length;
- props.setSelectedIndex((prev) => (prev - 1 + len) % len);
+ listController.selectPrevious();
},
});
- const selector = createSelector(props.selectedIndex);
-
return (
<>
- <div class="p-2 max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden">
- <Show
- when={dateOptions().length > 0}
- fallback={
- <Show
- when={props.searchValue().trim()}
- fallback={
- <CommandMenuEmptyState>
- Enter a date or duration
- </CommandMenuEmptyState>
- }
- >
+ <Show
+ when={dateOptions().length > 0}
+ fallback={
+ <Show
+ when={props.searchValue().trim()}
+ fallback={
<CommandMenuEmptyState>
- No dates match "{props.searchValue()}"
+ Enter a date or duration
</CommandMenuEmptyState>
- </Show>
+ }
+ >
+ <CommandMenuEmptyState>
+ No dates match "{props.searchValue()}"
+ </CommandMenuEmptyState>
+ </Show>
+ }
+ >
+ <CommandMenuList
+ items={dateOptions()}
+ selectedIndex={props.selectedIndex()}
+ scrollSelectedIntoView={listController.shouldScrollSelectedIntoView()}
+ itemId={(_, index) => `date-option-${index}`}
+ onSelect={(option) => props.onSubmit(option.date)}
+ onItemMouseMove={(index) =>
+ listController.setSelectedIndexFromPointer(index)
}
>
- <For each={dateOptions()}>
- {(option, index) => (
- <ListItem
- id={`date-option-${index()}`}
- isSelected={selector(index())}
- onClick={() => props.onSubmit(option.date)}
- onMouseEnter={() => props.setSelectedIndexFromMouse(index())}
- class="scroll-m-2"
- >
- <div class="flex-1 text-left">
- <p class="text-sm font-medium">{option.displayText}</p>
- </div>
- <span class="text-xs text-ink-muted">
- {option.secondaryText}
- </span>
- </ListItem>
- )}
- </For>
- </Show>
- </div>
+ {(option) => (
+ <>
+ <div class="flex-1 text-left">
+ <p class="text-sm font-medium">{option.displayText}</p>
+ </div>
+ <span class="text-xs text-ink-muted">{option.secondaryText}</span>
+ </>
+ )}
+ </CommandMenuList>
+ </Show>
<div class="p-4 border-t border-edge-muted">
<div class="text-xs text-ink-muted">
diff --git a/apps/web/src/features/property/editor/hooks/useSaveProperties.ts b/apps/web/src/features/property/editor/hooks/useSaveProperties.ts
index 1ed4876e5e..7398b8b163 100644
--- a/apps/web/src/features/property/editor/hooks/useSaveProperties.ts
+++ b/apps/web/src/features/property/editor/hooks/useSaveProperties.ts
@@ -1,4 +1,5 @@
-import type { EntityData } from '@entity';
+import { isTaskEntity } from '@entity';
+import type { PropertyEditorEntity } from '@property/editor/state/propertyEditor';
import type {
Property,
PropertyApiValues,
@@ -7,10 +8,16 @@ import type {
import { macroEntityToPropertyEntityType } from '@property/utils';
import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
+function propertyEditorEntityType(entity: PropertyEditorEntity) {
+ if ('entityType' in entity) return entity.entityType;
+ if (isTaskEntity(entity)) return 'TASK';
+ return macroEntityToPropertyEntityType(entity);
+}
+
export function useSavePropertyForMultiEntitites() {
const mutation = useBulkSaveEntityPropertiesMutation();
return async (
- entities: EntityData[],
+ entities: PropertyEditorEntity[],
property: Property | PropertyDefinitionDomain,
value: PropertyApiValues
) => {
@@ -22,7 +29,7 @@ export function useSavePropertyForMultiEntitites() {
await mutation.mutateAsync({
properties: entities.map((e) => ({
entityId: e.id,
- entityType: macroEntityToPropertyEntityType(e),
+ entityType: propertyEditorEntityType(e),
property,
apiValues: value,
})),
diff --git a/apps/web/src/features/property/editor/state/propertyEditor.ts b/apps/web/src/features/property/editor/state/propertyEditor.ts
index e3e43c9113..2348644c0c 100644
--- a/apps/web/src/features/property/editor/state/propertyEditor.ts
+++ b/apps/web/src/features/property/editor/state/propertyEditor.ts
@@ -1,21 +1,31 @@
import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';
import type { EntityData } from '@entity';
import type { Property, PropertyDefinitionDomain } from '@property/types';
+import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { createStore, reconcile } from 'solid-js/store';
type PropertyEditorMode = 'selector' | 'direct' | 'tag';
+export type PropertyEditorEntity =
+ | EntityData
+ | {
+ id: string;
+ name: string;
+ entityType: EntityType;
+ };
+
export const [propertyEditorOpen, setPropertyEditorOpen] =
createControlledOpenSignal(false, { id: 'property-edit' });
interface PropertyEditorState {
mode: PropertyEditorMode;
- selectedEntities: EntityData[];
+ selectedEntities: PropertyEditorEntity[];
targetProperty?: Property | PropertyDefinitionDomain;
}
type PropertyEditorOpenOptions = {
restoreFocus?: () => void | Promise<void>;
+ onPropertyAdded?: (addedDefinitionIds?: string[]) => void | Promise<void>;
};
const [state, setState] = createStore<PropertyEditorState>({
@@ -25,9 +35,10 @@ const [state, setState] = createStore<PropertyEditorState>({
});
let restoreFocusAfterClose: PropertyEditorOpenOptions['restoreFocus'];
+let onPropertyAddedForOpenEditor: PropertyEditorOpenOptions['onPropertyAdded'];
export function openPropertyEditor(
- entities: EntityData[],
+ entities: PropertyEditorEntity[],
mode: PropertyEditorMode = 'selector',
targetProperty?: Property | PropertyDefinitionDomain,
options?: PropertyEditorOpenOptions
@@ -37,6 +48,7 @@ export function openPropertyEditor(
return;
}
restoreFocusAfterClose = options?.restoreFocus;
+ onPropertyAddedForOpenEditor = options?.onPropertyAdded;
setState(
reconcile({
mode,
@@ -50,6 +62,7 @@ export function openPropertyEditor(
export function closePropertyEditor() {
const restoreFocus = restoreFocusAfterClose;
restoreFocusAfterClose = undefined;
+ onPropertyAddedForOpenEditor = undefined;
setPropertyEditorOpen(false);
setState(
reconcile({
@@ -62,6 +75,16 @@ export function closePropertyEditor() {
void restoreFocus?.();
}
+export async function notifyPropertyEditorPropertyAdded(
+ addedDefinitionIds?: string[]
+) {
+ await onPropertyAddedForOpenEditor?.(addedDefinitionIds);
+}
+
+export function hasPropertyEditorPropertyAddedHandler() {
+ return Boolean(onPropertyAddedForOpenEditor);
+}
+
export function togglePropertyEditor(force?: boolean) {
const next = force ?? !propertyEditorOpen();
if (next) setPropertyEditorOpen(true);
diff --git a/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx b/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx
index cfb743ee50..bbcbb883eb 100644
--- a/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx
+++ b/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx
@@ -7,6 +7,7 @@ import { openDocument } from '@core/component/LexicalMarkdown/component/core/Blo
import { itemToBlockName } from '@core/constant/allBlocks';
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
import Plus from '@phosphor/plus.svg';
+import TrashIcon from '@phosphor/trash.svg';
import DeleteIcon from '@phosphor/x.svg';
import { Property as PropertyNS, useProperty } from '@property';
import { Modals } from '@property/component/modal';
@@ -16,9 +17,14 @@ import {
type PropertySaveHandler,
usePropertiesContext,
} from '@property/context/PropertiesContext';
+import { useAllProperties } from '@property/editor/hooks/useAllProperties';
import { useEntityProperties, usePropertyEntityDisplay } from '@property/hooks';
import { TagsRow } from '@property/tags';
-import type { Property, PropertyApiValues } from '@property/types';
+import type {
+ Property,
+ PropertyApiValues,
+ PropertyDefinitionDomain,
+} from '@property/types';
import { getEntityValues, hasValue } from '@property/utils';
import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';
import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
@@ -37,6 +43,7 @@ import {
Suspense,
Switch,
} from 'solid-js';
+import { match } from 'ts-pattern';
export interface EntityPropertiesSectionProps {
entityId: string;
@@ -113,10 +120,15 @@ export function EntityTagsSection(props: EntityTagsSectionProps) {
}
export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
- const { properties, isLoading, error, refetch } = useEntityProperties(
- props.entityId,
- props.entityType,
- props.includeMetadata ?? false
+ const { properties, isLoading, error, refetch, addProperty, removeProperty } =
+ useEntityProperties(
+ props.entityId,
+ props.entityType,
+ props.includeMetadata ?? false
+ );
+ const allProperties = useAllProperties();
+ const [pendingPinDefIds, setPendingPinDefIds] = createSignal<Set<string>>(
+ new Set()
);
const tagsQuery = useTagsQuery();
@@ -138,15 +150,28 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
(property) => !hiddenDefinitionIds.has(property.propertyDefinitionId)
);
const defaults = props.defaultProperties?.() ?? [];
- if (defaults.length === 0) return fetched;
const fetchedDefinitionIds = new Set(
fetched.map((property) => property.propertyDefinitionId)
);
+ const defaultDefinitionIds = new Set(
+ defaults.map((property) => property.propertyDefinitionId)
+ );
+ const pendingPlaceholderProperties = allProperties().flatMap(
+ (definition) => {
+ if (!pendingPinDefIds().has(definition.id)) return [];
+ if (hiddenDefinitionIds.has(definition.id)) return [];
+ if (fetchedDefinitionIds.has(definition.id)) return [];
+ if (defaultDefinitionIds.has(definition.id)) return [];
+ const property = propertyFromPendingDefinition(definition);
+ return property ? [property] : [];
+ }
+ );
return [
...fetched,
...defaults.filter(
(property) => !fetchedDefinitionIds.has(property.propertyDefinitionId)
),
+ ...pendingPlaceholderProperties,
];
});
@@ -164,6 +189,7 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
return false;
}
if (property.isMetadata) return props.includeMetadata === true;
+ if (pendingPinDefIds().has(property.propertyDefinitionId)) return true;
if (!usesPinnedFilter) return true;
return (
defaultPinnedIds.includes(property.propertyDefinitionId) ||
@@ -182,17 +208,12 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
const collectionPinnedProperties = createMemo(() =>
filteredPinnedProperties().filter(isNonUserMultiEntityProperty)
);
-
- const [pendingPinDefIds, setPendingPinDefIds] = createSignal<Set<string>>(
- new Set()
+ const defaultPinnedDefinitionIds = createMemo(
+ () => new Set(props.defaultPinnedPropertyIds?.() ?? [])
);
const handlePropertyAdded = (addedDefinitionIds?: string[]) => {
- if (
- props.onPropertyPinned &&
- addedDefinitionIds &&
- addedDefinitionIds.length > 0
- ) {
+ if (addedDefinitionIds && addedDefinitionIds.length > 0) {
setPendingPinDefIds((prev) => {
const next = new Set(prev);
for (const id of addedDefinitionIds) next.add(id);
@@ -202,9 +223,27 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
refetch();
};
+ const removePendingProperty = (property: Property) => {
+ if (!property.propertyId.startsWith('pending:')) return;
+ setPendingPinDefIds((prev) => {
+ const next = new Set(prev);
+ next.delete(property.propertyDefinitionId);
+ return next;
+ });
+ };
+
+ const handlePropertyAddFailed = (definitionId: string) => {
+ setPendingPinDefIds((prev) => {
+ const next = new Set(prev);
+ next.delete(definitionId);
+ return next;
+ });
+ refetch();
+ };
+
createEffect(() => {
const pending = pendingPinDefIds();
- if (pending.size === 0 || !props.onPropertyPinned) return;
+ if (pending.size === 0) return;
const remaining = new Set(pending);
for (const defId of pending) {
@@ -212,7 +251,7 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
(property) => property.propertyDefinitionId === defId
);
if (instance) {
- props.onPropertyPinned(instance.propertyId);
+ props.onPropertyPinned?.(instance.propertyId);
remaining.delete(defId);
}
}
@@ -250,16 +289,20 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
>
<div class="text-xs">
<PropertiesProvider
+ entityId={props.entityId}
entityType={props.entityType}
canEdit={props.canEdit}
documentName={props.documentName}
properties={filteredPinnedProperties}
onRefresh={refetch}
onPropertyAdded={handlePropertyAdded}
+ onPropertyAddFailed={handlePropertyAddFailed}
onPropertyDeleted={refetch}
onPropertyPinned={props.onPropertyPinned}
onPropertyUnpinned={props.onPropertyUnpinned}
pinnedPropertyIds={props.pinnedPropertyIds}
+ addProperty={addProperty}
+ removeProperty={removeProperty}
saveHandler={saveHandler}
>
<Show when={isLoading()}>
@@ -290,6 +333,12 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
entityId={props.entityId}
getEmptyLabel={props.getEmptyLabel}
property={property}
+ canRemoveFromEntity={
+ !defaultPinnedDefinitionIds().has(
+ property.propertyDefinitionId
+ )
+ }
+ onRemovePendingProperty={removePendingProperty}
/>
)}
</For>
@@ -303,6 +352,12 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {
<EntityCollectionProperty
entityId={props.entityId}
property={property}
+ canRemoveFromEntity={
+ !defaultPinnedDefinitionIds().has(
+ property.propertyDefinitionId
+ )
+ }
+ onRemovePendingProperty={removePendingProperty}
/>
)}
</For>
@@ -339,6 +394,60 @@ function AddPinnedPropertyButton() {
);
}
+function propertyFromPendingDefinition(
+ definition: PropertyDefinitionDomain
+): Property | undefined {
+ const base = {
+ propertyId: `pending:${definition.id}`,
+ propertyDefinitionId: definition.id,
+ displayName: definition.displayName,
+ isMultiSelect: definition.isMultiSelect,
+ isMetadata: definition.isMetadata,
+ isSystemProperty: definition.isSystem,
+ options: definition.options,
+ owner: definition.owner,
+ specificEntityType: definition.specificEntityType,
+ createdAt: definition.createdAt,
+ updatedAt: definition.updatedAt,
+ };
+
+ return match(definition.valueType)
+ .with('STRING', () => ({
+ ...base,
+ valueType: 'STRING' as const,
+ value: null,
+ }))
+ .with('NUMBER', () => ({
+ ...base,
+ valueType: 'NUMBER' as const,
+ value: null,
+ }))
+ .with('BOOLEAN', () => ({
+ ...base,
+ valueType: 'BOOLEAN' as const,
+ value: null,
+ }))
+ .with('DATE', () => ({ ...base, valueType: 'DATE' as const, value: null }))
+ .with('SELECT_STRING', () => ({
+ ...base,
+ valueType: 'SELECT_STRING' as const,
+ value: null,
+ }))
+ .with('SELECT_NUMBER', () => ({
+ ...base,
+ valueType: 'SELECT_NUMBER' as const,
+ value: null,
+ }))
+ .with('ENTITY', () => ({
+ ...base,
+ valueType: 'ENTITY' as const,
+ value: null,
+ }))
+ .with('LINK', () => ({ ...base, valueType: 'LINK' as const, value: null }))
+ .with('TAG', () => undefined)
+ .exhaustive();
+}
+
function sortPinnedProperties<T extends Property>(
properties: T[],
pinnedOrder: readonly string[] = []
@@ -361,8 +470,10 @@ function isNonUserMultiEntityProperty(property: Property): boolean {
}
function SidePanelPropertyRow(props: {
+ canRemoveFromEntity: boolean;
entityId: string;
getEmptyLabel?: (property: Property) => JSX.Element | undefined;
+ onRemovePendingProperty: (property: Property) => void;
property: Property;
}) {
const ctx = usePropertiesContext();
@@ -377,7 +488,7 @@ function SidePanelPropertyRow(props: {
const isMultilineRow = () => t() === 'STRING' && hasValue(props.property);
return (
- <>
+ <div class="contents group/property-row">
<span
class={cn('text-ink-muted truncate', {
'self-start pt-[0.3125rem]': isMultilineRow(),
@@ -393,37 +504,117 @@ function SidePanelPropertyRow(props: {
'self-center': !isMultilineRow(),
})}
>
- <PropertyNS.Root
- class="min-w-0 max-w-full overflow-hidden"
- property={props.property}
- canEdit={ctx.canEdit}
- onSave={ctx.saveHandler.saveProperty}
- onRefresh={ctx.onRefresh}
- >
- <Switch
- fallback={
- <SinglePill
- getEmptyLabel={props.getEmptyLabel}
- property={props.property}
- />
- }
+ <div class="group/property-row relative min-w-0 max-w-full overflow-hidden">
+ <PropertyNS.Root
+ class="min-w-0 max-w-full overflow-hidden"
+ property={props.property}
+ canEdit={ctx.canEdit}
+ onSave={ctx.saveHandler.saveProperty}
+ onRefresh={ctx.onRefresh}
>
- <Match when={isInputType()}>
- <InputValue />
- </Match>
- <Match when={isMultiValueRow()}>
- <MultiValue property={props.property} />
- </Match>
- </Switch>
- <PropertyNS.PopoverEditor
- entitySelfFilter={{
- entityType: ctx.entityType,
- blockId: props.entityId,
- }}
+ <Switch
+ fallback={
+ <SinglePill
+ getEmptyLabel={props.getEmptyLabel}
+ property={props.property}
+ />
+ }
+ >
+ <Match when={isInputType()}>
+ <InputValue />
+ </Match>
+ <Match when={isMultiValueRow()}>
+ <MultiValue property={props.property} />
+ </Match>
+ </Switch>
+ <PropertyNS.PopoverEditor
+ entitySelfFilter={{
+ entityType: ctx.entityType,
+ blockId: props.entityId,
+ }}
+ />
+ </PropertyNS.Root>
+ <PropertyRowActions
+ canRemoveFromEntity={props.canRemoveFromEntity}
+ property={props.property}
+ onRemovePendingProperty={props.onRemovePendingProperty}
/>
- </PropertyNS.Root>
+ </div>
</div>
- </>
+ </div>
+ );
+}
+
+function isPendingProperty(property: Property): boolean {
+ return property.propertyId.startsWith('pending:');
+}
+
+function PropertyRowActions(props: {
+ canRemoveFromEntity: boolean;
+ onRemovePendingProperty: (property: Property) => void;
+ property: Property;
+}) {
+ const ctx = usePropertiesContext();
+ const [isSaving, setIsSaving] = createSignal(false);
+
+ const canRemove = () =>
+ props.canRemoveFromEntity &&
+ ctx.canEdit &&
+ !props.property.isMetadata &&
+ (isPendingProperty(props.property) || Boolean(ctx.removeProperty));
+ const hasActions = () => canRemove();
+
+ const stopRowInteraction = (event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ const removeFromEntity = async (event: MouseEvent) => {
+ stopRowInteraction(event);
+ if (!canRemove() || isSaving()) return;
+
+ if (isPendingProperty(props.property)) {
+ props.onRemovePendingProperty(props.property);
+ return;
+ }
+
+ const remove = ctx.removeProperty;
+ if (!remove) return;
+
+ setIsSaving(true);
+ try {
+ await remove(props.property.propertyId);
+ ctx.onPropertyUnpinned?.(props.property.propertyId);
+ ctx.onRefresh();
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <Show when={hasActions()}>
+ <div
+ class={cn(
+ 'absolute right-0 top-1/2 z-1 flex -translate-y-1/2 items-center gap-0.5',
+ 'pointer-events-none opacity-0 transition-opacity',
+ 'group-hover/property-row:opacity-100 group-focus-within/property-row:opacity-100 focus-within:opacity-100'
+ )}
+ onMouseDown={stopRowInteraction}
+ >
+ <Show when={canRemove()}>
+ <button
+ type="button"
+ title="Remove from entity"
+ aria-label="Remove from entity"
+ disabled={isSaving()}
+ class="pointer-events-auto flex size-5 items-center justify-center rounded-full text-ink-muted outline-none ring-0 shadow-none hover:bg-hover hover:text-failure-ink focus:outline-none focus-visible:outline-none focus-visible:ring-0 disabled:pointer-events-none disabled:opacity-50"
+ onClick={removeFromEntity}
+ >
+ <TrashIcon class="size-3" />
+ </button>
+ </Show>
+ </div>
+ </Show>
);
}
@@ -636,7 +827,9 @@ function NonUserEntityValue(props: { property: Property }) {
}
function EntityCollectionProperty(props: {
+ canRemoveFromEntity: boolean;
entityId: string;
+ onRemovePendingProperty: (property: Property) => void;
property: Property;
}) {
const ctx = usePropertiesContext();
@@ -648,7 +841,11 @@ function EntityCollectionProperty(props: {
onSave={ctx.saveHandler.saveProperty}
onRefresh={ctx.onRefresh}
>
- <EntityCollectionPropertyBody property={props.property} />
+ <EntityCollectionPropertyBody
+ canRemoveFromEntity={props.canRemoveFromEntity}
+ property={props.property}
+ onRemovePendingProperty={props.onRemovePendingProperty}
+ />
<PropertyNS.PopoverEditor
entitySelfFilter={{
entityType: ctx.entityType,
@@ -659,7 +856,11 @@ function EntityCollectionProperty(props: {
);
}
-function EntityCollectionPropertyBody(props: { property: Property }) {
+function EntityCollectionPropertyBody(props: {
+ canRemoveFromEntity: boolean;
+ onRemovePendingProperty: (property: Property) => void;
+ property: Property;
+}) {
const ctx = usePropertiesContext();
const propertyCtx = useProperty();
const entities = () => getEntityValues(props.property);
@@ -678,7 +879,7 @@ function EntityCollectionPropertyBody(props: { property: Property }) {
return (
<SidePanel.Card>
- <div class="p-2">
+ <div class="group/property-row relative p-2">
<div class="flex items-center justify-between gap-2">
<span
class="min-w-0 truncate text-ink-muted"
@@ -702,6 +903,11 @@ function EntityCollectionPropertyBody(props: { property: Property }) {
<Plus class="size-3" />
</Button>
</Show>
+ <PropertyRowActions
+ canRemoveFromEntity={props.canRemoveFromEntity}
+ property={props.property}
+ onRemovePendingProperty={props.onRemovePendingProperty}
+ />
</div>
<div class="mt-2 flex flex-wrap gap-1.5">
<For
diff --git a/apps/web/src/lib/core/component/ContextMenu.tsx b/apps/web/src/lib/core/component/ContextMenu.tsx
index fa333ef77c..89647e5396 100644
--- a/apps/web/src/lib/core/component/ContextMenu.tsx
+++ b/apps/web/src/lib/core/component/ContextMenu.tsx
@@ -143,9 +143,7 @@ export function MenuItem(props: MenuItemProps) {
<MenuItemWrapper
class={cn(
MENU_ITEM_CLASS,
- props.disabled
- ? 'opacity-50 cursor-not-allowed'
- : 'hover:bg-ink/5 hover-transition-bg',
+ props.disabled && 'opacity-50 cursor-not-allowed',
props.class
)}
onClick={props.onClick}
@@ -234,9 +232,7 @@ export function SubTrigger(props: {
<ContextMenu.SubTrigger
class={cn(
MENU_ITEM_CLASS,
- props.disabled
- ? 'opacity-50 cursor-not-allowed'
- : 'hover:bg-ink/5 hover-transition-bg'
+ props.disabled && 'opacity-50 cursor-not-allowed'
)}
disabled={props.disabled}
>
diff --git a/apps/web/src/lib/core/component/TabsInset.tsx b/apps/web/src/lib/core/component/TabsInset.tsx
index 58ba7ae3c6..a4c96bea6c 100644
--- a/apps/web/src/lib/core/component/TabsInset.tsx
+++ b/apps/web/src/lib/core/component/TabsInset.tsx
@@ -45,7 +45,7 @@ export const TabsInset = (props: TabsInsetProps) => {
class={cn('h-full flex items-center', local.class)}
>
<Layer depth={trackDepth()}>
- <div class="relative flex items-center border border-edge-muted bg-surface rounded-lg p-0.5">
+ <div class="relative flex items-center border border-edge-muted bg-surface rounded-lg p-0.5 has-focus-visible:ring-2 has-focus-visible:ring-accent/20">
<For each={local.list}>
{(item) => (
<Layer depth={itemDepth()}>
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 7dfe3e3884..b7b3e7370f 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -501,7 +501,7 @@ export const ENABLE_REFOCUS_HIGHLIGHT = resolveFeatureFlag(
export const ENABLE_CREATE_PROPERTY = resolveFeatureFlag(
'ENABLE_CREATE_PROPERTY',
- false
+ true
);
export const ENABLE_HOME_OVERRIDE = DEV_MODE_ENV ? true : undefined;
diff --git a/apps/web/src/lib/queries/properties/definitions.ts b/apps/web/src/lib/queries/properties/definitions.ts
index 456b5cf557..b0945fc3f9 100644
--- a/apps/web/src/lib/queries/properties/definitions.ts
+++ b/apps/web/src/lib/queries/properties/definitions.ts
@@ -6,6 +6,7 @@ import { propertiesServiceClient } from '../../service-clients/service-propertie
import type { CreatePropertyDefinitionRequest } from '../../service-clients/service-properties/generated/schemas/createPropertyDefinitionRequest';
import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
import type { PropertyDefinition } from '../../service-clients/service-properties/generated/schemas/propertyDefinition';
+import type { PropertyDefinitionResponse } from '../../service-clients/service-properties/generated/schemas/propertyDefinitionResponse';
import type { PropertyScope } from '../../service-clients/service-properties/generated/schemas/propertyScope';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
@@ -46,6 +47,32 @@ export function useListPropertiesQuery(
});
}
+export async function fetchPropertyDefinitionWithOptions(
+ definitionId: string
+): Promise<PropertyDefinitionResponse | undefined> {
+ const data = await queryClient.fetchQuery({
+ queryKey: propertiesKeys.definitions({
+ scope: 'all',
+ includeOptions: true,
+ }).queryKey,
+ queryFn: async () =>
+ await throwOnErr(
+ async () =>
+ await propertiesServiceClient.listProperties({
+ scope: 'all',
+ include_options: true,
+ })
+ ),
+ staleTime: 0,
+ });
+
+ return data.find((item) =>
+ 'definition' in item
+ ? item.definition.id === definitionId
+ : item.id === definitionId
+ );
+}
+
function invalidatePropertyDefinitions() {
queryClient.invalidateQueries({
predicate: ({ queryKey }) =>