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.

chg(properties): simpler query, use properties in frontmatter, invalidatations (#953)

teoc4551f9df1f2
diff --git a/js/app/packages/block-md/component/FrontMatterProperties.tsx b/js/app/packages/block-md/component/FrontMatterProperties.tsx
index 56ff691b79..67b73a401d 100644
--- a/js/app/packages/block-md/component/FrontMatterProperties.tsx
+++ b/js/app/packages/block-md/component/FrontMatterProperties.tsx
@@ -38,7 +38,6 @@ import {
setFrontMatterPreferenceForDoc,
} from '../signal/frontMatter';
import { mdStore } from '../signal/markdownBlockData';
-import { propertiesRefreshSignal } from '../signal/propertiesRefresh';
interface FrontMatterPropertiesProps {
canEdit: boolean;
@@ -62,18 +61,9 @@ export function FrontMatterProperties(props: FrontMatterPropertiesProps) {
const { properties, isLoading, error, refetch } = useEntityProperties(
blockId,
entityType,
- true // includeMetadata
+ true
);
- // Watch for property changes from MarkdownPropertiesModal and refetch
- createEffect(() => {
- const shouldRefresh = propertiesRefreshSignal.get();
- if (shouldRefresh) {
- propertiesRefreshSignal.set(false);
- refetch();
- }
- });
-
// Track expanded/collapsed state from persisted preference
const isExpanded = createMemo(() => {
const preference = frontMatterPreference[blockId];
@@ -154,13 +144,26 @@ export function FrontMatterProperties(props: FrontMatterPropertiesProps) {
// Network-based save handler for FrontMatter properties
const saveHandler: PropertySaveHandler = {
saveProperty: async (property: Property, value: PropertyApiValues) => {
- return await saveEntityProperty(blockId, entityType, property, value);
+ const result = await saveEntityProperty(
+ blockId,
+ entityType,
+ property,
+ value
+ );
+ if (result.ok) {
+ refetch();
+ }
+ return result;
},
saveDate: async (property: Property, date: Date) => {
- return await saveEntityProperty(blockId, entityType, property, {
+ const result = await saveEntityProperty(blockId, entityType, property, {
valueType: 'DATE',
value: date.toISOString(),
});
+ if (result.ok) {
+ refetch();
+ }
+ return result;
},
};
@@ -208,7 +211,6 @@ export function FrontMatterProperties(props: FrontMatterPropertiesProps) {
</div>
</Show>
- {/* Shouldn't really go in here, but leaving it here as fail safe */}
<Show when={error()}>
<div class="text-failure-ink text-center py-4">{error()}</div>
</Show>
diff --git a/js/app/packages/block-md/component/MarkdownPropertiesModal.tsx b/js/app/packages/block-md/component/MarkdownPropertiesModal.tsx
index acbd0e6264..400ff1563a 100644
--- a/js/app/packages/block-md/component/MarkdownPropertiesModal.tsx
+++ b/js/app/packages/block-md/component/MarkdownPropertiesModal.tsx
@@ -14,7 +14,6 @@ import TagIcon from '@icon/regular/tag.svg';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { createEffect, createSignal, Suspense } from 'solid-js';
import { mdStore } from '../signal/markdownBlockData';
-import { propertiesRefreshSignal } from '../signal/propertiesRefresh';
const DRAWER_ID = 'properties';
@@ -50,9 +49,6 @@ function MarkdownPropertiesContent(_props: { documentId: string }) {
const blockName = useBlockAliasedName();
const entityType: EntityType = blockName === 'task' ? 'TASK' : 'DOCUMENT';
- // Destructure block signal setter before any async operations
- const triggerRefresh = propertiesRefreshSignal.set;
-
// Track pinned property IDs from Lexical - reactively updates on editor state changes
const [pinnedPropertyIds, setPinnedPropertyIds] = createSignal<string[]>([]);
@@ -86,7 +82,6 @@ function MarkdownPropertiesContent(_props: { documentId: string }) {
const editor = mdData.editor;
if (editor) {
editor.dispatchCommand(ADD_PINNED_PROPERTY_COMMAND, propertyId);
- triggerRefresh(true);
}
};
@@ -94,7 +89,6 @@ function MarkdownPropertiesContent(_props: { documentId: string }) {
const editor = mdData.editor;
if (editor) {
editor.dispatchCommand(REMOVE_PINNED_PROPERTY_COMMAND, propertyId);
- triggerRefresh(true);
}
};
@@ -111,7 +105,6 @@ function MarkdownPropertiesContent(_props: { documentId: string }) {
onPropertyPinned={handlePropertyPinned}
onPropertyUnpinned={handlePropertyUnpinned}
pinnedPropertyIds={pinnedPropertyIds}
- onRefresh={() => triggerRefresh(true)}
/>
</div>
);
diff --git a/js/app/packages/block-md/signal/propertiesRefresh.ts b/js/app/packages/block-md/signal/propertiesRefresh.ts
deleted file mode 100644
index a647eab3f7..0000000000
--- a/js/app/packages/block-md/signal/propertiesRefresh.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { createBlockSignal } from '@core/block';
-
-/**
- * Block-scoped signal to trigger front matter refresh when properties change in the properties panel
- * This is one-way: MarkdownPropertiesModal -> FrontMatterProperties
- * Each document/block has its own refresh trigger
- * Set to true to trigger a refetch, will be reset to false after refetching
- */
-export const propertiesRefreshSignal = createBlockSignal(false);
diff --git a/js/app/packages/core/component/Properties/PropertiesView.tsx b/js/app/packages/core/component/Properties/PropertiesView.tsx
index 91e6f253b8..45e3ef6b64 100644
--- a/js/app/packages/core/component/Properties/PropertiesView.tsx
+++ b/js/app/packages/core/component/Properties/PropertiesView.tsx
@@ -49,18 +49,31 @@ export function PropertiesView(props: PropertiesPanelProps) {
const saveHandler: PropertySaveHandler = {
saveProperty: async (property: Property, value: PropertyApiValues) => {
- return await saveEntityProperty(
+ const result = await saveEntityProperty(
blockId,
props.entityType,
property,
value
);
+ if (result.ok) {
+ refetch();
+ }
+ return result;
},
saveDate: async (property: Property, date: Date) => {
- return await saveEntityProperty(blockId, props.entityType, property, {
- valueType: 'DATE',
- value: date.toISOString(),
- });
+ const result = await saveEntityProperty(
+ blockId,
+ props.entityType,
+ property,
+ {
+ valueType: 'DATE',
+ value: date.toISOString(),
+ }
+ );
+ if (result.ok) {
+ refetch();
+ }
+ return result;
},
};
diff --git a/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts b/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts
index 00bc68272d..bc0f581dc5 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 type { EntityType } from '@service-properties/generated/schemas/entityType';
-import { type Accessor, createSignal, onMount } from 'solid-js';
import {
- addEntityProperty,
- deleteEntityProperty,
- fetchEntityProperties,
-} from '../api';
+ invalidatePropertiesForEntity,
+ 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';
@@ -34,42 +34,15 @@ export function useEntityProperties(
propertyId: string
) => Promise<{ success: boolean; error?: string }>;
} {
- const [properties, setProperties] = createSignal<Property[]>([]);
- const [isLoading, setIsLoading] = createSignal(false);
- const [error, setError] = createSignal<string | null>(null);
-
- const handleFetchError = (errorMessage: string) => {
- setError(errorMessage);
- // Return error for component to handle UI feedback
- return { success: false, error: errorMessage };
- };
-
- const fetch = async () => {
- // Don't show loading spinner if we already have properties (background refresh)
- if (properties().length === 0) {
- setIsLoading(true);
- }
- setError(null);
+ const query = useEntityPropertiesQuery(
+ () => entityType,
+ () => entityId,
+ includeMetadata
+ );
- try {
- const result = await fetchEntityProperties(
- entityId,
- entityType,
- includeMetadata
- );
-
- if (result.ok) {
- setProperties(result.value);
- } else {
- return handleFetchError(ERROR_MESSAGES.PROPERTY_FETCH);
- }
- } catch (_err) {
- return handleFetchError(ERROR_MESSAGES.PROPERTY_FETCH);
- } finally {
- setIsLoading(false);
- }
-
- return { success: true };
+ const doRefetch = () => {
+ invalidatePropertiesForEntity(entityType, entityId);
+ void query.refetch();
};
const addProperty = async (
@@ -82,7 +55,7 @@ export function useEntityProperties(
);
if (result.ok) {
- await fetch(); // Refetch to get updated list
+ doRefetch();
return { success: true };
} else {
return { success: false, error: ERROR_MESSAGES.PROPERTY_ADD };
@@ -95,26 +68,18 @@ export function useEntityProperties(
const result = await deleteEntityProperty(propertyId);
if (result.ok) {
- await fetch(); // Refetch to get updated list
+ doRefetch();
return { success: true };
} else {
return { success: false, error: ERROR_MESSAGES.PROPERTY_DELETE };
}
};
- const refetch = () => {
- fetch();
- };
-
- onMount(() => {
- fetch();
- });
-
return {
- properties,
- isLoading,
- error,
- refetch,
+ properties: () => query.data ?? [],
+ isLoading: () => query.isLoading,
+ error: () => (query.error ? ERROR_MESSAGES.PROPERTY_FETCH : null),
+ refetch: doRefetch,
addProperty,
removeProperty,
};
diff --git a/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts b/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts
index 5586e45002..771c291167 100644
--- a/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts
+++ b/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts
@@ -27,19 +27,16 @@ function isTaskEntity(
export function useTaskProperties(
entities: () => Entity[] | undefined
): () => TaskPropertiesStore {
- const taskEntityRefs = createMemo(() => {
+ const taskEntityIds = createMemo(() => {
const allEntities = entities() ?? [];
- const taskEntities = allEntities.filter(isTaskEntity);
- return taskEntities.map((e) => ({
- entity_id: e.id,
- entity_type: 'TASK' as const,
- }));
+ return allEntities.filter(isTaskEntity).map((e) => e.id);
});
const query = useBulkEntityPropertiesQuery(
- taskEntityRefs,
+ 'TASK',
+ taskEntityIds,
TASK_PROPERTY_DEFINITION_IDS
);
- return () => query.data ?? {};
+ return createMemo(() => query.data ?? {});
}
diff --git a/js/app/packages/queries/properties/bulk.ts b/js/app/packages/queries/properties/bulk.ts
index ca40760860..4eefd2284a 100644
--- a/js/app/packages/queries/properties/bulk.ts
+++ b/js/app/packages/queries/properties/bulk.ts
@@ -1,63 +1,35 @@
-import type { UseBaseQueryOptions } from '@tanstack/solid-query';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { entityPropertyFromApi } from '../../core/component/Properties/api/converters';
import type { Property } from '../../core/component/Properties/types';
import { isErr } from '../../core/util/maybeResult';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
-import type { EntityReference } from '../../service-clients/service-properties/generated/schemas/entityReference';
-import { partitionByQueryCache } from '../cache';
+import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
import { queryClient } from '../client';
import { propertiesKeys } from './keys';
export type BulkEntityPropertiesData = Record<string, Property[]>;
-type BulkEntityPropertiesQueryOptions = UseBaseQueryOptions<
- BulkEntityPropertiesData,
- Error
->;
-
-type BulkEntityPropertiesParams = {
- readonly entities: readonly EntityReference[];
- readonly propertyDefinitionIds: readonly string[];
-};
-
-const entityPropertiesKey = (
- entity: EntityReference,
+/**
+ * Fetches properties for multiple entities of the same type.
+ * No caching partitioning - just a simple bulk fetch.
+ */
+async function fetchBulkProperties(
+ entityType: EntityType,
+ entityIds: readonly string[],
propertyDefinitionIds: readonly string[]
-) =>
- propertiesKeys.entity({
- entityType: entity.entity_type,
- entityId: entity.entity_id,
- propertyDefinitionIds,
- }).queryKey;
-
-async function fetchBulkWithCachePartition(
- params: BulkEntityPropertiesParams
): Promise<BulkEntityPropertiesData> {
- if (params.entities.length === 0) return {};
+ if (entityIds.length === 0) return {};
- const { cached, missing } = partitionByQueryCache<
- EntityReference,
- Property[]
- >({
- queryClient,
- items: params.entities,
- queryKeyOf: (entity) =>
- entityPropertiesKey(entity, params.propertyDefinitionIds),
- });
-
- const out: BulkEntityPropertiesData = {};
- for (const [entity, properties] of cached.entries()) {
- out[entity.entity_id] = properties;
- }
-
- if (missing.length === 0) return out;
+ const entities = entityIds.map((id) => ({
+ entity_type: entityType,
+ entity_id: id,
+ }));
const result = await propertiesServiceClient.getBulkEntityProperties({
body: {
- entities: [...missing],
- property_ids: [...params.propertyDefinitionIds],
+ entities,
+ property_ids: [...propertyDefinitionIds],
},
});
@@ -66,67 +38,36 @@ async function fetchBulkWithCachePartition(
}
const [, data] = result;
- for (const entity of missing) {
- const response = data[entity.entity_id];
- if (!response) {
- out[entity.entity_id] = [];
- continue;
- }
+ const out: BulkEntityPropertiesData = {};
- const properties = response.properties.map(entityPropertyFromApi);
- queryClient.setQueryData(
- entityPropertiesKey(entity, params.propertyDefinitionIds),
- properties
- );
- out[entity.entity_id] = properties;
+ for (const entityId of entityIds) {
+ const response = data[entityId];
+ out[entityId] = response?.properties.map(entityPropertyFromApi) ?? [];
}
return out;
}
-function bulkEntityPropertiesQueryOptions(
- params: BulkEntityPropertiesParams
-): BulkEntityPropertiesQueryOptions {
- return {
- queryKey: propertiesKeys.bulk({
- entities: params.entities,
- propertyDefinitionIds: params.propertyDefinitionIds,
- }).queryKey,
- queryFn: () => fetchBulkWithCachePartition(params),
- };
-}
-
+/**
+ * Hook for fetching properties for multiple entities.
+ * Simple query without complex caching logic.
+ */
export function useBulkEntityPropertiesQuery(
- entities: Accessor<readonly EntityReference[]>,
- propertyDefinitionIds: readonly string[],
- options?: Accessor<
- Omit<
- BulkEntityPropertiesQueryOptions,
- 'queryKey' | 'queryFn' | 'initialData'
- >
- >
+ entityType: EntityType,
+ entityIds: Accessor<readonly string[]>,
+ propertyDefinitionIds: readonly string[]
) {
return useQuery(
- () => {
- const currentEntities = entities();
- const placeholder: BulkEntityPropertiesData = {};
- for (const entity of currentEntities) {
- const cached = queryClient.getQueryData<Property[]>(
- entityPropertiesKey(entity, propertyDefinitionIds)
- );
- placeholder[entity.entity_id] = cached ?? [];
- }
- return {
- initialData: placeholder,
- staleTime: 0,
- enabled: currentEntities.length > 0,
- ...options?.(),
- ...bulkEntityPropertiesQueryOptions({
- entities: currentEntities,
- propertyDefinitionIds,
- }),
- };
- },
+ () => ({
+ queryKey: propertiesKeys.bulk({
+ entityType,
+ entityIds: entityIds(),
+ }).queryKey,
+ queryFn: () =>
+ fetchBulkProperties(entityType, entityIds(), propertyDefinitionIds),
+ staleTime: 0,
+ enabled: entityIds().length > 0,
+ }),
() => queryClient
);
}
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
new file mode 100644
index 0000000000..f3515c5888
--- /dev/null
+++ b/js/app/packages/queries/properties/entity.ts
@@ -0,0 +1,67 @@
+import { throwOnErr } from '@core/util/maybeResult';
+import { type QueryKey, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { entityPropertyFromApi } from '../../core/component/Properties/api/converters';
+import { propertiesServiceClient } from '../../service-clients/service-properties/client';
+import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
+import { queryClient } from '../client';
+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,
+ }),
+ () => queryClient
+ );
+}
+
+function bulkIncludesEntityPredicate(queryKey: QueryKey, entityId: string) {
+ return (
+ queryKey.includes('properties') &&
+ queryKey.includes('bulk') &&
+ queryKey.some(
+ (subKey) => Array.isArray(subKey) && subKey.includes(entityId)
+ )
+ );
+}
+
+/**
+ * Invalidates and refetches all property queries for a specific entity.
+ */
+export function invalidatePropertiesForEntity(
+ entityType: EntityType,
+ entityId: string
+) {
+ queryClient.invalidateQueries({
+ queryKey: propertiesKeys.entity({ entityType, entityId }).queryKey,
+ });
+
+ // This invalidates any bulk query including this entity
+ queryClient.invalidateQueries({
+ predicate: ({ queryKey }) =>
+ bulkIncludesEntityPredicate(queryKey, entityId),
+ });
+}
diff --git a/js/app/packages/queries/properties/keys.ts b/js/app/packages/queries/properties/keys.ts
index c5e9e80272..bdb36140c1 100644
--- a/js/app/packages/queries/properties/keys.ts
+++ b/js/app/packages/queries/properties/keys.ts
@@ -1,43 +1,12 @@
import { createQueryKeys } from '@lukemorales/query-key-factory';
-import { uniqueByKeySorted } from '../../core/util/compareUtils';
-import type { EntityReference } from '../../service-clients/service-properties/generated/schemas/entityReference';
import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
-const normalizeStringIds = (ids: readonly string[]) => [...new Set(ids)].sort();
-
-const entityRefKey = (e: EntityReference) => `${e.entity_type}:${e.entity_id}`;
-
-const normalizeEntities = (entities: readonly EntityReference[]) =>
- uniqueByKeySorted(entities, entityRefKey);
-
export const propertiesKeys = createQueryKeys('properties', {
all: null,
-
- entity: (params: {
- entityType: EntityType;
- entityId: string;
- propertyDefinitionIds?: readonly string[] | undefined;
- }) => ({
- queryKey: [
- 'entity',
- params.entityType,
- params.entityId,
- params.propertyDefinitionIds
- ? normalizeStringIds(params.propertyDefinitionIds)
- : undefined,
- ],
+ entity: (params: { entityType: EntityType; entityId: string }) => ({
+ queryKey: ['entity', params.entityType, params.entityId],
}),
-
- bulk: (params: {
- entities: readonly EntityReference[];
- propertyDefinitionIds: readonly string[];
- }) => ({
- queryKey: [
- 'bulk',
- {
- entities: normalizeEntities(params.entities),
- propertyDefinitionIds: normalizeStringIds(params.propertyDefinitionIds),
- },
- ],
+ bulk: (params: { entityType: EntityType; entityIds: readonly string[] }) => ({
+ queryKey: ['bulk', params.entityType, [...params.entityIds].sort()],
}),
});