Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(properties): fully port properties to use tanstack query, + some cleanup (#966)
teo5339425acdc4
diff --git a/js/app/packages/app/component/PropertyFilter/FilterProperty.tsx b/js/app/packages/app/component/PropertyFilter/FilterProperty.tsxindex ce67243b7c..eb3e00b05a 100644--- a/js/app/packages/app/component/PropertyFilter/FilterProperty.tsx+++ b/js/app/packages/app/component/PropertyFilter/FilterProperty.tsx@@ -1,6 +1,7 @@-import { listPropertiesFlat } from '@core/component/Properties/utils';+import { isPropertyDefinition } from '@core/component/Properties/utils';import { PropertyDataTypeIcon } from '@core/component/Properties/utils/PropertyDataTypeIcon';import MagnifyingGlassIcon from '@phosphor-icons/core/assets/regular/magnifying-glass.svg';+import { useListPropertiesQuery } from '@queries/properties/definitions';import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';import type { Component } from 'solid-js';import {@@ -21,9 +22,6 @@ export type FilterPropertySelectProps = {export const FilterPropertySelect: Component<FilterPropertySelectProps> = (props) => {- const [availableProperties, setAvailableProperties] = createSignal<- PropertyDefinition[]- >([]);const [searchQuery, setSearchQuery] = createSignal('');const [isDropdownOpen, setIsDropdownOpen] = createSignal(false);@@ -31,10 +29,16 @@ export const FilterPropertySelect: Component<FilterPropertySelectProps> = (let dropdownRef!: HTMLDivElement;let containerRef!: HTMLDivElement;- const fetchAvailableProperties = async () => {- const properties = await listPropertiesFlat('all');- setAvailableProperties(properties);- };+ const propertiesQuery = useListPropertiesQuery(() => ({+ scope: 'all',+ includeOptions: false,+ }));++ const availableProperties = createMemo((): PropertyDefinition[] => {+ const data = propertiesQuery.data;+ if (!data) return [];+ return (Array.isArray(data) ? data : []).filter(isPropertyDefinition);+ });// Filter to only filterable properties (exclude COMPANY entity type)const filterableProperties = createMemo(() => {@@ -79,7 +83,6 @@ export const FilterPropertySelect: Component<FilterPropertySelectProps> = (};onMount(() => {- fetchAvailableProperties();// Autofocus the search inputsearchInputRef?.focus();document.addEventListener('mousedown', handleClickOutside);diff --git a/js/app/packages/app/component/PropertyFilterControl.tsx b/js/app/packages/app/component/PropertyFilterControl.tsxindex 86b298a424..1ebb251a96 100644--- a/js/app/packages/app/component/PropertyFilterControl.tsx+++ b/js/app/packages/app/component/PropertyFilterControl.tsx@@ -1,14 +1,8 @@-import { listPropertiesFlat } from '@core/component/Properties/utils';+import { isPropertyDefinition } from '@core/component/Properties/utils';+import { useListPropertiesQuery } from '@queries/properties/definitions';import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';import type { Accessor, Component } from 'solid-js';-import {- createEffect,- createMemo,- createSignal,- For,- onMount,- Show,-} from 'solid-js';+import { createEffect, createMemo, For, Show } from 'solid-js';import { createStore, reconcile } from 'solid-js/store';import { FilterPropertyPill } from './PropertyFilter';import type { PropertyFilter } from './PropertyFilterTypes';@@ -31,14 +25,16 @@ type PropertyFilterControlProps = {export const PropertyFilterControl: Component<PropertyFilterControlProps> = (props) => {- // Fetch all properties once for looking up saved filters- const [allProperties, setAllProperties] = createSignal<PropertyDefinition[]>(- []- );-- onMount(async () => {- const properties = await listPropertiesFlat('all');- setAllProperties(properties);+ // Fetch all properties using query+ const propertiesQuery = useListPropertiesQuery(() => ({+ scope: 'all',+ includeOptions: false,+ }));++ const allProperties = createMemo((): PropertyDefinition[] => {+ const data = propertiesQuery.data;+ if (!data) return [];+ return (Array.isArray(data) ? data : []).filter(isPropertyDefinition);});// Look up property definition by IDdiff --git a/js/app/packages/block-md/component/ComposeTask.tsx b/js/app/packages/block-md/component/ComposeTask.tsxindex e02220d987..6b6b311cc7 100644--- a/js/app/packages/block-md/component/ComposeTask.tsx+++ b/js/app/packages/block-md/component/ComposeTask.tsx@@ -368,14 +368,12 @@ export function ComposeTask(props: ComposeTaskProps) {const saveHandler: PropertySaveHandler = {saveProperty: async (property: Property, value: PropertyApiValues) => {setPropertyValues(property.propertyDefinitionId, value);- return { ok: true, value: undefined };},saveDate: async (property: Property, date: Date) => {setPropertyValues(property.propertyDefinitionId, {valueType: 'DATE',value: date.toISOString(),});- return { ok: true, value: undefined };},};diff --git a/js/app/packages/block-md/component/FrontMatterProperties.tsx b/js/app/packages/block-md/component/FrontMatterProperties.tsxindex 67b73a401d..4f64771f28 100644--- a/js/app/packages/block-md/component/FrontMatterProperties.tsx+++ b/js/app/packages/block-md/component/FrontMatterProperties.tsx@@ -5,7 +5,6 @@ import {dispatchInternalLayoutShift,REMOVE_PINNED_PROPERTY_COMMAND,} from '@core/component/LexicalMarkdown/plugins';-import { saveEntityProperty } from '@core/component/Properties/api';import { Modals } from '@core/component/Properties/component/modal';import { PanelContainer } from '@core/component/Properties/component/panel';import { getDefaultPinnedProperties } from '@core/component/Properties/constants';@@ -18,6 +17,7 @@ import type {Property,PropertyApiValues,} from '@core/component/Properties/types';+import { useSaveEntityPropertyMutation } from '@queries/properties/entity';import CaretDown from '@icon/bold/caret-down-bold.svg';import CaretRight from '@icon/bold/caret-right-bold.svg';import EyeSlash from '@icon/bold/eye-slash-bold.svg';@@ -32,6 +32,7 @@ import {on,onCleanup,Show,+ Suspense,} from 'solid-js';import {frontMatterPreference,@@ -141,103 +142,102 @@ export function FrontMatterProperties(props: FrontMatterPropertiesProps) {const height = () => containerSize.height;createEffect(on(height, layoutShift));+ const saveMutation = useSaveEntityPropertyMutation();+// Network-based save handler for FrontMatter propertiesconst saveHandler: PropertySaveHandler = {- saveProperty: async (property: Property, value: PropertyApiValues) => {- const result = await saveEntityProperty(- blockId,+ saveProperty: (property: Property, value: PropertyApiValues) =>+ saveMutation.mutateAsync({+ entityId: blockId,entityType,property,- value- );- if (result.ok) {- refetch();- }- return result;- },- saveDate: async (property: Property, date: Date) => {- const result = await saveEntityProperty(blockId, entityType, property, {- valueType: 'DATE',- value: date.toISOString(),- });- if (result.ok) {- refetch();- }- return result;- },+ apiValues: value,+ }),+ saveDate: (property: Property, date: Date) =>+ saveMutation.mutateAsync({+ entityId: blockId,+ entityType,+ property,+ apiValues: {+ valueType: 'DATE',+ value: date.toISOString(),+ },+ }),};return (<Show when={!error()} fallback={props.fallback}>- <div class="mt-6 mb-6" ref={setContainerRef}>- <PropertiesProvider- entityType={entityType}- canEdit={props.canEdit}- documentName={props.documentName}- properties={filteredPinnedProperties}- onRefresh={refetch}- onPropertyAdded={handlePropertyAdded}- onPropertyDeleted={handlePropertyDeleted}- onPropertyPinned={handlePropertyPinned}- onPropertyUnpinned={handlePropertyUnpinned}- pinnedPropertyIds={pinnedPropertyIds}- saveHandler={saveHandler}- >- {/* Collapsible header with horizontal line */}- <div class="flex items-center gap-2 pt-2">- <div class="w-6 border-t border-edge-muted" />- <button- class="flex items-center gap-1 px-2 cursor-pointer hover:opacity-70 transition-opacity"- onClick={toggleExpanded}- >- {isExpanded() ? (- <CaretDown class="w-3 h-3" />- ) : (- <CaretRight class="w-3 h-3" />- )}- <span class="text-xs">Properties</span>- </button>- <div class="flex-1 border-t border-edge-muted" />- </div>-- {/* Collapsible content */}- <Show when={isExpanded()}>- <div class="py-2 text-xs">- <Show when={isLoading()}>- <div class="flex items-center justify-center py-8">- <div class="w-5 h-5 animate-spin">- <LoadingSpinner />+ <Suspense>+ <div class="mt-6 mb-6" ref={setContainerRef}>+ <PropertiesProvider+ entityType={entityType}+ canEdit={props.canEdit}+ documentName={props.documentName}+ properties={filteredPinnedProperties}+ onRefresh={refetch}+ onPropertyAdded={handlePropertyAdded}+ onPropertyDeleted={handlePropertyDeleted}+ onPropertyPinned={handlePropertyPinned}+ onPropertyUnpinned={handlePropertyUnpinned}+ pinnedPropertyIds={pinnedPropertyIds}+ saveHandler={saveHandler}+ >+ {/* Collapsible header with horizontal line */}+ <div class="flex items-center gap-2 pt-2">+ <div class="w-6 border-t border-edge-muted" />+ <button+ class="flex items-center gap-1 px-2 cursor-pointer hover:opacity-70 transition-opacity"+ onClick={toggleExpanded}+ >+ {isExpanded() ? (+ <CaretDown class="w-3 h-3" />+ ) : (+ <CaretRight class="w-3 h-3" />+ )}+ <span class="text-xs">Properties</span>+ </button>+ <div class="flex-1 border-t border-edge-muted" />+ </div>++ {/* Collapsible content */}+ <Show when={isExpanded()}>+ <div class="py-2 text-xs">+ <Show when={isLoading()}>+ <div class="flex items-center justify-center py-8">+ <div class="w-5 h-5 animate-spin">+ <LoadingSpinner />+ </div></div>+ </Show>++ <Show when={error()}>+ <div class="text-failure-ink text-center py-4">{error()}</div>+ </Show>++ <PanelContainer+ properties={filteredPinnedProperties}+ isLoading={isLoading}+ error={error}+ emptyMessage="No properties pinned yet"+ />++ <div class="pt-4 pb-2">+ <button+ class="flex items-center gap-1 cursor-pointer opacity-75 hover:opacity-50 transition-opacity"+ onClick={toggleExpanded}+ >+ <EyeSlash class="w-3 h-3 mr-2" />+ <span class="text-ink-muted">Hide Properties</span>+ </button></div>- </Show>-- <Show when={error()}>- <div class="text-failure-ink text-center py-4">{error()}</div>- </Show>-- <PanelContainer- properties={filteredPinnedProperties}- isLoading={isLoading}- error={error}- emptyMessage="No properties pinned yet"- />-- <div class="pt-4 pb-2">- <button- class="flex items-center gap-1 cursor-pointer opacity-75 hover:opacity-50 transition-opacity"- onClick={toggleExpanded}- >- <EyeSlash class="w-3 h-3 mr-2" />- <span class="text-ink-muted">Hide Properties</span>- </button>- </div>- <Modals />- </div>- <div class="border-t border-edge-muted pt-2" />- </Show>- </PropertiesProvider>- </div>+ <Modals />+ </div>+ <div class="border-t border-edge-muted pt-2" />+ </Show>+ </PropertiesProvider>+ </div>+ </Suspense></Show>);}diff --git a/js/app/packages/core/component/Properties/PropertiesView.tsx b/js/app/packages/core/component/Properties/PropertiesView.tsxindex 45e3ef6b64..ea0f4bcfc9 100644--- a/js/app/packages/core/component/Properties/PropertiesView.tsx+++ b/js/app/packages/core/component/Properties/PropertiesView.tsx@@ -1,7 +1,7 @@import { useBlockId } from '@core/block';import LoadingSpinner from '@icon/regular/spinner.svg';+import { useSaveEntityPropertyMutation } from '@queries/properties/entity';import { type Accessor, createMemo, Show } from 'solid-js';-import { saveEntityProperty } from './api';import { Modals } from './component/modal/Modals';import { AddPropertyButton } from './component/panel/AddPropertyButton';import { PanelContainer } from './component/panel/PanelContainer';@@ -30,6 +30,8 @@ export function PropertiesView(props: PropertiesPanelProps) {true // includeMetadata);+ const saveMutation = useSaveEntityPropertyMutation();+const handleRefresh = () => {refetch();props.onRefresh?.();@@ -48,33 +50,23 @@ export function PropertiesView(props: PropertiesPanelProps) {};const saveHandler: PropertySaveHandler = {- saveProperty: async (property: Property, value: PropertyApiValues) => {- const result = await saveEntityProperty(- blockId,- props.entityType,+ saveProperty: (property: Property, value: PropertyApiValues) =>+ saveMutation.mutateAsync({+ entityId: blockId,+ entityType: props.entityType,property,- value- );- if (result.ok) {- refetch();- }- return result;- },- saveDate: async (property: Property, date: Date) => {- const result = await saveEntityProperty(- blockId,- props.entityType,+ apiValues: value,+ }),+ saveDate: (property: Property, date: Date) =>+ saveMutation.mutateAsync({+ entityId: blockId,+ entityType: props.entityType,property,- {+ apiValues: {valueType: 'DATE',value: date.toISOString(),- }- );- if (result.ok) {- refetch();- }- return result;- },+ },+ }),};return (diff --git a/js/app/packages/core/component/Properties/api/fetchProperties.ts b/js/app/packages/core/component/Properties/api/fetchProperties.tsdeleted file mode 100644index efff3de331..0000000000--- a/js/app/packages/core/component/Properties/api/fetchProperties.ts+++ /dev/null@@ -1,55 +0,0 @@-import { isErr } from '@core/util/maybeResult';-import { propertiesServiceClient } from '@service-properties/client';-import type { EntityType } from '@service-properties/generated/schemas/entityType';-import type { Property, Result } from '../types';-import { ERROR_MESSAGES } from '../utils/errorHandling';-import { entityPropertyFromApi } from './converters';--export async function fetchEntityProperties(- entityId: string,- entityType: EntityType,- includeMetadata: boolean-): Promise<Result<Property[]>> {- try {- const result = await propertiesServiceClient.getEntityProperties({- entity_type: entityType,- entity_id: entityId,- query: {- include_metadata: includeMetadata,- },- });-- if (isErr(result)) {- console.error(- 'api.properties.fetchEntityProperties:',- result,- ERROR_MESSAGES.PROPERTY_FETCH- );- return {- ok: false,- error: {- code: 'API_ERROR',- message: ERROR_MESSAGES.PROPERTY_FETCH,- },- };- }-- const [, data] = result;- const properties = data.properties.map(entityPropertyFromApi);-- return { ok: true, value: properties };- } catch (error) {- console.error(- 'api.properties.fetchEntityProperties:',- error,- ERROR_MESSAGES.PROPERTY_FETCH- );- return {- ok: false,- error: {- code: 'EXCEPTION',- message: error instanceof Error ? error.message : 'Unknown error',- },- };- }-}diff --git a/js/app/packages/core/component/Properties/api/index.ts b/js/app/packages/core/component/Properties/api/index.tsindex 32ca096c67..59e7503e27 100644--- a/js/app/packages/core/component/Properties/api/index.ts+++ b/js/app/packages/core/component/Properties/api/index.ts@@ -1,7 +1 @@export { entityPropertyFromApi, propertyValueToApi } from './converters';-export { fetchEntityProperties } from './fetchProperties';-export {- addEntityProperty,- deleteEntityProperty,- saveEntityProperty,-} from './propertyValues';diff --git a/js/app/packages/core/component/Properties/api/propertyValues.ts b/js/app/packages/core/component/Properties/api/propertyValues.tsdeleted file mode 100644index f85ab76535..0000000000--- a/js/app/packages/core/component/Properties/api/propertyValues.ts+++ /dev/null@@ -1,164 +0,0 @@-import { isErr } from '@core/util/maybeResult';-import { propertiesServiceClient } from '@service-properties/client';-import type { EntityType } from '@service-properties/generated/schemas/entityType';-import type { Property, PropertyApiValues, Result } from '../types';-import { ERROR_MESSAGES } from '../utils/errorHandling';-import { propertyValueToApi } from './converters';--/**- * Save an entity property value- *- * @param entityId - The ID of the entity- * @param entityType - The type of entity (e.g., 'document', 'channel', 'project')- * @param property - The property to save- * @param apiValues - The values to save- */-export async function saveEntityProperty(- entityId: string,- entityType: EntityType,- property: Property,- apiValues: PropertyApiValues-): Promise<Result<void>> {- try {- const propertyValue = propertyValueToApi(apiValues, property.isMultiSelect);-- const result = await propertiesServiceClient.setEntityProperty({- entity_type: entityType,- entity_id: entityId,- property_id: property.propertyDefinitionId,- body: {- value: propertyValue,- },- });-- if (isErr(result)) {- console.error(- 'api.propertyValues.saveEntityProperty:',- result,- ERROR_MESSAGES.PROPERTY_SAVE- );- return {- ok: false,- error: {- code: 'API_ERROR',- message: ERROR_MESSAGES.PROPERTY_SAVE,- },- };- }-- return { ok: true, value: undefined };- } catch (error) {- console.error(- 'api.propertyValues.saveEntityProperty:',- error,- ERROR_MESSAGES.PROPERTY_SAVE- );- return {- ok: false,- error: {- code: 'EXCEPTION',- message: error instanceof Error ? error.message : 'Unknown error',- },- };- }-}--/**- * Delete a property from an entity- */-export async function deleteEntityProperty(- entityPropertyId: string-): Promise<Result<void>> {- try {- const result = await propertiesServiceClient.deleteEntityProperty({- entity_property_id: entityPropertyId,- });-- if (isErr(result)) {- console.error(- 'api.propertyValues.deleteEntityProperty:',- result,- ERROR_MESSAGES.PROPERTY_DELETE- );- return {- ok: false,- error: {- code: 'API_ERROR',- message: ERROR_MESSAGES.PROPERTY_DELETE,- },- };- }-- return { ok: true, value: undefined };- } catch (error) {- console.error(- 'api.propertyValues.deleteEntityProperty:',- error,- ERROR_MESSAGES.PROPERTY_DELETE- );- return {- ok: false,- error: {- code: 'EXCEPTION',- message: error instanceof Error ? error.message : 'Unknown error',- },- };- }-}--/**- * Add an entity property without an initial value- *- * The backend supports attaching properties without values. Users can set the value later.- * This is simpler and works for all property types (string, number, select, entity, etc.)- *- * @param entityId - The ID of the entity- * @param entityType - The type of entity (e.g., 'document', 'channel', 'project')- * @param propertyDefinitionId - The ID of the property definition to add- */-export async function addEntityProperty(- entityId: string,- entityType: EntityType,- propertyDefinitionId: string-): Promise<Result<void>> {- try {- const result = await propertiesServiceClient.setEntityProperty({- entity_type: entityType,- entity_id: entityId,- property_id: propertyDefinitionId,- body: {- value: null,- },- });-- if (isErr(result)) {- console.error(- 'api.propertyValues.addEntityProperty:',- result,- ERROR_MESSAGES.PROPERTY_ADD- );- return {- ok: false,- error: {- code: 'API_ERROR',- message: ERROR_MESSAGES.PROPERTY_ADD,- },- };- }-- return { ok: true, value: undefined };- } catch (error) {- console.error(- 'api.propertyValues.addEntityProperty:',- error,- ERROR_MESSAGES.PROPERTY_ADD- );- return {- ok: false,- error: {- code: 'EXCEPTION',- message: error instanceof Error ? error.message : 'Unknown error',- },- };- }-}diff --git a/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsx b/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsxindex 1f4eb7eb07..1f5fe2876f 100644--- a/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsx+++ b/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsx@@ -1,11 +1,10 @@import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import { useOrganizationId } from '@core/user';-import { isErr } from '@core/util/maybeResult';import { MODAL_VIEWPORT_CLASSES } from '@core/util/modalUtils';import LoadingSpinner from '@icon/regular/spinner.svg';import XIcon from '@icon/regular/x.svg';+import { useCreatePropertyDefinitionMutation } from '@queries/properties/definitions';import { useUserId } from '@service-gql/client';-import { propertiesServiceClient } from '@service-properties/client';import type { EntityType } from '@service-properties/generated/schemas/entityType';import type { PropertyDataType } from '@service-properties/generated/schemas/propertyDataType';import {@@ -121,7 +120,6 @@ interface CreatePropertyModalProps {export const CreatePropertyModal: Component<CreatePropertyModalProps> = (props) => {- const [isCreatingProperty, setIsCreatingProperty] = createSignal(false);const [newPropertyName, setNewPropertyName] = createSignal('');const [selectedDataType, setSelectedDataType] =createSignal<DataTypeValue>('string');@@ -134,6 +132,17 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (>([]);const [error, setError] = createSignal<string | null>(null);+ const createPropertyMutation = useCreatePropertyDefinitionMutation({+ onSuccess: () => {+ resetCreateForm();+ props.onPropertyCreated?.();+ props.onClose();+ },+ onError: () => {+ setError(ERROR_MESSAGES.PROPERTY_CREATE);+ },+ });+// Unified option management helperstype Option<T> = { id: string; value: T; display_order: number };@@ -287,7 +296,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (}};- const handleCreateProperty = async () => {+ const handleCreateProperty = () => {const orgId = organizationId();const currentUserId = userId();@@ -325,42 +334,24 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (return;}- setIsCreatingProperty(true);setError(null);- try {- const bodyData = orgId- ? {- scope: 'user_and_organization' as const,- organization_id: Number(orgId),- user_id: currentUserId!,- display_name: newPropertyName().trim(),- data_type: buildDataType(),- }- : {- scope: 'user' as const,- user_id: currentUserId!,- display_name: newPropertyName().trim(),- data_type: buildDataType(),- };-- const result = await propertiesServiceClient.createPropertyDefinition({- body: bodyData,- });-- if (isErr(result)) {- setError(ERROR_MESSAGES.PROPERTY_CREATE);- return;- }+ const bodyData = orgId+ ? {+ scope: 'user_and_organization' as const,+ organization_id: Number(orgId),+ user_id: currentUserId!,+ display_name: newPropertyName().trim(),+ data_type: buildDataType(),+ }+ : {+ scope: 'user' as const,+ user_id: currentUserId!,+ display_name: newPropertyName().trim(),+ data_type: buildDataType(),+ };- resetCreateForm();- props.onPropertyCreated?.();- props.onClose();- } catch (_error) {- setError(ERROR_MESSAGES.PROPERTY_CREATE);- } finally {- setIsCreatingProperty(false);- }+ createPropertyMutation.mutate({ body: bodyData });};const resetCreateForm = () => {@@ -580,19 +571,21 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (resetCreateForm();props.onClose();}}- disabled={isCreatingProperty()}+ disabled={createPropertyMutation.isPending}>Cancel</button></div><buttontype="button"- class={`${PROPERTY_STYLES.button.base} ${PROPERTY_STYLES.button.accent} ${newPropertyName().trim() && !isCreatingProperty() ? '' : 'cursor-not-allowed'}`}+ class={`${PROPERTY_STYLES.button.base} ${PROPERTY_STYLES.button.accent} ${newPropertyName().trim() && !createPropertyMutation.isPending ? '' : 'cursor-not-allowed'}`}onClick={handleCreateProperty}- disabled={!newPropertyName().trim() || isCreatingProperty()}+ disabled={+ !newPropertyName().trim() || createPropertyMutation.isPending+ }><Show- when={!isCreatingProperty()}+ when={!createPropertyMutation.isPending}fallback={<div class="flex items-center gap-1.5"><div class="w-3 h-3 animate-spin">diff --git a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsxindex c8df3bdeb3..b64d7a1f20 100644--- a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx+++ b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx@@ -24,12 +24,35 @@ import {} from '../../utils/entityConversion';import { PropertyEntitySelector } from './shared/PropertyEntitySelector';import { PropertyOptionSelector } from './shared/PropertyOptionSelector';+import {+ useAddPropertyOptionMutation,+ usePropertyOptionsQuery,+} from '@queries/properties/options';// Common CSS classesconst MODAL_BASE ='absolute bg-menu border border-edge-muted max-h-96 overflow-hidden flex flex-col w-full max-w-md';export function EditPropertyValueModal(props: PropertyEditorProps) {+ const propertyOptionsQuery = usePropertyOptionsQuery(+ () => props.property.propertyDefinitionId+ );++ const addPropertyOptionMutation = useAddPropertyOptionMutation({});++ const propertyOptions = createMemo(() => {+ if (+ propertyOptionsQuery.isLoading ||+ propertyOptionsQuery.isError ||+ !propertyOptionsQuery.data+ )+ return [];+ return propertyOptionsQuery.data;+ });++ const isLoading = () =>+ propertyOptionsQuery.isLoading || addPropertyOptionMutation.isPending;+const { saveHandler } = usePropertiesContext();let modalRef!: HTMLDivElement;@@ -48,15 +71,19 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {);const {- state: editorState,- fetchOptions,+ selectedOptions,+ hasChanges,initializeSelectedOptions,toggleOption,addOption,- } = usePropertyEditor(props.property);+ } = usePropertyEditor(+ props.property,+ propertyOptions,+ addPropertyOptionMutation.mutateAsync+ );const saveChanges = async () => {- const selectedArray = Array.from(editorState().selectedOptions);+ const selectedArray = Array.from(selectedOptions());let apiValues: PropertyApiValues;@@ -124,8 +151,8 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {const handleClose = async () => {// All properties that reach this modal (select and entity types) should auto-save- const hasChanges = editorState().hasChanges || hasEntityChanges();- if (hasChanges) {+ const hasUnsavedChanges = hasChanges() || hasEntityChanges();+ if (hasUnsavedChanges) {await saveChanges();} else {props.onClose();@@ -134,12 +161,7 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {onMount(() => {initializeSelectedOptions();- if (- props.property.valueType === 'SELECT_STRING' ||- props.property.valueType === 'SELECT_NUMBER'- ) {- fetchOptions();- }+ propertyOptionsQuery.refetch();// Attach hotkeys to modal elementattachHotkeys(modalRef);@@ -206,71 +228,53 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {})()}onClick={(e) => e.stopPropagation()}>- <div class="bg-dialog text-ink">- {/*<div class={HEADER_CLASSES}>+ <Show when={!isLoading()}>+ <div class="bg-dialog text-ink"><div>- <h3 class="text-base font-semibold text-ink">- {props.property.displayName}- </h3>- <p class="text-xs text-ink-muted mt-1">- {`${props.property.isMultiSelect ? 'Multi-select ' : ''}${getValueTypeDisplay(props.property)}`}- </p>- </div>- <div class="flex items-center gap-2">- <DeprecatedIconButton- icon={XIcon}- theme="clear"- size="sm"- onClick={handleClose}- />- </div>- </div>*/}-- <div>- <Show- when={- props.property.valueType === 'SELECT_STRING' ||- props.property.valueType === 'SELECT_NUMBER'- }- fallback={- <Show when={props.property.valueType === 'ENTITY'}>- <PropertyEntitySelector- property={props.property}- selectedOptions={() => {- const refs = selectedEntityRefs();- return entityReferencesToIdSet(refs);- }}- setSelectedOptions={(newOptions, entityInfo) => {- const currentRefs = selectedEntityRefs();- const updatedRefs = updateEntityReferences(- currentRefs,- newOptions,- entityInfo- );- setSelectedEntityRefs(updatedRefs);- }}- setHasChanges={() => {}} // Not needed with new hook- onClose={handleClose}- />- </Show>- }- >- <PropertyOptionSelector- property={props.property}- options={editorState().options}- isLoading={editorState().isLoading}- error={editorState().error}- selectedOptions={() => editorState().selectedOptions}- onToggleOption={toggleOption}- onRetry={fetchOptions}- onAddOption={- props.property.isSystemProperty ? undefined : addOption+ <Show+ when={+ props.property.valueType === 'SELECT_STRING' ||+ props.property.valueType === 'SELECT_NUMBER'}- onClose={handleClose}- />- </Show>+ fallback={+ <Show when={props.property.valueType === 'ENTITY'}>+ <PropertyEntitySelector+ property={props.property}+ selectedOptions={() => {+ const refs = selectedEntityRefs();+ return entityReferencesToIdSet(refs);+ }}+ setSelectedOptions={(newOptions, entityInfo) => {+ const currentRefs = selectedEntityRefs();+ const updatedRefs = updateEntityReferences(+ currentRefs,+ newOptions,+ entityInfo+ );+ setSelectedEntityRefs(updatedRefs);+ }}+ setHasChanges={() => {}} // Not needed with new hook+ onClose={handleClose}+ />+ </Show>+ }+ >+ <PropertyOptionSelector+ property={props.property}+ options={propertyOptions()}+ isLoading={false}+ error={null}+ selectedOptions={selectedOptions}+ onToggleOption={toggleOption}+ onAddOption={+ props.property.isSystemProperty ? undefined : addOption+ }+ onClose={handleClose}+ />+ </Show>+ </div></div>- </div>+ </Show></div></div></ScopedPortal>diff --git a/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsx b/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsxindex 23fddc7a02..e2176c9e1f 100644--- a/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsx+++ b/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsx@@ -1,24 +1,27 @@import { useBlockId } from '@core/block';import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';-import { toast } from '@core/component/Toast/Toast';import { MODAL_VIEWPORT_CLASSES } from '@core/util/modalUtils';import CheckIcon from '@icon/bold/check-bold.svg';import SearchIcon from '@icon/regular/magnifying-glass.svg';import LoadingSpinner from '@icon/regular/spinner.svg';import XIcon from '@icon/regular/x.svg';-import { createEffect, createSignal, For, Show } from 'solid-js';+import { useAddEntityPropertyMutation } from '@queries/properties/entity';+import { createEffect, createMemo, createSignal, For, Show } from 'solid-js';import { Portal } from 'solid-js/web';-import { addEntityProperty } from '../../api';import { MODAL_DIMENSIONS } from '../../constants';import { usePropertiesContext } from '../../context/PropertiesContext';import { usePropertySelection } from '../../hooks/usePropertySelection';import { PROPERTY_STYLES } from '../../styles';-import type { PropertySelectorProps } from '../../types';+import type {+ PropertyDefinitionFlat,+ PropertySelectorProps,+} from '../../types';import {getPropertyDefinitionTypeDisplay,useSearchInputFocus,} from '../../utils';-import { ERROR_MESSAGES, handlePropertyError } from '../../utils/errorHandling';+import { useListPropertiesQuery } from '@queries/properties/definitions';+export function SelectPropertyModal(props: PropertySelectorProps) {const blockId = useBlockId();const { entityType, onPropertyAdded, openCreateProperty } =@@ -26,22 +29,50 @@ export function SelectPropertyModal(props: PropertySelectorProps) {const [isAdding, setIsAdding] = createSignal(false);const [searchQuery, setSearchQuery] = createSignal('');+ const addMutation = useAddEntityPropertyMutation();++ const listPropertiesQuery = useListPropertiesQuery(() => ({+ scope: 'all',+ includeOptions: true,+ forEntityType: entityType,+ }));++ const availableProperties = createMemo((): PropertyDefinitionFlat[] => {+ if (+ listPropertiesQuery.isLoading ||+ listPropertiesQuery.isError ||+ !listPropertiesQuery.data+ ) {+ return [];+ }++ const data = listPropertiesQuery.data;++ const properties = Array.isArray(data) ? data : [];+ return properties.map((item) => {+ if ('definition' in item) {+ return {+ ...item.definition,+ propertyOptions: item.property_options || [],+ };+ }+ return {+ ...item,+ propertyOptions: [],+ };+ });+ });+let searchInputRef!: HTMLInputElement;let modalRef!: HTMLDivElement;- const {- state,- filteredProperties,- fetchAvailableProperties,- togglePropertySelection,- } = usePropertySelection(- props.existingPropertyIds,- () => searchQuery(),- entityType- );+ const { selectedPropertyIds, filteredProperties, togglePropertySelection } =+ usePropertySelection(props.existingPropertyIds, availableProperties, () =>+ searchQuery()+ );const handleAddProperties = async () => {- const selected = state().selectedPropertyIds;+ const selected = selectedPropertyIds();if (selected.size === 0) return;setIsAdding(true);@@ -49,38 +80,28 @@ export function SelectPropertyModal(props: PropertySelectorProps) {try {const addPromises = Array.from(selected).map(async (propertyDefinitionId) => {- const result = await addEntityProperty(- blockId,- entityType,- propertyDefinitionId- );-- return handlePropertyError(- result,- ERROR_MESSAGES.PROPERTY_ADD,- 'SelectPropertyModal.handleAddProperties'- );+ try {+ await addMutation.mutateAsync({+ entityId: blockId,+ entityType,+ propertyDefinitionId,+ });+ return true;+ } catch {+ // Error toast is shown by mutation's onError callback+ return false;+ }});const results = await Promise.all(addPromises);- const failures = results.filter((success) => !success);+ const allSucceeded = results.every(Boolean);- // Close modal regardless of success/failure (toasts already shown)props.onClose();- if (failures.length === 0) {+ if (allSucceeded) {onPropertyAdded();}- } catch (error) {- // Handle unexpected exceptions (e.g., Promise.all rejection)- console.error(- 'SelectPropertyModal.handleAddProperties:',- error,- ERROR_MESSAGES.PROPERTY_ADD- );- toast.failure(ERROR_MESSAGES.PROPERTY_ADD);- props.onClose();} finally {setIsAdding(false);}@@ -112,12 +133,11 @@ export function SelectPropertyModal(props: PropertySelectorProps) {useSearchInputFocus(() => searchInputRef,- () => props.isOpen && state().availableProperties.length > 0+ () => props.isOpen && availableProperties().length > 0);createEffect(() => {if (props.isOpen) {- fetchAvailableProperties();setSearchQuery('');}});@@ -169,7 +189,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {/></div>- <Show when={state().availableProperties.length > 0}>+ <Show when={availableProperties().length > 0}><div class="px-4 pb-2"><div class="relative"><div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none z-10">@@ -189,7 +209,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {<div class="px-4 pb-2 overflow-y-auto max-h-[60vh]"><Show- when={!state().isLoading}+ when={!listPropertiesQuery.isLoading}fallback={<div class="flex items-center justify-center py-8"><div class="w-5 h-5 animate-spin">@@ -199,25 +219,9 @@ export function SelectPropertyModal(props: PropertySelectorProps) {</div>}>- <Show- when={!state().error}- fallback={- <div class="text-center py-6">- <div class="text-failure-ink mb-3 text-sm">- {state().error}- </div>- <button- type="button"- onClick={fetchAvailableProperties}- class="px-3 py-1.5 bg-accent text-accent-ink text-sm hover:bg-accent/90"- >- Retry- </button>- </div>- }- >+ <Show when={!listPropertiesQuery.error}><Show- when={state().availableProperties.length > 0}+ when={availableProperties().length > 0}fallback={<div class="text-center py-6"><div class="text-ink-muted text-sm">@@ -238,7 +242,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {<For each={filteredProperties()}>{(property) => {const isSelected = () =>- state().selectedPropertyIds.has(property.id);+ selectedPropertyIds().has(property.id);return (<button@@ -292,12 +296,12 @@ export function SelectPropertyModal(props: PropertySelectorProps) {>Cancel</button>- <Show when={state().selectedPropertyIds.size > 0}>+ <Show when={selectedPropertyIds().size > 0}><buttontype="button"- class={`${PROPERTY_STYLES.button.base} ${state().selectedPropertyIds.size > 0 && !isAdding() ? PROPERTY_STYLES.button.accent : 'bg-ink-muted text-ink cursor-not-allowed'}`}+ class={`${PROPERTY_STYLES.button.base} ${selectedPropertyIds().size > 0 && !isAdding() ? PROPERTY_STYLES.button.accent : 'bg-ink-muted text-ink cursor-not-allowed'}`}onClick={handleAddProperties}- disabled={state().selectedPropertyIds.size === 0 || isAdding()}+ disabled={selectedPropertyIds().size === 0 || isAdding()}><Showwhen={!isAdding()}@@ -311,13 +315,13 @@ export function SelectPropertyModal(props: PropertySelectorProps) {}>Add{' '}- {state().selectedPropertyIds.size > 0- ? `(${state().selectedPropertyIds.size})`+ {selectedPropertyIds().size > 0+ ? `(${selectedPropertyIds().size})`: ''}</Show></button></Show>- <Show when={state().selectedPropertyIds.size === 0}>+ <Show when={selectedPropertyIds().size === 0}><div class="flex gap-2"><buttontype="button"@@ -326,7 +330,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {openCreateProperty();}}class={`${PROPERTY_STYLES.button.base} ${PROPERTY_STYLES.button.accent}`}- disabled={state().isLoading}+ disabled={false}>Create New Property</button>diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsxindex af3c499bf0..e0f8ba5827 100644--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx@@ -28,7 +28,6 @@ type SelectOptionsProps = {error: string | null;selectedOptions: () => Set<string>;onToggleOption: (value: string) => void;- onRetry: () => void;onAddOption?: (value: string) => Promise<void>;onClose?: () => void;};@@ -266,20 +265,7 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {</div>}>- <Show- when={!props.error}- fallback={- <div class="text-center py-6">- <div class="text-failure-ink mb-3 text-sm">{props.error}</div>- <button- onClick={props.onRetry}- class="px-3 py-1.5 bg-accent text-ink text-sm hover:bg-accent/90"- >- Retry- </button>- </div>- }- >+ <Show when={!props.error}><div><div class="relative"><div class="flex w-full items-center py-1 gap-2 px-2 border-b border-edge-muted">diff --git a/js/app/packages/core/component/Properties/component/panel/PropertyLabel.tsx b/js/app/packages/core/component/Properties/component/panel/PropertyLabel.tsxindex 201dc339b7..f9edb495e2 100644--- a/js/app/packages/core/component/Properties/component/panel/PropertyLabel.tsx+++ b/js/app/packages/core/component/Properties/component/panel/PropertyLabel.tsx@@ -1,12 +1,12 @@-import { useMaybeBlockAliasedName } from '@core/block';+import { useBlockId, useMaybeBlockAliasedName } from '@core/block';import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import DeleteIcon from '@icon/bold/x-bold.svg';import PinIcon from '@icon/regular/push-pin.svg';import UnpinIcon from '@icon/regular/push-pin-slash.svg';import XIcon from '@icon/regular/x.svg';import { Dialog } from '@kobalte/core/dialog';+import { useDeleteEntityPropertyMutation } from '@queries/properties/entity';import { type Component, createMemo, createSignal, Show } from 'solid-js';-import { deleteEntityProperty } from '../../api';import {getBuiltinPropertyIds,getDefaultPinnedProperties,@@ -25,11 +25,13 @@ export const PropertyLabel: Component<PropertyLabelProps> = (props) => {const {canEdit,documentName,+ entityType,onPropertyDeleted,onPropertyPinned,onPropertyUnpinned,pinnedPropertyIds,} = usePropertiesContext();+ const blockId = useBlockId();const blockName = useMaybeBlockAliasedName();const isBuiltin =blockName &&@@ -42,12 +44,13 @@ export const PropertyLabel: Component<PropertyLabelProps> = (props) => {props.property.propertyDefinitionId);+ const deleteMutation = useDeleteEntityPropertyMutation();+const isPinned = createMemo(() => pinnedPropertyIds?.()?.includes(props.property.propertyId) ?? false);const [isHovered, setIsHovered] = createSignal(false);const [deleteConfirmVisible, setDeleteConfirmVisible] = createSignal(false);- const [isDeleting, setIsDeleting] = createSignal(false);const handlePinClick = () => {if (isPinned()) {@@ -62,15 +65,17 @@ export const PropertyLabel: Component<PropertyLabelProps> = (props) => {};const handleDeleteConfirm = async () => {- setIsDeleting(true);- const result = await deleteEntityProperty(props.property.propertyId);-- if (result.ok) {+ try {+ await deleteMutation.mutateAsync({+ entityPropertyId: props.property.propertyId,+ entityType,+ entityId: blockId,+ });setDeleteConfirmVisible(false);onPropertyDeleted();+ } catch {+ // Error toast is shown by the mutation's onError callback}-- setIsDeleting(false);};const handleDeleteCancel = () => {@@ -160,7 +165,7 @@ export const PropertyLabel: Component<PropertyLabelProps> = (props) => {theme="clear"size="sm"onClick={handleDeleteCancel}- disabled={isDeleting()}+ disabled={deleteMutation.isPending}/></div><div class="px-4 pb-4">@@ -172,17 +177,17 @@ export const PropertyLabel: Component<PropertyLabelProps> = (props) => {<div class="flex justify-end gap-2"><buttononClick={handleDeleteCancel}- disabled={isDeleting()}+ disabled={deleteMutation.isPending}class="px-3 py-1.5 text-sm border text-ink-muted hover:text-ink border-edge hover:bg-hover">Cancel</button><buttononClick={handleDeleteConfirm}- disabled={isDeleting()}+ disabled={deleteMutation.isPending}class="px-3 py-1.5 text-sm border bg-failure/90 hover:bg-failure/80 text-ink disabled:opacity-50">- {isDeleting() ? 'Deleting...' : 'Delete'}+ {deleteMutation.isPending ? 'Deleting...' : 'Delete'}</button></div></div>diff --git a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsxindex 0155d4656e..07e85fabfd 100644--- a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx+++ b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx@@ -3,7 +3,6 @@ import { createSignal, Show } from 'solid-js';import { usePropertiesContext } from '../../context/PropertiesContext';import type { Property } from '../../types';import { formatDate } from '../../utils';-import { ERROR_MESSAGES, handlePropertyError } from '../../utils/errorHandling';import { EmptyValue, PropertyValueDeleteButton } from './ValueComponents';type DateValueProps = {@@ -34,20 +33,13 @@ export const DateValue: Component<DateValueProps> = (props) => {setIsSaving(true);try {- const result = await saveHandler.saveProperty(props.property, {+ await saveHandler.saveProperty(props.property, {valueType: 'DATE',value: null,});-- if (- handlePropertyError(- result,- ERROR_MESSAGES.PROPERTY_SAVE,- 'DateValue.handleDelete'- )- ) {- props.onRefresh?.();- }+ props.onRefresh?.();+ } catch {+ // Error toast is shown by mutation's onError callback} finally {setIsSaving(false);}diff --git a/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsxindex 166a0d49fb..d63c08b031 100644--- a/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsx+++ b/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsx@@ -5,7 +5,6 @@ import { createSignal, For, Show } from 'solid-js';import { usePropertiesContext } from '../../context/PropertiesContext';import type { Property } from '../../types';import { getEntityValues } from '../../utils';-import { ERROR_MESSAGES, handlePropertyError } from '../../utils/errorHandling';import { EntityIcon } from './EntityIcon';import { AddPropertyValueButton, EmptyValue } from './ValueComponents';@@ -50,20 +49,13 @@ export const EntityValue: Component<EntityValueProps> = (props) => {entity.entity_type !== entityToRemove.entity_type);- const result = await saveHandler.saveProperty(props.property, {+ await saveHandler.saveProperty(props.property, {valueType: 'ENTITY',refs: newValues.length > 0 ? newValues : null,});-- if (- handlePropertyError(- result,- ERROR_MESSAGES.PROPERTY_SAVE,- 'EntityValue.handleRemoveEntity'- )- ) {- props.onRefresh?.();- }+ props.onRefresh?.();+ } catch {+ // Error toast is shown by mutation's onError callback} finally {setIsSaving(false);}diff --git a/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsxindex 884fa732c3..38a3a338c1 100644--- a/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsx+++ b/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsx@@ -13,7 +13,6 @@ import {isValidUrl,normalizeUrl,} from '../../utils';-import { ERROR_MESSAGES } from '../../utils/errorHandling';import {AddPropertyValueButton,EmptyValue,@@ -81,19 +80,14 @@ export const LinkValue: Component<LinkValueProps> = (props) => {newValues = [normalized];}- const result = await saveHandler.saveProperty(props.property, {+ await saveHandler.saveProperty(props.property, {valueType: 'LINK',values: newValues,});-- if (result.ok) {- cancelAdding();- props.onRefresh?.();- } else {- setError(ERROR_MESSAGES.PROPERTY_SAVE);- }- } catch (_err) {- setError(ERROR_MESSAGES.PROPERTY_SAVE);+ cancelAdding();+ props.onRefresh?.();+ } catch {+ // Error toast is shown by mutation's onError callback} finally {setIsSaving(false);}@@ -107,14 +101,13 @@ export const LinkValue: Component<LinkValueProps> = (props) => {try {const newValues = linkValues.filter((link: string) => link !== url);- const result = await saveHandler.saveProperty(props.property, {+ await saveHandler.saveProperty(props.property, {valueType: 'LINK',values: newValues.length > 0 ? newValues : null,});-- if (result.ok) {- props.onRefresh?.();- }+ props.onRefresh?.();+ } catch {+ // Error toast is shown by mutation's onError callback} finally {setIsSaving(false);}diff --git a/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsxindex 05a01f0181..25463346cc 100644--- a/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsx+++ b/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsx@@ -5,7 +5,6 @@ import { usePropertiesContext } from '../../context/PropertiesContext';import { PROPERTY_STYLES } from '../../styles/styles';import type { Property } from '../../types';import { formatPropertyValue, getSelectValues } from '../../utils';-import { ERROR_MESSAGES, handlePropertyError } from '../../utils/errorHandling';import { PropertyValueIcon } from './PropertyValueIcon';import {AddPropertyValueButton,@@ -50,20 +49,13 @@ export const SelectValue: Component<SelectValueProps> = (props) => {return;}- const result = await saveHandler.saveProperty(props.property, {+ await saveHandler.saveProperty(props.property, {valueType,values: newValues.length > 0 ? newValues : null,});-- if (- handlePropertyError(- result,- ERROR_MESSAGES.PROPERTY_SAVE,- 'SelectValue.handleRemoveValue'- )- ) {- props.onRefresh?.();- }+ props.onRefresh?.();+ } catch {+ // Error toast is shown by mutation's onError callback} finally {setIsSaving(false);}diff --git a/js/app/packages/core/component/Properties/context/PropertiesContext.tsx b/js/app/packages/core/component/Properties/context/PropertiesContext.tsxindex ed7ebe319b..ed2fd7ab49 100644--- a/js/app/packages/core/component/Properties/context/PropertiesContext.tsx+++ b/js/app/packages/core/component/Properties/context/PropertiesContext.tsx@@ -7,7 +7,7 @@ import {type ParentProps,useContext,} from 'solid-js';-import type { Property, PropertyApiValues, Result } from '../types';+import type { Property, PropertyApiValues } from '../types';// Specific modal state types with proper typingexport interface PropertySelectorModalState {@@ -29,11 +29,8 @@ export interface CreatePropertyModalState {}export interface PropertySaveHandler {- saveProperty: (- property: Property,- value: PropertyApiValues- ) => Promise<Result<void>>;- saveDate: (property: Property, date: Date) => Promise<Result<void>>;+ saveProperty: (property: Property, value: PropertyApiValues) => Promise<void>;+ saveDate: (property: Property, date: Date) => Promise<void>;}export interface PropertiesContextValue {diff --git a/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsx b/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsxindex b20e7e896d..b2dd96a09d 100644--- a/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsx+++ b/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsx@@ -183,7 +183,6 @@ const PropertiesDebug: Component = () => {});setPropertyValues(property.propertyDefinitionId, value);- return { ok: true, value: undefined };},saveDate: async (property: Property, date: Date) => {console.log('Properties Debug - Saving date:', {@@ -196,7 +195,6 @@ const PropertiesDebug: Component = () => {valueType: 'DATE',value: date.toISOString(),});- return { ok: true, value: undefined };},};diff --git a/js/app/packages/core/component/Properties/hooks/useBooleanEditor.ts b/js/app/packages/core/component/Properties/hooks/useBooleanEditor.tsindex 269bd351af..ad3c82c81b 100644--- a/js/app/packages/core/component/Properties/hooks/useBooleanEditor.ts+++ b/js/app/packages/core/component/Properties/hooks/useBooleanEditor.ts@@ -1,7 +1,6 @@import { type Accessor, createMemo, createSignal } from 'solid-js';import { usePropertiesContext } from '../context/PropertiesContext';import type { Property } from '../types';-import { ERROR_MESSAGES, handlePropertyError } from '../utils/errorHandling';/*** Hook for editing boolean properties@@ -37,20 +36,13 @@ export function useBooleanEditor(// Otherwise toggle between true and falseconst newValue = actualValue === null ? true : !actualValue;- const result = await saveHandler.saveProperty(property, {+ await saveHandler.saveProperty(property, {valueType: 'BOOLEAN',value: newValue,});-- if (- handlePropertyError(- result,- ERROR_MESSAGES.PROPERTY_SAVE,- 'useBooleanEditor.toggle'- )- ) {- onSaved?.();- }+ onSaved?.();+ } catch {+ // Error toast is shown by mutation's onError callback} finally {setIsSaving(false);}diff --git a/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts b/js/app/packages/core/component/Properties/hooks/useEntityProperties.tsindex bc0f581dc5..5806f1ea8e 100644--- a/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts+++ b/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts@@ -1,10 +1,10 @@import {- invalidatePropertiesForEntity,+ useAddEntityPropertyMutation,+ useDeleteEntityPropertyMutation,useEntityPropertiesQuery,} from '@queries/properties/entity';import type { EntityType } from '@service-properties/generated/schemas/entityType';import type { Accessor } from 'solid-js';-import { addEntityProperty, deleteEntityProperty } from '../api';import type { Property } from '../types';import { ERROR_MESSAGES } from '../utils/errorHandling';@@ -12,7 +12,7 @@ import { ERROR_MESSAGES } from '../utils/errorHandling';* Main hook for fetching and managing properties for an entity** This hook focuses purely on data management and returns structured results.- * UI feedback (toasts, notifications) should be handled by consuming components.+ * UI feedback (toasts, notifications) is handled by mutations.** @param entityId - The ID of the entity to fetch properties for* @param entityType - The type of entity (e.g., 'document', 'channel', 'project')@@ -27,12 +27,8 @@ export function useEntityProperties(isLoading: Accessor<boolean>;error: Accessor<string | null>;refetch: () => void;- addProperty: (- propertyDefinitionId: string- ) => Promise<{ success: boolean; error?: string }>;- removeProperty: (- propertyId: string- ) => Promise<{ success: boolean; error?: string }>;+ addProperty: (propertyDefinitionId: string) => Promise<void>;+ removeProperty: (propertyId: string) => Promise<void>;} {const query = useEntityPropertiesQuery(() => entityType,@@ -40,47 +36,21 @@ export function useEntityProperties(includeMetadata);- const doRefetch = () => {- invalidatePropertiesForEntity(entityType, entityId);- void query.refetch();- };-- const addProperty = async (- propertyDefinitionId: string- ): Promise<{ success: boolean; error?: string }> => {- const result = await addEntityProperty(- entityId,- entityType,- propertyDefinitionId- );-- if (result.ok) {- doRefetch();- return { success: true };- } else {- return { success: false, error: ERROR_MESSAGES.PROPERTY_ADD };- }- };-- const removeProperty = async (- propertyId: string- ): Promise<{ success: boolean; error?: string }> => {- const result = await deleteEntityProperty(propertyId);-- if (result.ok) {- doRefetch();- return { success: true };- } else {- return { success: false, error: ERROR_MESSAGES.PROPERTY_DELETE };- }- };+ const addMutation = useAddEntityPropertyMutation();+ const deleteMutation = useDeleteEntityPropertyMutation();return {properties: () => query.data ?? [],isLoading: () => query.isLoading,error: () => (query.error ? ERROR_MESSAGES.PROPERTY_FETCH : null),- refetch: doRefetch,- addProperty,- removeProperty,+ refetch: () => void query.refetch(),+ addProperty: (propertyDefinitionId: string) =>+ addMutation.mutateAsync({ entityId, entityType, propertyDefinitionId }),+ removeProperty: (propertyId: string) =>+ deleteMutation.mutateAsync({+ entityPropertyId: propertyId,+ entityType,+ entityId,+ }),};}diff --git a/js/app/packages/core/component/Properties/hooks/useInlineEditor.ts b/js/app/packages/core/component/Properties/hooks/useInlineEditor.tsindex 82b558e551..3c3ea23cf6 100644--- a/js/app/packages/core/component/Properties/hooks/useInlineEditor.ts+++ b/js/app/packages/core/component/Properties/hooks/useInlineEditor.ts@@ -3,7 +3,6 @@ import { NUMBER_DECIMAL_PLACES } from '../constants';import { usePropertiesContext } from '../context/PropertiesContext';import type { Property, PropertyApiValues } from '../types';import { formatPropertyValue } from '../utils';-import { ERROR_MESSAGES, handlePropertyError } from '../utils/errorHandling';/*** Hook for inline editing of string and number properties@@ -82,18 +81,11 @@ export function useInlineEditor(throw new Error(`Unsupported property type: ${property.valueType}`);}- const result = await saveHandler.saveProperty(property, apiValues);-- if (- handlePropertyError(- result,- ERROR_MESSAGES.PROPERTY_SAVE,- 'useInlineEditor.save'- )- ) {- setIsEditing(false);- onSaved?.();- }+ await saveHandler.saveProperty(property, apiValues);+ setIsEditing(false);+ onSaved?.();+ } catch {+ // Error toast is shown by mutation's onError callback} finally {setIsSaving(false);}diff --git a/js/app/packages/core/component/Properties/hooks/usePropertyEditor.ts b/js/app/packages/core/component/Properties/hooks/usePropertyEditor.tsindex 75bd3f124e..71794fd8ed 100644--- a/js/app/packages/core/component/Properties/hooks/usePropertyEditor.ts+++ b/js/app/packages/core/component/Properties/hooks/usePropertyEditor.ts@@ -1,62 +1,38 @@-import { isErr } from '@core/util/maybeResult';-import { propertiesServiceClient } from '@service-properties/client';+import type { AddPropertyOptionAsyncMutation } from '@queries/properties/options';import { createSignal } from 'solid-js';+import type { Accessor } from 'solid-js';import type { Property, PropertyOption } from '../types';-import { ERROR_MESSAGES } from '../utils/errorHandling';-export interface PropertyEditorState {- options: PropertyOption[];+type LocalState = {selectedOptions: Set<string>;- isLoading: boolean;- error: string | null;hasChanges: boolean;+};++export interface PropertyEditorReturn {+ selectedOptions: Accessor<Set<string>>;+ hasChanges: Accessor<boolean>;+ initializeSelectedOptions: () => void;+ toggleOption: (optionValue: string) => void;+ addOption: (value: string) => Promise<void>;}/*** Hook for managing property value editing in modals* Handles option fetching, selection state, and option creation+ *+ * Note: Uses manual fetch instead of TanStack Query to avoid+ * triggering Suspense boundaries when the modal opens.*/-export function usePropertyEditor(property: Property) {- const [state, setState] = createSignal<PropertyEditorState>({- options: [],+export function usePropertyEditor(+ property: Property,+ propertyOptions: Accessor<PropertyOption[]>,+ addPropertyOption: AddPropertyOptionAsyncMutation+): PropertyEditorReturn {+ const [localState, setLocalState] = createSignal<LocalState>({selectedOptions: new Set(),- isLoading: false,- error: null,hasChanges: false,});- const fetchOptions = async () => {- setState((prev) => ({ ...prev, isLoading: true, error: null }));-- try {- const result = await propertiesServiceClient.getPropertyOptions({- definition_id: property.propertyDefinitionId,- });-- if (isErr(result)) {- setState((prev) => ({- ...prev,- error: ERROR_MESSAGES.OPTION_FETCH,- isLoading: false,- }));- return;- }-- const [, data] = result;- setState((prev) => ({- ...prev,- options: Array.isArray(data) ? data : [],- isLoading: false,- }));- } catch (_apiError) {- setState((prev) => ({- ...prev,- error: ERROR_MESSAGES.OPTION_FETCH,- isLoading: false,- }));- }- };-const initializeSelectedOptions = () => {const selected = new Set<string>();@@ -78,11 +54,11 @@ export function usePropertyEditor(property: Property) {});}- setState((prev) => ({ ...prev, selectedOptions: selected }));+ setLocalState((prev) => ({ ...prev, selectedOptions: selected }));};const toggleOption = (optionValue: string) => {- setState((prev) => {+ setLocalState((prev) => {const newSelected = new Set(prev.selectedOptions);if (property.isMultiSelect) {@@ -105,101 +81,74 @@ export function usePropertyEditor(property: Property) {};const addOption = async (value: string) => {- try {- const currentOptions = state().options;- const nextDisplayOrder =- currentOptions.length > 0- ? Math.max(...currentOptions.map((opt) => opt.display_order)) + 1- : 0;-- let optionBody:- | {- type: 'select_string';- option: { value: string; display_order: number };- }- | {- type: 'select_number';- option: { value: number; display_order: number };- };-- if (property.valueType === 'SELECT_STRING') {- optionBody = {- type: 'select_string',- option: {- value,- display_order: nextDisplayOrder,- },- };- } else if (property.valueType === 'SELECT_NUMBER') {- const numValue = parseFloat(value);- if (isNaN(numValue) || !Number.isFinite(numValue)) {- throw new Error('Invalid number value');+ const currentOptions = propertyOptions();+ const nextDisplayOrder =+ currentOptions.length > 0+ ? Math.max(...currentOptions.map((opt) => opt.display_order)) + 1+ : 0;++ let optionBody:+ | {+ type: 'select_string';+ option: { value: string; display_order: number };}- optionBody = {- type: 'select_number',- option: {- value: numValue,- display_order: nextDisplayOrder,- },+ | {+ type: 'select_number';+ option: { value: number; display_order: number };};- } else {- throw new Error(- `Adding options for ${property.valueType} type is not supported`- );- }-- const result = await propertiesServiceClient.addPropertyOption({- definition_id: property.propertyDefinitionId,- body: optionBody,- });-- if (isErr(result)) {- throw new Error(ERROR_MESSAGES.OPTION_CREATE);- }-- const [, newOption] = result;- // Type guard to ensure newOption is PropertyOption- if (!newOption || typeof newOption !== 'object' || !('id' in newOption)) {- throw new Error('Invalid option returned from API');+ if (property.valueType === 'SELECT_STRING') {+ optionBody = {+ type: 'select_string',+ option: {+ value,+ display_order: nextDisplayOrder,+ },+ };+ } else if (property.valueType === 'SELECT_NUMBER') {+ const numValue = parseFloat(value);+ if (isNaN(numValue) || !Number.isFinite(numValue)) {+ throw new Error('Invalid number value');}+ optionBody = {+ type: 'select_number',+ option: {+ value: numValue,+ display_order: nextDisplayOrder,+ },+ };+ } else {+ throw new Error(+ `Adding options for ${property.valueType} type is not supported`+ );+ }- setState((prev) => ({- ...prev,- options: [...prev.options, newOption as PropertyOption],- }));-- const newSelected = new Set(state().selectedOptions);+ const newOption = await addPropertyOption({+ propertyDefinitionId: property.propertyDefinitionId,+ body: optionBody,+ });- // The API returns the option ID, which is what we need for selection- const optionId = newOption.id;- let valueToSelect: string = optionId;+ // Select the newly created option+ const newSelected = new Set(localState().selectedOptions);+ const optionId = newOption.id;- if (property.isMultiSelect) {- newSelected.add(valueToSelect);- } else {- newSelected.clear();- newSelected.add(valueToSelect);- }-- setState((prev) => ({- ...prev,- selectedOptions: newSelected,- hasChanges: true,- }));- } catch (error) {- console.error(- 'usePropertyEditor.addOption:',- error,- ERROR_MESSAGES.OPTION_ADD- );- throw error;+ if (property.isMultiSelect) {+ newSelected.add(optionId);+ } else {+ newSelected.clear();+ newSelected.add(optionId);}++ setLocalState((prev) => ({+ ...prev,+ selectedOptions: newSelected,+ hasChanges: true,+ }));};return {- state,- fetchOptions,+ selectedOptions: () => localState().selectedOptions,+ hasChanges: () => localState().hasChanges,initializeSelectedOptions,toggleOption,addOption,diff --git a/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts b/js/app/packages/core/component/Properties/hooks/usePropertySelection.tsindex ac6be9d6b7..40a4c00fcb 100644--- a/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts+++ b/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts@@ -1,63 +1,37 @@-import { isErr } from '@core/util/maybeResult';-import { propertiesServiceClient } from '@service-properties/client';-import type { EntityType } from '@service-properties/generated/schemas/entityType';-import { createMemo, createSignal } from 'solid-js';+import { type Accessor, createMemo, createSignal } from 'solid-js';import type { PropertyDefinitionFlat } from '../types';-import { ERROR_MESSAGES } from '../utils/errorHandling';-export interface PropertySelectionState {- availableProperties: PropertyDefinitionFlat[];- selectedPropertyIds: Set<string>;- isLoading: boolean;- error: string | null;-}--/**- * Hook for managing property selection in the "Add Properties" modal- * Handles fetching available properties, filtering, and tracking selections- * @param existingPropertyIds - IDs of properties already attached to the entity- * @param searchQuery - Optional search query for filtering- * @param entityType - Optional entity type to filter properties applicable to this type- */export function usePropertySelection(existingPropertyIds: () => string[],- searchQuery?: () => string,- entityType?: EntityType+ availableProperties: Accessor<PropertyDefinitionFlat[]>,+ searchQuery?: () => string) {- const [state, setState] = createSignal<PropertySelectionState>({- availableProperties: [],- selectedPropertyIds: new Set(),- isLoading: false,- error: null,- });+ const [selectedPropertyIds, setSelectedPropertyIds] = createSignal<+ Set<string>+ >(new Set());- // Memoize Set creation to avoid recreation on every search keystroke- // Reactive to existingPropertyIds changesconst existingPropertyIdsSet = createMemo(() => new Set(existingPropertyIds()));const filteredProperties = createMemo(() => {- const currentState = state();const query = searchQuery ? searchQuery().toLowerCase().trim() : '';const existingIds = existingPropertyIdsSet();- // First filter out existing properties and hidden entity types- const availableProperties = currentState.availableProperties.filter(+ const filtered = availableProperties().filter((property) =>property &&property.id &&!existingIds.has(property.id) &&- // Hide COMPANY entity properties (not yet implemented)+ // COMPANY entity properties not yet implementedproperty.specific_entity_type !== 'COMPANY');// Then apply search filter- if (!query) return availableProperties;+ if (!query) return filtered;- return availableProperties.filter((property) => {+ return filtered.filter((property) => {const name = property.display_name.toLowerCase();- // Check name first before doing string concatenationif (name.includes(query)) {return true;}@@ -73,79 +47,25 @@ export function usePropertySelection(});});- const fetchAvailableProperties = async () => {- setState((prev) => ({ ...prev, isLoading: true, error: null }));-- try {- const result = await propertiesServiceClient.listProperties({- scope: 'all',- include_options: true,- for_entity_type: entityType,- });-- if (isErr(result)) {- setState((prev) => ({- ...prev,- error: ERROR_MESSAGES.PROPERTY_FETCH,- isLoading: false,- }));- return;- }-- const [, data] = result;- const availableProperties = Array.isArray(data) ? data : [];-- // Transform the nested or flat API response to a flat structure- const transformedProperties = availableProperties.map((item) => {- if ('definition' in item) {- return {- ...item.definition,- propertyOptions: item.property_options || [],- };- }-- return {- ...item,- propertyOptions: [],- };- });-- setState((prev) => ({- ...prev,- availableProperties: transformedProperties,- isLoading: false,- }));- } catch (_apiError) {- setState((prev) => ({- ...prev,- error: ERROR_MESSAGES.PROPERTY_FETCH,- isLoading: false,- }));- }- };-const togglePropertySelection = (propertyId: string) => {- setState((prev) => {- const newSelected = new Set(prev.selectedPropertyIds);-+ setSelectedPropertyIds((prev) => {+ const newSelected = new Set(prev);if (newSelected.has(propertyId)) {newSelected.delete(propertyId);} else {newSelected.add(propertyId);}-- return { ...prev, selectedPropertyIds: newSelected };+ return newSelected;});};const clearSelection = () => {- setState((prev) => ({ ...prev, selectedPropertyIds: new Set() }));+ setSelectedPropertyIds(new Set<string>());};return {- state,filteredProperties,- fetchAvailableProperties,+ selectedPropertyIds,togglePropertySelection,clearSelection,};diff --git a/js/app/packages/core/component/Properties/utils/typeGuards.ts b/js/app/packages/core/component/Properties/utils/typeGuards.tsindex fa380f9b01..bb89548095 100644--- a/js/app/packages/core/component/Properties/utils/typeGuards.ts+++ b/js/app/packages/core/component/Properties/utils/typeGuards.ts@@ -1,9 +1,6 @@-import { isErr } from '@core/util/maybeResult';-import { propertiesServiceClient } from '@service-properties/client';import type { EntityReference } from '@service-properties/generated/schemas/entityReference';import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';import type { PropertyDefinitionResponse } from '@service-properties/generated/schemas/propertyDefinitionResponse';-import type { PropertyScope } from '@service-properties/generated/schemas/propertyScope';import type { Property } from '../types';/**@@ -109,23 +106,3 @@ export function isPropertyDefinition(): p is PropertyDefinition {return !('definition' in p);}--/**- * Fetch property definitions without options (flat structure)- * Narrows the response type from PropertyDefinitionResponse[] to PropertyDefinition[]- */-export async function listPropertiesFlat(- scope: PropertyScope-): Promise<PropertyDefinition[]> {- const result = await propertiesServiceClient.listProperties({- scope,- include_options: false,- });-- if (isErr(result)) {- return [];- }-- const [, data] = result;- return (Array.isArray(data) ? data : []).filter(isPropertyDefinition);-}diff --git a/js/app/packages/queries/properties/definitions.ts b/js/app/packages/queries/properties/definitions.tsnew file mode 100644index 0000000000..b21145d428--- /dev/null+++ b/js/app/packages/queries/properties/definitions.ts@@ -0,0 +1,90 @@+import { toast } from '@core/component/Toast/Toast';+import { throwOnErr } from '@core/util/maybeResult';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { propertiesServiceClient } from '../../service-clients/service-properties/client';+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 { PropertyScope } from '../../service-clients/service-properties/generated/schemas/propertyScope';+import { queryClient } from '../client';+import { type MutationCallbacks, withCallbacks } from '../utils';+import { propertiesKeys } from './keys';++export type ListPropertiesQueryParams = {+ scope: PropertyScope;+ includeOptions: boolean;+ forEntityType?: EntityType;+};++export function useListPropertiesQuery(+ params: Accessor<ListPropertiesQueryParams>,+ enabled: Accessor<boolean> = () => true+) {+ return useQuery(() => {+ const { scope, includeOptions, forEntityType } = params();+ return {+ queryKey: propertiesKeys.definitions({+ scope,+ includeOptions,+ forEntityType,+ }).queryKey,+ queryFn: async () => {+ const data = await throwOnErr(+ async () =>+ await propertiesServiceClient.listProperties({+ scope,+ include_options: includeOptions,+ for_entity_type: forEntityType,+ })+ );+ return data;+ },+ enabled: enabled(),+ staleTime: 1000 * 60 * 5, // 5 minutes+ };+ });+}++export function invalidatePropertyDefinitions() {+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) =>+ queryKey.includes('properties') && queryKey.includes('definitions'),+ });+}++export type CreatePropertyDefinitionParams = {+ body: CreatePropertyDefinitionRequest;+};++export function useCreatePropertyDefinitionMutation(+ callbacks?: MutationCallbacks<+ PropertyDefinition,+ Error,+ CreatePropertyDefinitionParams+ >+) {+ return useMutation(() => ({+ mutationFn: async (vars: CreatePropertyDefinitionParams) => {+ const result = await throwOnErr(+ async () =>+ await propertiesServiceClient.createPropertyDefinition({+ body: vars.body,+ })+ );+ return result;+ },+ ...withCallbacks<PropertyDefinition, Error, CreatePropertyDefinitionParams>(+ {+ onError(error) {+ console.error('Failed to create property definition', error);+ toast.failure('Failed to create property');+ },+ onSuccess: () => {+ invalidatePropertyDefinitions();+ },+ },+ callbacks+ ),+ }));+}diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.tsindex f3515c5888..438de9e7c1 100644--- a/js/app/packages/queries/properties/entity.ts+++ b/js/app/packages/queries/properties/entity.ts@@ -1,39 +1,49 @@+import { toast } from '@core/component/Toast/Toast';import { throwOnErr } from '@core/util/maybeResult';-import { type QueryKey, useQuery } from '@tanstack/solid-query';+import { type QueryKey, useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';-import { entityPropertyFromApi } from '../../core/component/Properties/api/converters';+import {+ entityPropertyFromApi,+ propertyValueToApi,+} from '../../core/component/Properties/api/converters';+import type {+ Property,+ PropertyApiValues,+} from '../../core/component/Properties/types';import { propertiesServiceClient } from '../../service-clients/service-properties/client';import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';import { queryClient } from '../client';+import { type MutationCallbacks, withCallbacks } from '../utils';import { propertiesKeys } from './keys';-/**- * Query hook for fetching properties for a single entity.- */export function useEntityPropertiesQuery(entityType: Accessor<EntityType>,entityId: Accessor<string>,includeMetadata: boolean) {return useQuery(- () => ({- queryKey: propertiesKeys.entity({- entityType: entityType(),- entityId: entityId(),- }).queryKey,- queryFn: async () => {- const data = await throwOnErr(- async () =>- await propertiesServiceClient.getEntityProperties({- entity_type: entityType(),- entity_id: entityId(),- query: { include_metadata: includeMetadata },- })- );- return data.properties.map(entityPropertyFromApi);- },- staleTime: 0,- }),+ () => {+ const type = entityType();+ const id = entityId();+ return {+ queryKey: propertiesKeys.entity({+ entityType: type,+ entityId: id,+ }).queryKey,+ queryFn: async () => {+ const data = await throwOnErr(+ async () =>+ await propertiesServiceClient.getEntityProperties({+ entity_type: type,+ entity_id: id,+ query: { include_metadata: includeMetadata },+ })+ );+ return data.properties.map(entityPropertyFromApi);+ },+ staleTime: 0,+ };+ },() => queryClient);}@@ -48,9 +58,6 @@ function bulkIncludesEntityPredicate(queryKey: QueryKey, entityId: string) {);}-/**- * Invalidates and refetches all property queries for a specific entity.- */export function invalidatePropertiesForEntity(entityType: EntityType,entityId: string@@ -65,3 +72,128 @@ export function invalidatePropertiesForEntity(bulkIncludesEntityPredicate(queryKey, entityId),});}++export type SaveEntityPropertyParams = {+ entityId: string;+ entityType: EntityType;+ property: Property;+ apiValues: PropertyApiValues;+};++export function useSaveEntityPropertyMutation(+ callbacks?: MutationCallbacks<void, Error, SaveEntityPropertyParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: SaveEntityPropertyParams) => {+ const propertyValue = propertyValueToApi(+ vars.apiValues,+ vars.property.isMultiSelect+ );++ await throwOnErr(+ async () =>+ await propertiesServiceClient.setEntityProperty({+ entity_type: vars.entityType,+ entity_id: vars.entityId,+ property_id: vars.property.propertyDefinitionId,+ body: {+ value: propertyValue,+ },+ })+ );+ },+ ...withCallbacks<void, Error, SaveEntityPropertyParams>(+ {+ onError(error) {+ console.error('Failed to save property', error);+ toast.failure('Failed to save property');+ },+ onSettled: (_data, _error, variables) => {+ invalidatePropertiesForEntity(+ variables.entityType,+ variables.entityId+ );+ },+ },+ callbacks+ ),+ }));+}++export type DeleteEntityPropertyParams = {+ entityPropertyId: string;+ entityType: EntityType;+ entityId: string;+};++export function useDeleteEntityPropertyMutation(+ callbacks?: MutationCallbacks<void, Error, DeleteEntityPropertyParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: DeleteEntityPropertyParams) => {+ await throwOnErr(+ async () =>+ await propertiesServiceClient.deleteEntityProperty({+ entity_property_id: vars.entityPropertyId,+ })+ );+ },+ ...withCallbacks<void, Error, DeleteEntityPropertyParams>(+ {+ onError(error) {+ console.error('Failed to delete property', error);+ toast.failure('Failed to delete property');+ },+ onSettled: (_data, _error, variables) => {+ invalidatePropertiesForEntity(+ variables.entityType,+ variables.entityId+ );+ },+ },+ callbacks+ ),+ }));+}++export type AddEntityPropertyParams = {+ entityId: string;+ entityType: EntityType;+ propertyDefinitionId: string;+};++/** Adds property without initial value - user sets it later */+export function useAddEntityPropertyMutation(+ callbacks?: MutationCallbacks<void, Error, AddEntityPropertyParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: AddEntityPropertyParams) => {+ await throwOnErr(+ async () =>+ await propertiesServiceClient.setEntityProperty({+ entity_type: vars.entityType,+ entity_id: vars.entityId,+ property_id: vars.propertyDefinitionId,+ body: {+ value: null,+ },+ })+ );+ },+ ...withCallbacks<void, Error, AddEntityPropertyParams>(+ {+ onError(error) {+ console.error('Failed to add property', error);+ toast.failure('Failed to add property');+ },+ onSettled: (_data, _error, variables) => {+ invalidatePropertiesForEntity(+ variables.entityType,+ variables.entityId+ );+ },+ },+ callbacks+ ),+ }));+}diff --git a/js/app/packages/queries/properties/keys.ts b/js/app/packages/queries/properties/keys.tsindex bdb36140c1..c5c478ce50 100644--- a/js/app/packages/queries/properties/keys.ts+++ b/js/app/packages/queries/properties/keys.ts@@ -1,5 +1,6 @@import { createQueryKeys } from '@lukemorales/query-key-factory';import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';+import type { PropertyScope } from '../../service-clients/service-properties/generated/schemas/propertyScope';export const propertiesKeys = createQueryKeys('properties', {all: null,@@ -9,4 +10,19 @@ export const propertiesKeys = createQueryKeys('properties', {bulk: (params: { entityType: EntityType; entityIds: readonly string[] }) => ({queryKey: ['bulk', params.entityType, [...params.entityIds].sort()],}),+ options: (params: { propertyDefinitionId: string }) => ({+ queryKey: ['options', params.propertyDefinitionId],+ }),+ definitions: (params: {+ scope: PropertyScope;+ includeOptions: boolean;+ forEntityType?: EntityType;+ }) => ({+ queryKey: [+ 'definitions',+ params.scope,+ params.includeOptions,+ params.forEntityType,+ ],+ }),});diff --git a/js/app/packages/queries/properties/options.ts b/js/app/packages/queries/properties/options.tsnew file mode 100644index 0000000000..8b2467b256--- /dev/null+++ b/js/app/packages/queries/properties/options.ts@@ -0,0 +1,80 @@+import { toast } from '@core/component/Toast/Toast';+import { throwOnErr } from '@core/util/maybeResult';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { propertiesServiceClient } from '../../service-clients/service-properties/client';+import type { AddPropertyOptionRequest } from '../../service-clients/service-properties/generated/schemas/addPropertyOptionRequest';+import type { PropertyOption } from '../../service-clients/service-properties/generated/schemas/propertyOption';+import { queryClient } from '../client';+import { type MutationCallbacks, withCallbacks } from '../utils';+import { propertiesKeys } from './keys';++export function usePropertyOptionsQuery(+ propertyDefinitionId: Accessor<string>,+ enabled: Accessor<boolean> = () => true+) {+ return useQuery(() => {+ const defId = propertyDefinitionId();+ return {+ queryKey: propertiesKeys.options({ propertyDefinitionId: defId })+ .queryKey,+ queryFn: async () => {+ const result = await throwOnErr(+ async () =>+ await propertiesServiceClient.getPropertyOptions({+ definition_id: defId,+ })+ );+ return result;+ },+ enabled: enabled(),+ staleTime: 1000 * 60 * 5, // 5 minutes+ };+ });+}++export type PropertyOptionsQuery = ReturnType<typeof usePropertyOptionsQuery>;++export function invalidatePropertyOptions(propertyDefinitionId: string) {+ queryClient.invalidateQueries({+ queryKey: propertiesKeys.options({ propertyDefinitionId }).queryKey,+ });+}++export type AddPropertyOptionAsyncMutation = ReturnType<+ typeof useAddPropertyOptionMutation+>['mutateAsync'];++export type AddPropertyOptionParams = {+ propertyDefinitionId: string;+ body: AddPropertyOptionRequest;+};++export function useAddPropertyOptionMutation(+ callbacks?: MutationCallbacks<PropertyOption, Error, AddPropertyOptionParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: AddPropertyOptionParams) => {+ const result = await throwOnErr(+ async () =>+ await propertiesServiceClient.addPropertyOption({+ definition_id: vars.propertyDefinitionId,+ body: vars.body,+ })+ );+ return result;+ },+ ...withCallbacks<PropertyOption, Error, AddPropertyOptionParams>(+ {+ onError(error) {+ console.error('Failed to add property option', error);+ toast.failure('Failed to add option');+ },+ onSuccess: (_data, variables) => {+ invalidatePropertyOptions(variables.propertyDefinitionId);+ },+ },+ callbacks+ ),+ }));+}