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.

improve [properties-fe] - refactor properties (#227)

Daniel Kweone9bfb9d34d71
diff --git a/js/app/packages/core/component/Properties/api/converters.ts b/js/app/packages/core/component/Properties/api/converters.ts
index 76e4169c0d..22be22ebe8 100644
--- a/js/app/packages/core/component/Properties/api/converters.ts
+++ b/js/app/packages/core/component/Properties/api/converters.ts
@@ -1,3 +1,4 @@
+import type { PropertyValue } from '@service-properties/generated/schemas/propertyValue';
import { NUMBER_DECIMAL_PLACES } from '../constants';
import type {
EntityPropertyWithDefinition,
@@ -9,40 +10,184 @@ import type {
} from '../types';
/**
- * Convert domain PropertyApiValues to API format
+ * Type guard to check if PropertyValue has a specific type
+ */
+function hasPropertyValueType(
+ value: PropertyValue | null | undefined,
+ type: string
+): value is PropertyValue & { type: string; value: unknown } {
+ return (
+ value !== null &&
+ value !== undefined &&
+ 'type' in value &&
+ value.type === type &&
+ 'value' in value
+ );
+}
+
+/**
+ * Convert EntityPropertyWithDefinition from API format to domain Property type
+ *
+ * Transforms the nested API response structure into a flat, strongly-typed domain model.
+ * Handles all value types with proper type guards and formatting.
+ */
+export function entityPropertyFromApi(
+ apiProperty: EntityPropertyWithDefinition
+): Property {
+ const baseProperty = {
+ propertyId: apiProperty.property.id,
+ propertyDefinitionId: apiProperty.definition.id,
+ displayName: apiProperty.definition.display_name,
+ isMultiSelect: apiProperty.definition.is_multi_select,
+ isMetadata: apiProperty.definition.is_metadata,
+ options: apiProperty.options ?? undefined,
+ owner: apiProperty.definition.owner,
+ specificEntityType: apiProperty.definition.specific_entity_type,
+ createdAt: apiProperty.property.created_at,
+ updatedAt: apiProperty.property.updated_at,
+ };
+
+ const propertyValue = apiProperty.value;
+ const valueType = apiProperty.definition.data_type as ValueType;
+
+ // Handle each value type with proper type checking
+ switch (valueType) {
+ case 'STRING': {
+ if (hasPropertyValueType(propertyValue, 'String')) {
+ const stringVal = propertyValue.value;
+ if (typeof stringVal === 'string' && stringVal) {
+ return { ...baseProperty, valueType: 'STRING', value: stringVal };
+ }
+ }
+ return { ...baseProperty, valueType: 'STRING', value: null };
+ }
+
+ case 'NUMBER': {
+ if (hasPropertyValueType(propertyValue, 'Number')) {
+ const numVal = propertyValue.value;
+ if (
+ typeof numVal === 'number' &&
+ numVal !== undefined &&
+ numVal !== null
+ ) {
+ return {
+ ...baseProperty,
+ valueType: 'NUMBER',
+ value: parseFloat(numVal.toFixed(NUMBER_DECIMAL_PLACES)),
+ };
+ }
+ }
+ return { ...baseProperty, valueType: 'NUMBER', value: null };
+ }
+
+ case 'BOOLEAN': {
+ if (hasPropertyValueType(propertyValue, 'Boolean')) {
+ const boolVal = propertyValue.value;
+ if (typeof boolVal === 'boolean') {
+ return { ...baseProperty, valueType: 'BOOLEAN', value: boolVal };
+ }
+ }
+ return { ...baseProperty, valueType: 'BOOLEAN', value: null };
+ }
+
+ case 'DATE': {
+ if (hasPropertyValueType(propertyValue, 'Date')) {
+ const dateVal = propertyValue.value;
+ if (
+ dateVal &&
+ (typeof dateVal === 'string' || typeof dateVal === 'number')
+ ) {
+ return {
+ ...baseProperty,
+ valueType: 'DATE',
+ value: new Date(dateVal),
+ };
+ }
+ }
+ return { ...baseProperty, valueType: 'DATE', value: null };
+ }
+
+ case 'SELECT_STRING':
+ case 'SELECT_NUMBER': {
+ if (hasPropertyValueType(propertyValue, 'SelectOption')) {
+ const selectVal = propertyValue.value;
+ if (
+ Array.isArray(selectVal) &&
+ selectVal.every((v) => typeof v === 'string')
+ ) {
+ return {
+ ...baseProperty,
+ valueType,
+ value: selectVal as string[],
+ };
+ }
+ }
+ return { ...baseProperty, valueType, value: null };
+ }
+
+ case 'ENTITY': {
+ if (hasPropertyValueType(propertyValue, 'EntityReference')) {
+ const entityVal = propertyValue.value;
+ if (Array.isArray(entityVal)) {
+ const refs: EntityReference[] = [];
+ for (const ref of entityVal) {
+ if (
+ ref &&
+ typeof ref === 'object' &&
+ 'entity_id' in ref &&
+ 'entity_type' in ref
+ ) {
+ refs.push(ref as EntityReference);
+ }
+ }
+ return { ...baseProperty, valueType: 'ENTITY', value: refs };
+ }
+ }
+ return { ...baseProperty, valueType: 'ENTITY', value: null };
+ }
+
+ case 'LINK': {
+ if (hasPropertyValueType(propertyValue, 'Link')) {
+ const linkVal = propertyValue.value;
+ if (
+ Array.isArray(linkVal) &&
+ linkVal.every((v) => typeof v === 'string')
+ ) {
+ return {
+ ...baseProperty,
+ valueType: 'LINK',
+ value: linkVal as string[],
+ };
+ }
+ }
+ return { ...baseProperty, valueType: 'LINK', value: null };
+ }
+
+ default: {
+ const exhaustiveCheck: never = valueType;
+ throw new Error(
+ `Unsupported value type: ${(exhaustiveCheck as { valueType: string }).valueType}`
+ );
+ }
+ }
+}
+
+/**
+ * Convert PropertyApiValues from domain format to API SetPropertyValue format
*
* Transforms typed property values into the API's expected format, handling:
* - Primitive types (string, number, date, boolean)
* - Select types (single and multi-select for both string and number options)
* - Entity references (single and multi-entity for all entity types)
* - Number formatting to 4 decimal places
- *
- * @param apiValues - The property values in domain format (discriminated union)
- * @param isMultiSelect - Whether this property supports multiple selections
- * @returns SetPropertyValue for API submission, or null to unset the value
- *
- * @example
- * // String value
- * toApiFormat({ valueType: 'string', value: 'Hello' }, false)
- * // Returns: { type: 'string', value: 'Hello' }
- *
- * @example
- * // Multi-select
- * toApiFormat({ valueType: 'select_string', values: ['opt1', 'opt2'] }, true)
- * // Returns: { type: 'multi_select_option', option_ids: ['opt1', 'opt2'] }
- *
- * @example
- * // Unset value
- * toApiFormat({ valueType: 'string', value: null }, false)
- * // Returns: null
*/
-export function toApiFormat(
+export function propertyValueToApi(
apiValues: PropertyApiValues,
isMultiSelect: boolean
): SetPropertyValue | null {
switch (apiValues.valueType) {
case 'STRING':
- if (apiValues.value === null) {
+ if (apiValues.value == null) {
return null;
}
return {
@@ -51,7 +196,7 @@ export function toApiFormat(
};
case 'NUMBER':
- if (apiValues.value === null) {
+ if (apiValues.value == null) {
return null;
}
return {
@@ -60,7 +205,7 @@ export function toApiFormat(
};
case 'DATE':
- if (apiValues.value === null) {
+ if (apiValues.value == null) {
return null;
}
return {
@@ -69,7 +214,7 @@ export function toApiFormat(
};
case 'BOOLEAN':
- if (apiValues.value === null) {
+ if (apiValues.value == null) {
return null;
}
return {
@@ -97,7 +242,6 @@ export function toApiFormat(
if (!apiValues.refs || apiValues.refs.length === 0) {
return null;
}
-
if (isMultiSelect) {
return {
type: 'multi_entity_reference',
@@ -124,187 +268,11 @@ export function toApiFormat(
url: apiValues.values[0],
};
- default:
+ default: {
const exhaustiveCheck: never = apiValues;
throw new Error(
`Unsupported value type: ${(exhaustiveCheck as { valueType: string }).valueType}`
);
- }
-}
-
-/**
- * Convert API property response to domain Property type
- *
- * Transforms the nested API response structure into a flat, strongly-typed domain model.
- *
- * Key transformations:
- * - Parses discriminated union from API's PropertyValue structure
- * - Formats numbers to 4 decimal places
- * - Distinguishes "property not set" (undefined) from "property set but empty" ([])
- *
- * @param apiProperty - Raw API property response with nested structure
- * @returns Flat Property object with typed value arrays
- *
- * @example
- * // API response with string value
- * fromApiFormat({
- * id: 'prop1',
- * values: [{ value: { type: 'string', value: 'Hello' } }],
- * definition: { display_name: 'Name', data_type: 'string', ... }
- * })
- * // Returns: { propertyId: 'prop1', stringValue: ['Hello'], ... }
- */
-export function fromApiFormat(
- apiProperty: EntityPropertyWithDefinition
-): Property {
- const baseProperty = {
- propertyId: apiProperty.property.id,
- propertyDefinitionId: apiProperty.definition.id,
- displayName: apiProperty.definition.display_name,
- isMultiSelect: apiProperty.definition.is_multi_select,
- isMetadata: apiProperty.definition.is_metadata,
- options: apiProperty.options ?? undefined, // Convert null to undefined
- owner: apiProperty.definition.owner,
- specificEntityType: apiProperty.definition.specific_entity_type,
- // Timestamps
- createdAt: apiProperty.property.created_at,
- updatedAt: apiProperty.property.updated_at,
- };
-
- const propertyValue = apiProperty.value;
- const valueType = apiProperty.definition.data_type as ValueType;
-
- // Parse and return the appropriate discriminated union type
- // undefined = "property not set", empty array = "set but empty", value = "has data"
- switch (valueType) {
- case 'STRING':
- if (
- propertyValue &&
- 'type' in propertyValue &&
- propertyValue.type === 'String' &&
- 'value' in propertyValue
- ) {
- const stringVal = propertyValue.value;
- if (stringVal && typeof stringVal === 'string') {
- return { ...baseProperty, valueType: 'STRING', value: stringVal };
- }
- }
- return { ...baseProperty, valueType: 'STRING', value: undefined };
-
- case 'NUMBER':
- if (
- propertyValue &&
- 'type' in propertyValue &&
- propertyValue.type === 'Number' &&
- 'value' in propertyValue
- ) {
- const numVal = propertyValue.value;
- if (
- numVal !== undefined &&
- numVal !== null &&
- typeof numVal === 'number'
- ) {
- return {
- ...baseProperty,
- valueType: 'NUMBER',
- value: parseFloat(numVal.toFixed(NUMBER_DECIMAL_PLACES)),
- };
- }
- }
- return { ...baseProperty, valueType: 'NUMBER', value: undefined };
-
- case 'BOOLEAN':
- if (
- propertyValue &&
- 'type' in propertyValue &&
- propertyValue.type === 'Boolean' &&
- 'value' in propertyValue
- ) {
- const boolVal = propertyValue.value;
- if (typeof boolVal === 'boolean') {
- return { ...baseProperty, valueType: 'BOOLEAN', value: boolVal };
- }
- }
- return { ...baseProperty, valueType: 'BOOLEAN', value: undefined };
-
- case 'DATE':
- if (
- propertyValue &&
- 'type' in propertyValue &&
- propertyValue.type === 'Date' &&
- 'value' in propertyValue
- ) {
- const dateVal = propertyValue.value;
- if (
- dateVal &&
- (typeof dateVal === 'string' || typeof dateVal === 'number')
- ) {
- return {
- ...baseProperty,
- valueType: 'DATE',
- value: new Date(dateVal),
- };
- }
- }
- return { ...baseProperty, valueType: 'DATE', value: undefined };
-
- case 'SELECT_STRING':
- case 'SELECT_NUMBER':
- if (
- propertyValue &&
- 'type' in propertyValue &&
- propertyValue.type === 'SelectOption' &&
- 'value' in propertyValue
- ) {
- const selectVal = propertyValue.value;
- if (Array.isArray(selectVal)) {
- return {
- ...baseProperty,
- valueType,
- value: selectVal,
- };
- }
- }
- return { ...baseProperty, valueType, value: undefined };
-
- case 'ENTITY':
- if (
- propertyValue &&
- 'type' in propertyValue &&
- propertyValue.type === 'EntityReference' &&
- 'value' in propertyValue
- ) {
- const entityVal = propertyValue.value;
- if (Array.isArray(entityVal)) {
- const refs: EntityReference[] = [];
- entityVal.forEach((ref: unknown) => {
- if (
- ref &&
- typeof ref === 'object' &&
- 'entity_id' in ref &&
- 'entity_type' in ref
- ) {
- refs.push(ref as EntityReference);
- }
- });
- return { ...baseProperty, valueType: 'ENTITY', value: refs };
- }
- }
- return { ...baseProperty, valueType: 'ENTITY', value: undefined };
-
- case 'LINK':
- if (
- propertyValue &&
- 'type' in propertyValue &&
- propertyValue.type === 'Link' &&
- 'value' in propertyValue
- ) {
- const linkVal = propertyValue.value;
- // Link values are always returned as arrays from the API
- if (Array.isArray(linkVal)) {
- return { ...baseProperty, valueType: 'LINK', value: linkVal };
- }
- }
- return { ...baseProperty, valueType: 'LINK', value: undefined };
+ }
}
}
diff --git a/js/app/packages/core/component/Properties/api/fetchProperties.ts b/js/app/packages/core/component/Properties/api/fetchProperties.ts
index d91201c3fc..ad477edd78 100644
--- a/js/app/packages/core/component/Properties/api/fetchProperties.ts
+++ b/js/app/packages/core/component/Properties/api/fetchProperties.ts
@@ -2,8 +2,8 @@ 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 { ErrorHandler } from '../utils/errorHandling';
-import { fromApiFormat } from './converters';
+import { ERROR_MESSAGES } from '../utils/errorHandling';
+import { entityPropertyFromApi } from './converters';
/**
* Fetch all properties for an entity
@@ -27,29 +27,29 @@ export async function fetchEntityProperties(
});
if (isErr(result)) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.properties.fetchEntityProperties:',
result,
- 'api.properties.fetchEntityProperties',
- 'Failed to load properties'
+ ERROR_MESSAGES.PROPERTY_FETCH
);
return {
ok: false,
error: {
code: 'API_ERROR',
- message: 'Failed to load properties',
+ message: ERROR_MESSAGES.PROPERTY_FETCH,
},
};
}
const [, data] = result;
- const properties = data.properties.map(fromApiFormat);
+ const properties = data.properties.map(entityPropertyFromApi);
return { ok: true, value: properties };
} catch (error) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.properties.fetchEntityProperties:',
error,
- 'api.properties.fetchEntityProperties',
- 'Failed to load properties'
+ ERROR_MESSAGES.PROPERTY_FETCH
);
return {
ok: false,
diff --git a/js/app/packages/core/component/Properties/api/index.ts b/js/app/packages/core/component/Properties/api/index.ts
index 400ea77c41..32ca096c67 100644
--- a/js/app/packages/core/component/Properties/api/index.ts
+++ b/js/app/packages/core/component/Properties/api/index.ts
@@ -1,7 +1,7 @@
-export { fromApiFormat, toApiFormat } from './converters';
+export { entityPropertyFromApi, propertyValueToApi } from './converters';
export { fetchEntityProperties } from './fetchProperties';
export {
- addPropertyToEntity,
+ addEntityProperty,
deleteEntityProperty,
- savePropertyValue,
+ saveEntityProperty,
} from './propertyValues';
diff --git a/js/app/packages/core/component/Properties/api/propertyValues.ts b/js/app/packages/core/component/Properties/api/propertyValues.ts
index 0f09edb22a..f85ab76535 100644
--- a/js/app/packages/core/component/Properties/api/propertyValues.ts
+++ b/js/app/packages/core/component/Properties/api/propertyValues.ts
@@ -2,25 +2,25 @@ 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 { ErrorHandler } from '../utils/errorHandling';
-import { toApiFormat } from './converters';
+import { ERROR_MESSAGES } from '../utils/errorHandling';
+import { propertyValueToApi } from './converters';
/**
- * Save a property value
+ * 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 savePropertyValue(
+export async function saveEntityProperty(
entityId: string,
entityType: EntityType,
property: Property,
apiValues: PropertyApiValues
): Promise<Result<void>> {
try {
- const propertyValue = toApiFormat(apiValues, property.isMultiSelect);
+ const propertyValue = propertyValueToApi(apiValues, property.isMultiSelect);
const result = await propertiesServiceClient.setEntityProperty({
entity_type: entityType,
@@ -32,26 +32,26 @@ export async function savePropertyValue(
});
if (isErr(result)) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.propertyValues.saveEntityProperty:',
result,
- 'api.propertyValues.savePropertyValue',
- 'Failed to save property value'
+ ERROR_MESSAGES.PROPERTY_SAVE
);
return {
ok: false,
error: {
code: 'API_ERROR',
- message: 'Failed to save property value',
+ message: ERROR_MESSAGES.PROPERTY_SAVE,
},
};
}
return { ok: true, value: undefined };
} catch (error) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.propertyValues.saveEntityProperty:',
error,
- 'api.propertyValues.savePropertyValue',
- 'Failed to save property value'
+ ERROR_MESSAGES.PROPERTY_SAVE
);
return {
ok: false,
@@ -75,26 +75,26 @@ export async function deleteEntityProperty(
});
if (isErr(result)) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.propertyValues.deleteEntityProperty:',
result,
- 'api.propertyValues.deleteEntityProperty',
- 'Failed to delete property'
+ ERROR_MESSAGES.PROPERTY_DELETE
);
return {
ok: false,
error: {
code: 'API_ERROR',
- message: 'Failed to delete property',
+ message: ERROR_MESSAGES.PROPERTY_DELETE,
},
};
}
return { ok: true, value: undefined };
} catch (error) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.propertyValues.deleteEntityProperty:',
error,
- 'api.propertyValues.deleteEntityProperty',
- 'Failed to delete property'
+ ERROR_MESSAGES.PROPERTY_DELETE
);
return {
ok: false,
@@ -107,7 +107,7 @@ export async function deleteEntityProperty(
}
/**
- * Add a property to an entity without an initial value
+ * 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.)
@@ -116,7 +116,7 @@ export async function deleteEntityProperty(
* @param entityType - The type of entity (e.g., 'document', 'channel', 'project')
* @param propertyDefinitionId - The ID of the property definition to add
*/
-export async function addPropertyToEntity(
+export async function addEntityProperty(
entityId: string,
entityType: EntityType,
propertyDefinitionId: string
@@ -132,26 +132,26 @@ export async function addPropertyToEntity(
});
if (isErr(result)) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.propertyValues.addEntityProperty:',
result,
- 'api.propertyValues.addPropertyToEntity',
- 'Failed to add property'
+ ERROR_MESSAGES.PROPERTY_ADD
);
return {
ok: false,
error: {
code: 'API_ERROR',
- message: 'Failed to add property',
+ message: ERROR_MESSAGES.PROPERTY_ADD,
},
};
}
return { ok: true, value: undefined };
} catch (error) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'api.propertyValues.addEntityProperty:',
error,
- 'api.propertyValues.addPropertyToEntity',
- 'Failed to add property'
+ ERROR_MESSAGES.PROPERTY_ADD
);
return {
ok: false,
diff --git a/js/app/packages/core/component/Properties/api/utils.ts b/js/app/packages/core/component/Properties/api/utils.ts
deleted file mode 100644
index f7b3d23d82..0000000000
--- a/js/app/packages/core/component/Properties/api/utils.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { toast } from '@core/component/Toast/Toast';
-import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import type { Property, PropertyApiValues } from '../types';
-import { ErrorHandler } from '../utils/errorHandling';
-import {
- addPropertyToEntity as apiAddPropertyToEntity,
- deleteEntityProperty as apiDeleteEntityProperty,
- savePropertyValue as apiSavePropertyValue,
-} from './index';
-
-/**
- * Shared utility for saving property values with consistent error handling
- *
- * @param entityId - The ID of the block/entity
- * @param property - The property to save
- * @param apiValues - The values to save
- * @param entityType - The type of entity
- */
-export async function savePropertyValue(
- entityId: string,
- property: Property,
- apiValues: PropertyApiValues,
- entityType: EntityType
-): Promise<boolean> {
- const result = await apiSavePropertyValue(
- entityId,
- entityType,
- property,
- apiValues
- );
-
- if (!result.ok) {
- ErrorHandler.handleApiError(
- result.error,
- 'apiUtils.savePropertyValue',
- 'Failed to save property value'
- );
- toast.failure('Failed to save property value');
- return false;
- }
-
- return true;
-}
-
-/**
- * Shared utility for removing entity properties with consistent error handling
- *
- * @param entityPropertyId - The ID of the entity property to delete
- */
-export async function removeEntityProperty(
- entityPropertyId: string
-): Promise<boolean> {
- const result = await apiDeleteEntityProperty(entityPropertyId);
-
- if (!result.ok) {
- ErrorHandler.handleApiError(
- result.error,
- 'apiUtils.removeEntityProperty',
- 'Failed to delete property'
- );
- toast.failure('Failed to delete property');
- return false;
- }
-
- return true;
-}
-
-/**
- * Shared utility for adding properties to entities with consistent error handling
- *
- * @param entityId - The ID of the block/entity
- * @param propertyDefinitionId - The ID of the property definition to add
- * @param entityType - The type of entity
- */
-export async function addEntityProperty(
- entityId: string,
- propertyDefinitionId: string,
- entityType: EntityType
-): Promise<boolean> {
- const result = await apiAddPropertyToEntity(
- entityId,
- entityType,
- propertyDefinitionId
- );
-
- if (!result.ok) {
- ErrorHandler.handleApiError(
- result.error,
- 'apiUtils.addEntityProperty',
- 'Failed to add property'
- );
- toast.failure(result.error.message || 'Failed to add property');
- return false;
- }
-
- return true;
-}
diff --git a/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsx b/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsx
index 1f902f23ff..553a91e662 100644
--- a/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/CreatePropertyModal.tsx
@@ -16,11 +16,7 @@ import {
Show,
} from 'solid-js';
import { Portal } from 'solid-js/web';
-import {
- BUTTON_BASE_CLASSES,
- PRIMARY_BUTTON_CLASSES,
- SECONDARY_BUTTON_CLASSES,
-} from '../../constants';
+import { PROPERTY_STYLES } from '../../styles';
import {
getPropertyDataTypeDropdownOptions,
usePropertyNameFocus,
@@ -187,7 +183,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
// Validate that we have a user ID for user-scoped properties
if (!orgId && !currentUserId) {
- setError('Unable to create property: user information not available');
+ setError(ERROR_MESSAGES.PROPERTY_CREATE);
return;
}
@@ -215,7 +211,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
});
if (isErr(result)) {
- setError(ERROR_MESSAGES.CREATE_PROPERTY);
+ setError(ERROR_MESSAGES.PROPERTY_CREATE);
return;
}
@@ -223,7 +219,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
props.onPropertyCreated?.();
props.onClose();
} catch (_error) {
- setError(ERROR_MESSAGES.CREATE_PROPERTY);
+ setError(ERROR_MESSAGES.PROPERTY_CREATE);
} finally {
setIsCreatingProperty(false);
}
@@ -567,7 +563,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
<div class="flex gap-2">
<button
type="button"
- class={`${BUTTON_BASE_CLASSES} ${SECONDARY_BUTTON_CLASSES}`}
+ class={`${PROPERTY_STYLES.button.base} ${PROPERTY_STYLES.button.secondary}`}
onClick={() => {
resetCreateForm();
props.onClose();
@@ -579,7 +575,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
</div>
<button
type="button"
- class={`${BUTTON_BASE_CLASSES} ${newPropertyName().trim() && !isCreatingProperty() ? PRIMARY_BUTTON_CLASSES : 'bg-ink-muted text-ink cursor-not-allowed'}`}
+ class={`${PROPERTY_STYLES.button.base} ${newPropertyName().trim() && !isCreatingProperty() ? PROPERTY_STYLES.button.primary : 'bg-ink-muted text-ink cursor-not-allowed'}`}
onClick={handleCreateProperty}
disabled={!newPropertyName().trim() || isCreatingProperty()}
>
diff --git a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
index e265167716..12a6eff2cc 100644
--- a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
@@ -14,16 +14,15 @@ import {
Show,
} from 'solid-js';
import { Portal } from 'solid-js/web';
-import { savePropertyValue } from '../../api/propertyValues';
+import { saveEntityProperty } from '../../api';
import { MODAL_DIMENSIONS } from '../../constants';
-import { usePropertyEditor } from '../../hooks/usePropertyModals';
+import { usePropertyEditor } from '../../hooks/usePropertyEditor';
import type { PropertyApiValues, PropertyEditorProps } from '../../types';
import { getValueTypeDisplay } from '../../utils';
import {
entityReferencesToIdSet,
updateEntityReferences,
} from '../../utils/entityConversion';
-import { ErrorHandler } from '../../utils/errorHandling';
import { PropertyEntitySelector } from './shared/PropertyEntitySelector';
import { PropertyOptionSelector } from './shared/PropertyOptionSelector';
@@ -39,7 +38,7 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
const [selectedEntityRefs, setSelectedEntityRefs] = createSignal<
EntityReference[]
>(
- props.property.valueType === 'ENTITY' && props.property.value
+ props.property.valueType === 'ENTITY' && props.property.value != null
? props.property.value
: []
);
@@ -80,18 +79,17 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
}
default:
// Should not reach here as modal only handles select and entity types
- ErrorHandler.handleApiError(
+ console.error(
+ 'PropertyEditor.saveChanges:',
new Error(
`Invalid property type for modal editor: ${props.property.valueType}`
- ),
- 'PropertyEditor.saveChanges',
- 'Invalid property type'
+ )
);
return;
}
- // savePropertyValue already handles error logging and user feedback
- const result = await savePropertyValue(
+ // saveEntityProperty already handles error logging and user feedback
+ const result = await saveEntityProperty(
blockId,
props.entityType,
props.property,
@@ -109,7 +107,7 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
if (props.property.valueType !== 'ENTITY') return false;
const currentRefs = selectedEntityRefs();
- const originalRefs = (props.property.value as EntityReference[]) || [];
+ const originalRefs = props.property.value ?? [];
// Compare lengths first
if (currentRefs.length !== originalRefs.length) return true;
diff --git a/js/app/packages/core/component/Properties/component/modal/Modals.tsx b/js/app/packages/core/component/Properties/component/modal/Modals.tsx
index f7b1d094db..2706ef572a 100644
--- a/js/app/packages/core/component/Properties/component/modal/Modals.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/Modals.tsx
@@ -1,10 +1,12 @@
import { useBlockId } from '@core/block';
import { DatePicker } from '@core/component/DatePicker';
+import { toast } from '@core/component/Toast/Toast';
import { type Component, createMemo } from 'solid-js';
import { Portal, Show } from 'solid-js/web';
-import { savePropertyValue } from '../../api/utils';
+import { saveEntityProperty } from '../../api';
import { usePropertiesContext } from '../../context/PropertiesContext';
import type { Property } from '../../types';
+import { ERROR_MESSAGES } from '../../utils/errorHandling';
import { CreatePropertyModal } from './CreatePropertyModal';
import { EditPropertyValueModal } from './EditPropertyValueModal';
import { SelectPropertyModal } from './SelectPropertyModal';
@@ -36,15 +38,22 @@ export const Modals: Component = () => {
};
const handleDateSaved = async (newDate: Date, property: Property) => {
- const success = await savePropertyValue(
- blockId,
- property,
- { valueType: 'DATE', value: newDate.toISOString() },
- entityType
- );
- if (success) {
- onRefresh();
+ const result = await saveEntityProperty(blockId, entityType, property, {
+ valueType: 'DATE',
+ value: newDate.toISOString(),
+ });
+
+ if (!result.ok) {
+ console.error(
+ 'Modals.handleDateSaved:',
+ result.error,
+ ERROR_MESSAGES.PROPERTY_SAVE
+ );
+ toast.failure(ERROR_MESSAGES.PROPERTY_SAVE);
+ return;
}
+
+ onRefresh();
closeDatePicker();
};
@@ -59,7 +68,7 @@ export const Modals: Component = () => {
<SelectPropertyModal
isOpen={true}
onClose={closePropertySelector}
- existingPropertyIds={existingPropertyIds()}
+ existingPropertyIds={existingPropertyIds}
/>
</Show>
@@ -87,9 +96,8 @@ export const Modals: Component = () => {
<Show when={datePickerModal()}>
{(state) => {
const property = state().property;
- const dateValue = property.value
- ? new Date(property.value)
- : new Date();
+ const dateValue =
+ property.value != null ? new Date(property.value) : new Date();
const anchor = state().anchor;
return anchor ? (
diff --git a/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsx b/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsx
index c120f3ca9a..f1c5e83ac5 100644
--- a/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/SelectPropertyModal.tsx
@@ -1,5 +1,6 @@
import { useBlockId } from '@core/block';
import { IconButton } from '@core/component/IconButton';
+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';
@@ -7,23 +8,17 @@ import LoadingSpinner from '@icon/regular/spinner.svg';
import XIcon from '@icon/regular/x.svg';
import { createEffect, createSignal, For, Show } from 'solid-js';
import { Portal } from 'solid-js/web';
-import { addEntityProperty } from '../../api/utils';
-import {
- ACCENT_BUTTON_CLASSES,
- BUTTON_BASE_CLASSES,
- CHECKBOX_BASE_CLASSES,
- MODAL_DIMENSIONS,
- PRIMARY_BUTTON_CLASSES,
- SECONDARY_BUTTON_CLASSES,
-} from '../../constants';
+import { addEntityProperty } from '../../api';
+import { MODAL_DIMENSIONS } from '../../constants';
import { usePropertiesContext } from '../../context/PropertiesContext';
-import { usePropertyModals } from '../../hooks/usePropertyModals';
-import { PROPERTY_STYLES } from '../../styles/styles';
+import { usePropertySelection } from '../../hooks/usePropertySelection';
+import { PROPERTY_STYLES } from '../../styles';
import type { PropertySelectorProps } from '../../types';
import {
getPropertyDefinitionTypeDisplay,
useSearchInputFocus,
} from '../../utils';
+import { ERROR_MESSAGES } from '../../utils/errorHandling';
import { CreatePropertyModal } from './CreatePropertyModal';
export function SelectPropertyModal(props: PropertySelectorProps) {
@@ -41,7 +36,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {
filteredProperties,
fetchAvailableProperties,
togglePropertySelection,
- } = usePropertyModals(props.existingPropertyIds, () => searchQuery());
+ } = usePropertySelection(props.existingPropertyIds, () => searchQuery());
const handleAddProperties = async () => {
const selected = state().selectedPropertyIds;
@@ -52,25 +47,41 @@ export function SelectPropertyModal(props: PropertySelectorProps) {
try {
const addPromises = Array.from(selected).map(
async (propertyDefinitionId) => {
- return await addEntityProperty(
+ const result = await addEntityProperty(
blockId,
- propertyDefinitionId,
- entityType
+ entityType,
+ propertyDefinitionId
);
+
+ if (!result.ok) {
+ console.error(
+ 'SelectPropertyModal.handleAddProperties:',
+ result.error,
+ ERROR_MESSAGES.PROPERTY_ADD
+ );
+ toast.failure(ERROR_MESSAGES.PROPERTY_ADD);
+ }
+
+ return result.ok;
}
);
const results = await Promise.all(addPromises);
- const failures = results.filter((success: boolean) => !success);
+ const failures = results.filter((success) => !success);
- // Close modal regardless of success/failure (toast already shown by addEntityProperty)
+ // Close modal regardless of success/failure (toasts already shown)
props.onClose();
if (failures.length === 0) {
onPropertyAdded();
}
- } catch (_error) {
- // Close modal (toast already shown by addEntityProperty)
+ } catch (error) {
+ console.error(
+ 'SelectPropertyModal.handleAddProperties:',
+ error,
+ ERROR_MESSAGES.PROPERTY_ADD
+ );
+ toast.failure(ERROR_MESSAGES.PROPERTY_ADD);
props.onClose();
} finally {
setIsAdding(false);
@@ -264,13 +275,16 @@ export function SelectPropertyModal(props: PropertySelectorProps) {
</h4>
</div>
<div class="text-xs text-ink-muted mt-0.5">
- {getPropertyDefinitionTypeDisplay(
- property
- )}
+ {getPropertyDefinitionTypeDisplay({
+ dataType: property.data_type,
+ specificEntityType:
+ property.specific_entity_type,
+ isMultiSelect: property.is_multi_select,
+ })}
</div>
</div>
<div
- class={`${CHECKBOX_BASE_CLASSES} border-edge bg-transparent`}
+ class={`${PROPERTY_STYLES.checkbox.base} border-edge bg-transparent`}
>
<Show when={isSelected()}>
<CheckIcon class="w-3 h-3 text-accent" />
@@ -291,7 +305,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {
<div class="flex items-center justify-between p-4 pt-2">
<button
type="button"
- class={`${BUTTON_BASE_CLASSES} ${SECONDARY_BUTTON_CLASSES}`}
+ class={`${PROPERTY_STYLES.button.base} ${PROPERTY_STYLES.button.secondary}`}
onClick={() => props.onClose()}
disabled={isAdding()}
>
@@ -300,7 +314,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {
<Show when={state().selectedPropertyIds.size > 0}>
<button
type="button"
- class={`${BUTTON_BASE_CLASSES} ${state().selectedPropertyIds.size > 0 && !isAdding() ? PRIMARY_BUTTON_CLASSES : 'bg-ink-muted text-ink cursor-not-allowed'}`}
+ class={`${PROPERTY_STYLES.button.base} ${state().selectedPropertyIds.size > 0 && !isAdding() ? PROPERTY_STYLES.button.primary : 'bg-ink-muted text-ink cursor-not-allowed'}`}
onClick={handleAddProperties}
disabled={
state().selectedPropertyIds.size === 0 || isAdding()
@@ -329,7 +343,7 @@ export function SelectPropertyModal(props: PropertySelectorProps) {
<button
type="button"
onClick={() => setIsCreating(true)}
- class={`${BUTTON_BASE_CLASSES} ${ACCENT_BUTTON_CLASSES}`}
+ class={`${PROPERTY_STYLES.button.base} ${PROPERTY_STYLES.button.accent}`}
disabled={state().isLoading}
>
Create New Property
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
index e4da791b36..378e634fb1 100644
--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
@@ -248,7 +248,10 @@ export function PropertyEntitySelector(props: EntityInputProps) {
}
// Add missing selected entities from property value (handles pagination)
- if (props.property.valueType === 'ENTITY' && props.property.value) {
+ if (
+ props.property.valueType === 'ENTITY' &&
+ props.property.value != null
+ ) {
const allAvailableEntities = entities();
for (const ref of props.property.value) {
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx
index ad13ebd7c6..082ab88c31 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
@@ -8,7 +8,7 @@ import type { z } from 'zod';
import { PROPERTY_STYLES } from '../../../styles/styles';
import type { Property } from '../../../types';
import { formatOptionValue, useSearchInputFocus } from '../../../utils';
-import { ErrorHandler } from '../../../utils/errorHandling';
+import { ERROR_MESSAGES } from '../../../utils/errorHandling';
type PropertyOption = z.infer<typeof schemas.getPropertyOptionsResponseItem>;
@@ -72,10 +72,10 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
await props.onAddOption(searchQuery().trim());
setSearchQuery('');
} catch (error) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'PropertyOptionsList.handleAddOption:',
error,
- 'PropertyOptionsList.handleAddOption',
- 'Failed to add option'
+ ERROR_MESSAGES.OPTION_ADD
);
} finally {
setIsAddingOption(false);
@@ -118,7 +118,10 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {
return allOptions;
});
- useSearchInputFocus(() => searchInputRef);
+ useSearchInputFocus(
+ () => searchInputRef,
+ () => !props.isLoading && !props.error
+ );
const AddOptionButton = () => (
<div
diff --git a/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsx b/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsx
index 8e8110b964..8e49ff6a8d 100644
--- a/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsx
+++ b/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsx
@@ -15,7 +15,7 @@ export const PropertyGrid: Component<PropertiesListProps> = (props) => {
(prop) =>
prop.isMetadata &&
// Hide "Project" property if value is null
- !(prop.displayName === 'Project' && prop.value === undefined)
+ !(prop.displayName === 'Project' && prop.value == null)
)
);
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/BooleanValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/BooleanValue.tsx
index 73442848c0..aa9680cbba 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/BooleanValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/BooleanValue.tsx
@@ -14,19 +14,19 @@ type BooleanValueProps = {
/**
* Display component for boolean properties with instant toggle
- * Treats undefined as false (unchecked)
+ * Treats null as false (unchecked)
*/
export const BooleanValue: Component<BooleanValueProps> = (props) => {
const { value, isSaving, toggle } = useBooleanEditor(
- props.property as Property & { valueType: 'boolean' },
+ props.property as Property & { valueType: 'BOOLEAN' },
props.entityType,
props.onRefresh
);
const isReadOnly = () => props.property.isMetadata || !props.canEdit;
- // Treat undefined/null as false
- const isChecked = () => value() === true;
+ // Treat null as false - use !! to convert any truthy value to boolean
+ const isChecked = () => !!value();
const handleClick = () => {
if (!isReadOnly() && !isSaving()) {
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx
index bef6f0a53d..7c3633fe55 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx
@@ -23,9 +23,10 @@ export const DateValue: Component<DateValueProps> = (props) => {
const isReadOnly = () => props.property.isMetadata || !props.canEdit;
- const displayValue = props.property.value
- ? formatDate(props.property.value as Date)
- : '';
+ const displayValue =
+ props.property.value != null
+ ? formatDate(props.property.value as Date)
+ : '';
return (
<button
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsx
index cca10c74cc..15ad6f85f8 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/EntityValue.tsx
@@ -3,7 +3,7 @@ import type { EntityReference } from '@service-properties/generated/schemas/enti
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import type { Component } from 'solid-js';
import { createSignal, For, Show } from 'solid-js';
-import { savePropertyValue } from '../../api/propertyValues';
+import { saveEntityProperty } from '../../api';
import type { Property } from '../../types';
import { EntityIcon } from './EntityIcon';
import { AddPropertyValueButton, EmptyValue } from './ValueComponents';
@@ -38,12 +38,12 @@ export const EntityValue: Component<EntityValueProps> = (props) => {
try {
const entities = (props.property.value as EntityReference[]) ?? [];
const newValues = entities.filter(
- (entity) =>
+ (entity: EntityReference) =>
entity.entity_id !== entityToRemove.entity_id ||
entity.entity_type !== entityToRemove.entity_type
);
- const result = await savePropertyValue(
+ const result = await saveEntityProperty(
blockId,
props.entityType,
props.property,
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsx
index 3c2f98afbe..7c5a4b724b 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/LinkValue.tsx
@@ -8,9 +8,10 @@ import { proxyResource } from '@service-unfurl/client';
import type { Component } from 'solid-js';
import { createSignal, For, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
-import { savePropertyValue } from '../../api/propertyValues';
+import { saveEntityProperty } from '../../api';
import type { Property } from '../../types';
import { extractDomain, isValidUrl, normalizeUrl } from '../../utils';
+import { ERROR_MESSAGES } from '../../utils/errorHandling';
import { AddPropertyValueButton, EmptyValue } from './ValueComponents';
type LinkValueProps = {
@@ -30,7 +31,7 @@ export const LinkValue: Component<LinkValueProps> = (props) => {
const [badLinks, setBadLinks] = createStore<Record<string, true>>({});
const isReadOnly = () => props.property.isMetadata || !props.canEdit;
- const linkValues = (props.property.value || []) as string[];
+ const linkValues = (props.property.value ?? []) as string[];
const startAdding = () => {
if (isReadOnly()) return;
@@ -74,7 +75,7 @@ export const LinkValue: Component<LinkValueProps> = (props) => {
newValues = [normalized];
}
- const result = await savePropertyValue(
+ const result = await saveEntityProperty(
blockId,
props.entityType,
props.property,
@@ -88,10 +89,10 @@ export const LinkValue: Component<LinkValueProps> = (props) => {
cancelAdding();
props.onRefresh?.();
} else {
- setError('Failed to save link');
+ setError(ERROR_MESSAGES.PROPERTY_SAVE);
}
} catch (_err) {
- setError('Failed to save link');
+ setError(ERROR_MESSAGES.PROPERTY_SAVE);
} finally {
setIsSaving(false);
}
@@ -105,7 +106,7 @@ export const LinkValue: Component<LinkValueProps> = (props) => {
try {
const newValues = linkValues.filter((link) => link !== url);
- const result = await savePropertyValue(
+ const result = await saveEntityProperty(
blockId,
props.entityType,
props.property,
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/NumberValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/NumberValue.tsx
index 8f965a2188..6d8835f5ec 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/NumberValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/NumberValue.tsx
@@ -45,8 +45,7 @@ export const NumberValue: Component<NumberValueProps> = (props) => {
}
};
- const hasValue = () =>
- !(props.property.value === undefined || props.property.value === null);
+ const hasValue = () => props.property.value != null;
const displayValue = hasValue()
? formatNumber(props.property.value as number)
: '';
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsx
index e0695d0113..265e89c4d1 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/SelectValue.tsx
@@ -4,7 +4,7 @@ import DeleteIcon from '@icon/bold/x-bold.svg';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import type { Component } from 'solid-js';
import { createSignal, For, Show } from 'solid-js';
-import { savePropertyValue } from '../../api/propertyValues';
+import { saveEntityProperty } from '../../api';
import { PROPERTY_STYLES } from '../../styles/styles';
import type { Property } from '../../types';
import { formatPropertyValue } from '../../utils';
@@ -47,7 +47,7 @@ export const SelectValue: Component<SelectValueProps> = (props) => {
return;
}
- const result = await savePropertyValue(
+ const result = await saveEntityProperty(
blockId,
props.entityType,
props.property,
@@ -66,7 +66,7 @@ export const SelectValue: Component<SelectValueProps> = (props) => {
};
const isReadOnly = () => props.property.isMetadata || !props.canEdit;
- const displayValues = (props.property.value || []) as string[];
+ const displayValues = (props.property.value ?? []) as string[];
return (
<div
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/TextValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/TextValue.tsx
index 4c2391c553..597012d11a 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/TextValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/TextValue.tsx
@@ -45,7 +45,7 @@ export const TextValue: Component<TextValueProps> = (props) => {
};
const hasValue = () =>
- props.property.value &&
+ props.property.value != null &&
typeof props.property.value === 'string' &&
props.property.value.length > 0;
diff --git a/js/app/packages/core/component/Properties/constants.ts b/js/app/packages/core/component/Properties/constants.ts
index 037278ccbf..b3b5646800 100644
--- a/js/app/packages/core/component/Properties/constants.ts
+++ b/js/app/packages/core/component/Properties/constants.ts
@@ -1,10 +1,12 @@
+/**
+ * Business logic constants for Properties components
+ * For styling constants, see styles/styles.ts (PROPERTY_STYLES)
+ */
+
export const NUMBER_DECIMAL_PLACES = 4; // Matches backend precision
export const FOCUS_CONFIG = {
- DEFAULT_DELAY: 100, // Initial render delay
- PROPERTY_NAME_DELAY: 200, // Modal animation delay
- MAX_ATTEMPTS: 10, // Max focus retries
- RETRY_DELAY: 50, // Retry interval
+ DELAY: 100, // Delay before focusing element after it's connected to DOM
} as const;
export const MODAL_DIMENSIONS = {
@@ -16,16 +18,3 @@ export const MODAL_DIMENSIONS = {
SELECTOR_SMALL_SCREEN_THRESHOLD: 600, // Mobile breakpoint
SELECTOR_SMALL_SCREEN_TOP_PERCENTAGE: 0.1, // 10% from top
} as const;
-
-// Button classes
-export const BUTTON_BASE_CLASSES = 'px-3 py-1.5 text-sm border';
-export const PRIMARY_BUTTON_CLASSES =
- 'bg-accent/90 hover:bg-accent/80 text-ink';
-export const SECONDARY_BUTTON_CLASSES =
- 'text-ink-muted hover:text-ink border-edge hover:bg-hover';
-export const ACCENT_BUTTON_CLASSES =
- 'text-accent hover:text-accent/80 border-accent hover:bg-accent/10';
-
-// Checkbox classes
-export const CHECKBOX_BASE_CLASSES =
- 'w-4 h-4 border flex items-center justify-center';
diff --git a/js/app/packages/core/component/Properties/hooks/index.ts b/js/app/packages/core/component/Properties/hooks/index.ts
index 223a2efc45..9aaa7a4cfd 100644
--- a/js/app/packages/core/component/Properties/hooks/index.ts
+++ b/js/app/packages/core/component/Properties/hooks/index.ts
@@ -1,4 +1,5 @@
export { useBooleanEditor } from './useBooleanEditor';
export { useEntityProperties } from './useEntityProperties';
export { useInlineEditor } from './useInlineEditor';
-export { usePropertyModals } from './usePropertyModals';
+export { usePropertyEditor } from './usePropertyEditor';
+export { usePropertySelection } from './usePropertySelection';
diff --git a/js/app/packages/core/component/Properties/hooks/useBooleanEditor.ts b/js/app/packages/core/component/Properties/hooks/useBooleanEditor.ts
index 9608dead26..8f1893e20a 100644
--- a/js/app/packages/core/component/Properties/hooks/useBooleanEditor.ts
+++ b/js/app/packages/core/component/Properties/hooks/useBooleanEditor.ts
@@ -1,7 +1,7 @@
import { useBlockId } from '@core/block';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { type Accessor, createMemo, createSignal } from 'solid-js';
-import { savePropertyValue } from '../api';
+import { saveEntityProperty } from '../api';
import type { Property } from '../types';
/**
@@ -16,7 +16,7 @@ export function useBooleanEditor(
entityType: EntityType,
onSaved?: () => void
): {
- value: Accessor<boolean | undefined>;
+ value: Accessor<boolean | null>;
isSaving: Accessor<boolean>;
toggle: () => Promise<void>;
} {
@@ -24,7 +24,7 @@ export function useBooleanEditor(
const [isSaving, setIsSaving] = createSignal(false);
const currentValue = createMemo(() => {
- return property.value as boolean | undefined;
+ return property.value as boolean | null;
});
const toggle = async () => {
@@ -33,13 +33,13 @@ export function useBooleanEditor(
setIsSaving(true);
try {
- const actualValue = property.value as boolean | undefined;
+ const actualValue = property.value as boolean | null;
- // If currently unset (undefined), set to true
+ // If currently unset (null), set to true
// Otherwise toggle between true and false
- const newValue = actualValue === undefined ? true : !actualValue;
+ const newValue = actualValue === null ? true : !actualValue;
- const result = await savePropertyValue(blockId, entityType, property, {
+ const result = await saveEntityProperty(blockId, entityType, property, {
valueType: 'BOOLEAN',
value: newValue,
});
diff --git a/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts b/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts
index 3b20a13a95..00bc68272d 100644
--- a/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts
+++ b/js/app/packages/core/component/Properties/hooks/useEntityProperties.ts
@@ -1,11 +1,12 @@
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { type Accessor, createSignal, onMount } from 'solid-js';
import {
- addPropertyToEntity,
+ addEntityProperty,
deleteEntityProperty,
fetchEntityProperties,
} from '../api';
import type { Property } from '../types';
+import { ERROR_MESSAGES } from '../utils/errorHandling';
/**
* Main hook for fetching and managing properties for an entity
@@ -37,6 +38,12 @@ export function useEntityProperties(
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) {
@@ -54,16 +61,10 @@ export function useEntityProperties(
if (result.ok) {
setProperties(result.value);
} else {
- const errorMessage = 'Failed to load properties';
- setError(errorMessage);
- // Return error for component to handle UI feedback
- return { success: false, error: errorMessage };
+ return handleFetchError(ERROR_MESSAGES.PROPERTY_FETCH);
}
} catch (_err) {
- const errorMessage = 'Failed to load properties';
- setError(errorMessage);
- // Return error for component to handle UI feedback
- return { success: false, error: errorMessage };
+ return handleFetchError(ERROR_MESSAGES.PROPERTY_FETCH);
} finally {
setIsLoading(false);
}
@@ -74,7 +75,7 @@ export function useEntityProperties(
const addProperty = async (
propertyDefinitionId: string
): Promise<{ success: boolean; error?: string }> => {
- const result = await addPropertyToEntity(
+ const result = await addEntityProperty(
entityId,
entityType,
propertyDefinitionId
@@ -84,7 +85,7 @@ export function useEntityProperties(
await fetch(); // Refetch to get updated list
return { success: true };
} else {
- return { success: false, error: 'Failed to add property' };
+ return { success: false, error: ERROR_MESSAGES.PROPERTY_ADD };
}
};
@@ -97,7 +98,7 @@ export function useEntityProperties(
await fetch(); // Refetch to get updated list
return { success: true };
} else {
- return { success: false, error: 'Failed to delete property' };
+ return { success: false, error: ERROR_MESSAGES.PROPERTY_DELETE };
}
};
diff --git a/js/app/packages/core/component/Properties/hooks/useInlineEditor.ts b/js/app/packages/core/component/Properties/hooks/useInlineEditor.ts
index 4256d88994..7f10aea6b2 100644
--- a/js/app/packages/core/component/Properties/hooks/useInlineEditor.ts
+++ b/js/app/packages/core/component/Properties/hooks/useInlineEditor.ts
@@ -1,7 +1,7 @@
import { useBlockId } from '@core/block';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { type Accessor, createSignal, type Setter } from 'solid-js';
-import { savePropertyValue } from '../api';
+import { saveEntityProperty } from '../api';
import { NUMBER_DECIMAL_PLACES } from '../constants';
import type { Property, PropertyApiValues } from '../types';
import { formatPropertyValue } from '../utils';
@@ -34,7 +34,7 @@ export function useInlineEditor(
const getCurrentRawValue = () => {
const val = property.value;
- if (val === undefined) return '';
+ if (val == null) return '';
// This hook works with string and number properties
// For these types, val is a single value, not an array
@@ -85,7 +85,7 @@ export function useInlineEditor(
throw new Error(`Unsupported property type: ${property.valueType}`);
}
- const result = await savePropertyValue(
+ const result = await saveEntityProperty(
blockId,
entityType,
property,
diff --git a/js/app/packages/core/component/Properties/hooks/usePropertyModals.ts b/js/app/packages/core/component/Properties/hooks/usePropertyEditor.ts
similarity index 57%
rename from js/app/packages/core/component/Properties/hooks/usePropertyModals.ts
rename to js/app/packages/core/component/Properties/hooks/usePropertyEditor.ts
index 16a7dc3c5a..75bd3f124e 100644
--- a/js/app/packages/core/component/Properties/hooks/usePropertyModals.ts
+++ b/js/app/packages/core/component/Properties/hooks/usePropertyEditor.ts
@@ -1,127 +1,8 @@
import { isErr } from '@core/util/maybeResult';
import { propertiesServiceClient } from '@service-properties/client';
-import { createMemo, createSignal } from 'solid-js';
-import type {
- Property,
- PropertyDefinitionFlat,
- PropertyOption,
-} from '../types';
-import { ERROR_MESSAGES, ErrorHandler } from '../utils/errorHandling';
-
-export interface PropertyManagementState {
- availableProperties: PropertyDefinitionFlat[];
- selectedPropertyIds: Set<string>;
- isLoading: boolean;
- error: string | null;
-}
-
-export function usePropertyModals(
- existingPropertyIds: string[],
- searchQuery?: () => string
-) {
- const [state, setState] = createSignal<PropertyManagementState>({
- availableProperties: [],
- selectedPropertyIds: new Set(),
- isLoading: false,
- error: null,
- });
-
- // Memoize Set creation to avoid recreation on every search keystroke
- const 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 (reactive to existingPropertyIds changes)
- const availableProperties = currentState.availableProperties.filter(
- (property) => property && property.id && !existingIds.has(property.id)
- );
-
- // Then apply search filter
- if (!query) return availableProperties;
-
- return availableProperties.filter((property) => {
- const name = property.display_name.toLowerCase();
- const dataType = property.data_type;
- let typeDisplay = dataType;
-
- if (dataType === 'ENTITY' && property.specific_entity_type) {
- typeDisplay += ` (${property.specific_entity_type})`;
- }
-
- return name.includes(query) || typeDisplay.toLowerCase().includes(query);
- });
- });
-
- const fetchAvailableProperties = async () => {
- setState((prev) => ({ ...prev, isLoading: true, error: null }));
-
- try {
- const result = await propertiesServiceClient.listProperties({
- scope: 'all',
- include_options: true,
- });
-
- if (isErr(result)) {
- setState((prev) => ({
- ...prev,
- error: ERROR_MESSAGES.FETCH_PROPERTIES,
- isLoading: false,
- }));
- return;
- }
-
- const [, data] = result;
- const availableProperties = Array.isArray(data) ? data : [];
-
- // Transform the nested structure to flat structure
- const transformedProperties = availableProperties.map((item) => ({
- ...item.definition,
- propertyOptions: item.property_options || [],
- }));
-
- setState((prev) => ({
- ...prev,
- availableProperties: transformedProperties,
- isLoading: false,
- }));
- } catch (_apiError) {
- setState((prev) => ({
- ...prev,
- error: ERROR_MESSAGES.FETCH_PROPERTIES,
- isLoading: false,
- }));
- }
- };
-
- const togglePropertySelection = (propertyId: string) => {
- setState((prev) => {
- const newSelected = new Set(prev.selectedPropertyIds);
-
- if (newSelected.has(propertyId)) {
- newSelected.delete(propertyId);
- } else {
- newSelected.add(propertyId);
- }
-
- return { ...prev, selectedPropertyIds: newSelected };
- });
- };
-
- const clearSelection = () => {
- setState((prev) => ({ ...prev, selectedPropertyIds: new Set() }));
- };
-
- return {
- state,
- filteredProperties,
- fetchAvailableProperties,
- togglePropertySelection,
- clearSelection,
- };
-}
+import { createSignal } from 'solid-js';
+import type { Property, PropertyOption } from '../types';
+import { ERROR_MESSAGES } from '../utils/errorHandling';
export interface PropertyEditorState {
options: PropertyOption[];
@@ -131,6 +12,10 @@ export interface PropertyEditorState {
hasChanges: boolean;
}
+/**
+ * Hook for managing property value editing in modals
+ * Handles option fetching, selection state, and option creation
+ */
export function usePropertyEditor(property: Property) {
const [state, setState] = createSignal<PropertyEditorState>({
options: [],
@@ -151,7 +36,7 @@ export function usePropertyEditor(property: Property) {
if (isErr(result)) {
setState((prev) => ({
...prev,
- error: ERROR_MESSAGES.FETCH_OPTIONS,
+ error: ERROR_MESSAGES.OPTION_FETCH,
isLoading: false,
}));
return;
@@ -166,7 +51,7 @@ export function usePropertyEditor(property: Property) {
} catch (_apiError) {
setState((prev) => ({
...prev,
- error: ERROR_MESSAGES.FETCH_OPTIONS,
+ error: ERROR_MESSAGES.OPTION_FETCH,
isLoading: false,
}));
}
@@ -175,7 +60,7 @@ export function usePropertyEditor(property: Property) {
const initializeSelectedOptions = () => {
const selected = new Set<string>();
- // For select types, property.value is already an array (or undefined)
+ // For select types, property.value is already an array (or null)
if (
(property.valueType === 'SELECT_STRING' ||
property.valueType === 'SELECT_NUMBER') &&
@@ -269,7 +154,7 @@ export function usePropertyEditor(property: Property) {
});
if (isErr(result)) {
- throw new Error('Failed to create option');
+ throw new Error(ERROR_MESSAGES.OPTION_CREATE);
}
const [, newOption] = result;
@@ -303,10 +188,10 @@ export function usePropertyEditor(property: Property) {
hasChanges: true,
}));
} catch (error) {
- ErrorHandler.handleApiError(
+ console.error(
+ 'usePropertyEditor.addOption:',
error,
- 'usePropertyEditor.addOption',
- 'Failed to add option'
+ ERROR_MESSAGES.OPTION_ADD
);
throw error;
}
diff --git a/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts b/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts
new file mode 100644
index 0000000000..05de208da2
--- /dev/null
+++ b/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts
@@ -0,0 +1,132 @@
+import { isErr } from '@core/util/maybeResult';
+import { propertiesServiceClient } from '@service-properties/client';
+import { 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
+ */
+export function usePropertySelection(
+ existingPropertyIds: () => string[],
+ searchQuery?: () => string
+) {
+ const [state, setState] = createSignal<PropertySelectionState>({
+ availableProperties: [],
+ selectedPropertyIds: new Set(),
+ isLoading: false,
+ error: null,
+ });
+
+ // Memoize Set creation to avoid recreation on every search keystroke
+ // Reactive to existingPropertyIds changes
+ const 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 (reactive to existingPropertyIds changes)
+ const availableProperties = currentState.availableProperties.filter(
+ (property) => property && property.id && !existingIds.has(property.id)
+ );
+
+ // Then apply search filter
+ if (!query) return availableProperties;
+
+ return availableProperties.filter((property) => {
+ const name = property.display_name.toLowerCase();
+ // Check name first before doing string concatenation
+ if (name.includes(query)) {
+ return true;
+ }
+
+ const dataType = property.data_type;
+ let typeDisplay = dataType;
+
+ if (dataType === 'ENTITY' && property.specific_entity_type) {
+ typeDisplay += ` ${property.specific_entity_type}`;
+ }
+
+ return typeDisplay.toLowerCase().includes(query);
+ });
+ });
+
+ const fetchAvailableProperties = async () => {
+ setState((prev) => ({ ...prev, isLoading: true, error: null }));
+
+ try {
+ const result = await propertiesServiceClient.listProperties({
+ scope: 'all',
+ include_options: true,
+ });
+
+ 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 structure to flat structure
+ const transformedProperties = availableProperties.map((item) => ({
+ ...item.definition,
+ propertyOptions: item.property_options || [],
+ }));
+
+ 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);
+
+ if (newSelected.has(propertyId)) {
+ newSelected.delete(propertyId);
+ } else {
+ newSelected.add(propertyId);
+ }
+
+ return { ...prev, selectedPropertyIds: newSelected };
+ });
+ };
+
+ const clearSelection = () => {
+ setState((prev) => ({ ...prev, selectedPropertyIds: new Set() }));
+ };
+
+ return {
+ state,
+ filteredProperties,
+ fetchAvailableProperties,
+ togglePropertySelection,
+ clearSelection,
+ };
+}
diff --git a/js/app/packages/core/component/Properties/styles/styles.ts b/js/app/packages/core/component/Properties/styles/styles.ts
index a13b73538a..5240b480e5 100644
--- a/js/app/packages/core/component/Properties/styles/styles.ts
+++ b/js/app/packages/core/component/Properties/styles/styles.ts
@@ -1,66 +1,28 @@
/**
* Centralized style constants for Properties components
+ * Only includes actively used styles
*/
export const PROPERTY_STYLES = {
- modal: {
- base: 'absolute bg-dialog border-3 border-edge shadow-xl z-modal max-h-96 overflow-hidden flex flex-col w-full max-w-md',
- overlay: 'fixed inset-0 bg-overlay z-modal-overlay',
- header: 'flex items-center justify-between p-4',
- content: 'flex-1 overflow-y-auto max-h-64 px-4 pb-2',
- closeButton:
- 'text-ink-muted hover:text-ink text-xl w-5 h-5 flex items-center justify-center',
- },
-
input: {
- base: 'w-full px-3 py-1.5 border border-edge text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 focus:border-accent',
- inline:
- 'text-right text-ink text-xs px-2 py-1 border border-edge bg-transparent focus:outline-none focus:border-accent',
search:
'w-full pl-10 pr-3 py-1 border border-edge text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 focus:border-accent bg-input text-ink placeholder-ink-muted',
},
- select: {
- base: 'w-full px-3 py-1.5 border border-edge bg-menu text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 focus:border-accent text-ink',
- },
-
button: {
base: 'px-3 py-1.5 text-sm border',
primary: 'bg-accent/90 hover:bg-accent/80 text-ink',
secondary: 'text-ink-muted hover:text-ink border-edge hover:bg-hover',
accent: 'text-accent hover:text-accent/80 border-accent hover:bg-accent/10',
- danger: 'bg-failure hover:bg-failure/90 text-failure-ink',
},
value: {
- display:
- 'text-right text-xs px-2 py-1 border border-edge bg-transparent inline-block max-w-full',
- button:
- 'text-right text-ink text-xs hover:bg-hover px-2 py-1 cursor-pointer border border-edge bg-transparent inline-block max-w-full',
- multi:
- 'text-right text-xs px-2 py-1 border border-edge bg-transparent inline-block shrink-0 max-w-[140px] break-words',
multiButton:
'text-right text-ink text-xs hover:bg-hover px-2 py-1 cursor-pointer border border-edge bg-transparent inline-block shrink-0 max-w-[140px] break-words',
},
checkbox: {
base: 'w-4 h-4 border flex items-center justify-center',
- checked: 'bg-accent border-accent',
- unchecked: 'border-edge bg-transparent',
- },
-
- common: {
- spinner: 'w-5 h-5 animate-spin',
- loadingContainer: 'flex items-center justify-center py-8',
- errorText: 'text-failure-ink text-sm text-center',
- mutedText: 'text-ink-muted',
- truncate: 'truncate',
- },
-
- row: {
- base: 'flex gap-4 w-full group',
- label: 'flex-shrink-0 min-w-[100px] max-w-[45%]',
- value: 'flex-1 flex justify-end',
},
} as const;
diff --git a/js/app/packages/core/component/Properties/types.ts b/js/app/packages/core/component/Properties/types.ts
index b39657a2e7..6df1d81f34 100644
--- a/js/app/packages/core/component/Properties/types.ts
+++ b/js/app/packages/core/component/Properties/types.ts
@@ -36,8 +36,8 @@ export type ValueType =
/**
* UI layer property with discriminated union for type-safe values
*
- * Note: Single-value types use `value?: T`, multi-value types use `value?: T[]`
- * This reflects the semantic difference between logically single vs multiple values.
+ * Note: All value types use `value: T | null` or `value: T[] | null` (not optional properties)
+ * This reflects that unset values are explicitly `null` rather than `undefined`.
*
* @see EntityPropertyWithDefinition - Backend structured type
* @see PropertyValue - Backend discriminated union for values
@@ -54,15 +54,15 @@ export type Property = {
createdAt: string;
updatedAt: string;
} & ( // Single-value types
- | { valueType: 'STRING'; value?: string }
- | { valueType: 'NUMBER'; value?: number }
- | { valueType: 'BOOLEAN'; value?: boolean }
- | { valueType: 'DATE'; value?: Date }
+ | { valueType: 'STRING'; value: string | null }
+ | { valueType: 'NUMBER'; value: number | null }
+ | { valueType: 'BOOLEAN'; value: boolean | null }
+ | { valueType: 'DATE'; value: Date | null }
// Multi-value types (select values are option IDs, not display values)
- | { valueType: 'SELECT_STRING'; value?: string[] }
- | { valueType: 'SELECT_NUMBER'; value?: string[] }
- | { valueType: 'ENTITY'; value?: EntityReference[] }
- | { valueType: 'LINK'; value?: string[] }
+ | { valueType: 'SELECT_STRING'; value: string[] | null }
+ | { valueType: 'SELECT_NUMBER'; value: string[] | null }
+ | { valueType: 'ENTITY'; value: EntityReference[] | null }
+ | { valueType: 'LINK'; value: string[] | null }
);
/**
@@ -135,7 +135,7 @@ export type PropertyEditorProps = {
export type PropertySelectorProps = {
isOpen: boolean;
onClose: () => void;
- existingPropertyIds: string[];
+ existingPropertyIds: () => string[];
};
// Re-export generated API types from service-properties
diff --git a/js/app/packages/core/component/Properties/utils.ts b/js/app/packages/core/component/Properties/utils.ts
deleted file mode 100644
index 1865feabbc..0000000000
--- a/js/app/packages/core/component/Properties/utils.ts
+++ /dev/null
@@ -1,394 +0,0 @@
-import { createEffect, onCleanup } from 'solid-js';
-import { FOCUS_CONFIG, NUMBER_DECIMAL_PLACES } from './constants';
-import type { Property, PropertyOptionValue } from './types';
-
-type PropertyValueUnion = string | number | Date | boolean;
-
-/**
- * Format a number to show up to 4 decimal places
- * Uses exponential notation for numbers beyond safe integer range
- */
-export function formatNumber(value: number): string {
- // Use exponential notation for numbers beyond 15 digits
- // 15 is the largest js can handle
- if (Math.abs(value) >= 1e15 || (value !== 0 && Math.abs(value) < 1e-15)) {
- return value.toExponential(NUMBER_DECIMAL_PLACES);
- }
- // Round to 4 decimal places and remove trailing zeros
- const rounded = parseFloat(value.toFixed(NUMBER_DECIMAL_PLACES));
- return rounded.toString();
-}
-
-/**
- * Format a date value for display
- */
-export function formatDate(value: Date | string): string {
- const date = typeof value === 'string' ? new Date(value) : value;
-
- // Parse as local date to avoid timezone issues
- const dateStr = date.toISOString().split('T')[0];
- const localDate = new Date(dateStr + 'T00:00:00');
-
- return localDate.toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- });
-}
-
-/**
- * Format a boolean value for display
- */
-export function formatBoolean(value: boolean): string {
- return value ? 'True' : 'False';
-}
-
-/**
- * Extract domain from a URL for display
- */
-export function extractDomain(url: string): string {
- try {
- const urlObj = new URL(url);
- return urlObj.hostname;
- } catch {
- return url;
- }
-}
-
-/**
- * Normalize a URL by adding https:// if no protocol is present
- */
-export function normalizeUrl(url: string): string {
- const trimmed = url.trim();
- if (!trimmed) return '';
-
- // Check if URL has a protocol
- if (!/^https?:\/\//i.test(trimmed)) {
- return `https://${trimmed}`;
- }
-
- return trimmed;
-}
-
-/**
- * Validate if a string is a valid URL
- * Requires a proper domain with TLD (e.g., example.com)
- */
-export function isValidUrl(url: string): boolean {
- try {
- const urlObj = new URL(url);
-
- // Check if hostname has at least one dot (for TLD) or is localhost
- const hostname = urlObj.hostname;
- if (hostname === 'localhost' || hostname === '127.0.0.1') {
- return true;
- }
-
- // Must have at least one dot for TLD
- if (!hostname.includes('.')) {
- return false;
- }
-
- // Must have something before and after the dot
- const parts = hostname.split('.');
- if (parts.some((part) => part.length === 0)) {
- return false;
- }
-
- return true;
- } catch {
- return false;
- }
-}
-
-/**
- * Format a property value for display
- * Handles all value types including looking up select options by ID
- * Returns '—' for undefined/null values
- */
-export const formatPropertyValue = (
- property: Property,
- value: PropertyValueUnion | string | undefined
-): string => {
- // Handle undefined/null values
- if (value === undefined || value === null) {
- return '';
- }
-
- // For select types, value is an option ID - look it up in property.options
- if (
- property.valueType === 'SELECT_STRING' ||
- property.valueType === 'SELECT_NUMBER'
- ) {
- const optionId = typeof value === 'string' ? value : String(value);
- return formatOptionValueById(optionId, property.options);
- }
-
- if (property.valueType === 'DATE' && value instanceof Date) {
- return formatDate(value);
- }
-
- if (property.valueType === 'BOOLEAN' && typeof value === 'boolean') {
- return formatBoolean(value);
- }
-
- if (property.valueType === 'NUMBER' && typeof value === 'number') {
- return formatNumber(value);
- }
-
- let formattedValue = value.toString();
-
- // Filter out "macro|" prefix for system owner properties
- if (property.displayName === 'Owner') {
- formattedValue = formattedValue.replace('macro|', '');
- }
-
- return formattedValue;
-};
-
-/**
- * Format a property option value by looking up its UUID in the options list
- * Used when you have an option ID and need to display its value
- *
- * @param optionId - The UUID of the option
- * @param options - The property's options array (from property.options)
- * @returns Formatted display value or the ID if not found
- */
-export const formatOptionValueById = (
- optionId: string,
- options: Array<{ id: string; value: PropertyOptionValue }> | undefined
-): string => {
- if (!options) return optionId;
-
- const option = options.find((opt) => opt.id === optionId);
- if (!option) return optionId; // Fallback to showing the ID if option not found
-
- return formatOptionValue(option);
-};
-
-/**
- * Format a property option value for display (used when you already have the option object)
- * Takes a PropertyOption object and extracts its display value
- */
-export const formatOptionValue = (option: {
- value: PropertyOptionValue;
-}): string => {
- const optionValue = option.value;
- if ('type' in optionValue && 'value' in optionValue) {
- if (optionValue.type === 'string') {
- return optionValue.value;
- }
- if (optionValue.type === 'number') {
- return optionValue.value.toString();
- }
- }
- return 'No value';
-};
-
-/**
- * Get the raw option value (for comparison/selection)
- * Takes a PropertyOption object and extracts its raw value
- */
-export const getOptionValue = (option: {
- value: PropertyOptionValue;
-}): string => {
- const optionValue = option.value;
- if ('type' in optionValue && 'value' in optionValue) {
- if (optionValue.type === 'string') {
- return optionValue.value;
- }
- if (optionValue.type === 'number') {
- return optionValue.value.toString();
- }
- }
- return '';
-};
-
-/**
- * Get dropdown options for property data types
- * This is the single source of truth for all property type labels
- */
-export const getPropertyDataTypeDropdownOptions = () => [
- { value: 'string' as const, label: 'Input' },
- { value: 'number' as const, label: 'Input (Number)' },
- { value: 'boolean' as const, label: 'Checkbox' },
- { value: 'date' as const, label: 'Date' },
- { value: 'link' as const, label: 'Link' },
- { value: 'select_string' as const, label: 'Option' },
- { value: 'select_number' as const, label: 'Option (Number)' },
- { value: 'entity:USER' as const, label: 'User' },
- { value: 'entity:DOCUMENT' as const, label: 'Document' },
- { value: 'entity:CHANNEL' as const, label: 'Channel' },
- { value: 'entity:PROJECT' as const, label: 'Project' },
- { value: 'entity:CHAT' as const, label: 'Chat' },
- // { value: 'entity:THREAD' as const, label: 'Thread' }, // Not yet supported
- { value: 'entity' as const, label: 'Any Entity' },
-];
-
-/**
- * Get display name for a property definition's data type
- * Uses the same labels as the property creation dropdown for consistency
- *
- * Handles both backend UPPERCASE and frontend lowercase data_type values
- */
-export const getPropertyDefinitionTypeDisplay = (property: {
- data_type: string;
- specific_entity_type?: string | null;
- is_multi_select: boolean;
-}): string => {
- if (!property) {
- return 'Unknown';
- }
-
- const { data_type, specific_entity_type, is_multi_select } = property;
-
- if (!data_type || typeof data_type !== 'string') {
- return 'Unknown';
- }
-
- // Normalize to lowercase for comparison with dropdown options
- const dataTypeLower = data_type.toLowerCase();
-
- // Get the base label from dropdown options
- const dropdownOptions = getPropertyDataTypeDropdownOptions();
- let display: string;
-
- if (dataTypeLower === 'entity') {
- // For specific entity types, find the matching dropdown option
- display =
- dropdownOptions.find(
- (opt) => opt.value === `entity:${specific_entity_type}`
- )?.label || `${dataTypeLower[0].toUpperCase() + dataTypeLower.slice(1)}`;
- } else {
- // For other types, find the matching dropdown option
- const option = dropdownOptions.find((opt) => opt.value === dataTypeLower);
- display =
- option?.label ||
- (typeof data_type === 'string'
- ? data_type.replace(/_/g, ' ')
- : 'Unknown');
- }
-
- // Add multi indicator
- if (['select_string', 'select_number', 'link'].includes(dataTypeLower)) {
- display = `${is_multi_select === true ? 'Multi' : 'Single'} ${display}`;
- } else if (dataTypeLower === 'entity') {
- display = `${is_multi_select === true ? 'Multi' : 'Single'}-Select ${display}`;
- }
-
- return display;
-};
-
-/**
- * Get display name for a property's value type
- * For entity types with specificEntityType, returns the specific type (e.g., "User", "Document")
- */
-export const getValueTypeDisplay = (
- property: Pick<Property, 'valueType' | 'specificEntityType'>
-): string => {
- // For entity types, use the specific entity type if available
- if (property.valueType === 'ENTITY' && property.specificEntityType) {
- // Convert from UPPERCASE to Title Case
- const entityTypeLower = property.specificEntityType.toLowerCase();
- return entityTypeLower.charAt(0).toUpperCase() + entityTypeLower.slice(1);
- }
-
- switch (property.valueType) {
- case 'STRING':
- return 'Text';
- case 'NUMBER':
- return 'Number';
- case 'DATE':
- return 'Date';
- case 'BOOLEAN':
- return 'Boolean';
- case 'ENTITY':
- return 'Entity';
- case 'SELECT_STRING':
- return 'Select (Text)';
- case 'SELECT_NUMBER':
- return 'Select (Number)';
- case 'LINK':
- return 'Link';
- default:
- return property.valueType;
- }
-};
-
-/**
- * Consolidated hook for auto-focusing elements with reliable focus handling.
- * Handles race conditions with API responses, modal loading, and DOM updates.
- */
-export function useAutoFocus(
- inputRef: () => HTMLElement | undefined,
- shouldFocus: () => boolean = () => true,
- options: {
- delay?: number;
- maxAttempts?: number;
- } = {}
-) {
- const {
- delay = FOCUS_CONFIG.DEFAULT_DELAY,
- maxAttempts = FOCUS_CONFIG.MAX_ATTEMPTS,
- } = options;
-
- const focusElement = (
- element: HTMLElement | undefined,
- attempts = maxAttempts
- ) => {
- if (!element || attempts <= 0) return;
-
- requestAnimationFrame(() => {
- if (
- element.offsetParent !== null &&
- !('disabled' in element && element.disabled) &&
- element.tabIndex >= 0
- ) {
- try {
- element.focus();
- if (document.activeElement === element) {
- return;
- }
- } catch (_error) {
- // Focus failed, will retry
- }
- }
-
- setTimeout(() => {
- focusElement(element, attempts - 1);
- }, FOCUS_CONFIG.RETRY_DELAY);
- });
- };
-
- createEffect(() => {
- if (shouldFocus()) {
- const timeoutId = setTimeout(() => {
- focusElement(inputRef());
- }, delay);
-
- onCleanup(() => {
- clearTimeout(timeoutId);
- });
- }
- });
-
- return { focusElement };
-}
-
-export function useSearchInputFocus(
- inputRef: () => HTMLInputElement | undefined,
- shouldFocus: () => boolean = () => true
-) {
- return useAutoFocus(inputRef, shouldFocus, {
- delay: FOCUS_CONFIG.DEFAULT_DELAY,
- });
-}
-
-export function usePropertyNameFocus(
- inputRef: () => HTMLInputElement | undefined,
- isCreating: () => boolean
-) {
- return useAutoFocus(inputRef, isCreating, {
- delay: FOCUS_CONFIG.PROPERTY_NAME_DELAY,
- });
-}
diff --git a/js/app/packages/core/component/Properties/utils/display.ts b/js/app/packages/core/component/Properties/utils/display.ts
new file mode 100644
index 0000000000..10edfdf33a
--- /dev/null
+++ b/js/app/packages/core/component/Properties/utils/display.ts
@@ -0,0 +1,115 @@
+import type { Property } from '../types';
+
+/**
+ * Get dropdown options for property data types
+ * This is the single source of truth for all property type labels
+ */
+export const getPropertyDataTypeDropdownOptions = () => [
+ { value: 'string' as const, label: 'Input' },
+ { value: 'number' as const, label: 'Input (Number)' },
+ { value: 'boolean' as const, label: 'Checkbox' },
+ { value: 'date' as const, label: 'Date' },
+ { value: 'link' as const, label: 'Link' },
+ { value: 'select_string' as const, label: 'Option' },
+ { value: 'select_number' as const, label: 'Option (Number)' },
+ { value: 'entity:USER' as const, label: 'User' },
+ { value: 'entity:DOCUMENT' as const, label: 'Document' },
+ { value: 'entity:CHANNEL' as const, label: 'Channel' },
+ { value: 'entity:PROJECT' as const, label: 'Project' },
+ { value: 'entity:CHAT' as const, label: 'Chat' },
+ // { value: 'entity:THREAD' as const, label: 'Thread' }, // Not yet supported
+ { value: 'entity' as const, label: 'Any Entity' },
+];
+
+/**
+ * Get display name for a property definition's data type
+ * Uses the same labels as the property creation dropdown for consistency
+ *
+ * Handles both backend UPPERCASE and frontend lowercase data_type values
+ */
+export const getPropertyDefinitionTypeDisplay = (property: {
+ dataType: string;
+ specificEntityType?: string | null;
+ isMultiSelect: boolean;
+}): string => {
+ if (!property) {
+ return 'Unknown';
+ }
+
+ // Map from camelCase parameters to snake_case for internal use
+ const data_type = property.dataType;
+ const specific_entity_type = property.specificEntityType;
+ const is_multi_select = property.isMultiSelect;
+
+ if (!data_type || typeof data_type !== 'string') {
+ return 'Unknown';
+ }
+
+ // Normalize to lowercase for comparison with dropdown options
+ const dataTypeLower = data_type.toLowerCase();
+
+ // Get the base label from dropdown options
+ const dropdownOptions = getPropertyDataTypeDropdownOptions();
+ let display: string;
+
+ if (dataTypeLower === 'entity') {
+ // For specific entity types, find the matching dropdown option
+ display =
+ dropdownOptions.find(
+ (opt) => opt.value === `entity:${specific_entity_type}`
+ )?.label || `${dataTypeLower[0].toUpperCase() + dataTypeLower.slice(1)}`;
+ } else {
+ // For other types, find the matching dropdown option
+ const option = dropdownOptions.find((opt) => opt.value === dataTypeLower);
+ display =
+ option?.label ||
+ (typeof data_type === 'string'
+ ? data_type.replace(/_/g, ' ')
+ : 'Unknown');
+ }
+
+ // Add multi indicator
+ if (['select_string', 'select_number', 'link'].includes(dataTypeLower)) {
+ display = `${is_multi_select ? 'Multi' : 'Single'} ${display}`;
+ } else if (dataTypeLower === 'entity') {
+ display = `${is_multi_select ? 'Multi' : 'Single'}-Select ${display}`;
+ }
+
+ return display;
+};
+
+/**
+ * Get display name for a property's value type
+ * For entity types with specificEntityType, returns the specific type (e.g., "User", "Document")
+ */
+export const getValueTypeDisplay = (
+ property: Pick<Property, 'valueType' | 'specificEntityType'>
+): string => {
+ // For entity types, use the specific entity type if available
+ if (property.valueType === 'ENTITY' && property.specificEntityType) {
+ // Convert from UPPERCASE to Title Case
+ const entityTypeLower = property.specificEntityType.toLowerCase();
+ return entityTypeLower.charAt(0).toUpperCase() + entityTypeLower.slice(1);
+ }
+
+ switch (property.valueType) {
+ case 'STRING':
+ return 'Text';
+ case 'NUMBER':
+ return 'Number';
+ case 'DATE':
+ return 'Date';
+ case 'BOOLEAN':
+ return 'Boolean';
+ case 'ENTITY':
+ return 'Entity';
+ case 'SELECT_STRING':
+ return 'Select (Text)';
+ case 'SELECT_NUMBER':
+ return 'Select (Number)';
+ case 'LINK':
+ return 'Link';
+ default:
+ return property.valueType;
+ }
+};
diff --git a/js/app/packages/core/component/Properties/utils/errorHandling.ts b/js/app/packages/core/component/Properties/utils/errorHandling.ts
index 5bec57c1fd..be3dddf4bf 100644
--- a/js/app/packages/core/component/Properties/utils/errorHandling.ts
+++ b/js/app/packages/core/component/Properties/utils/errorHandling.ts
@@ -1,89 +1,22 @@
-export interface ErrorResult {
- ok: false;
- error: string;
-}
-
-export interface SuccessResult<T = undefined> {
- ok: true;
- value: T;
-}
-
-export type ApiResult<T = undefined> = SuccessResult<T> | ErrorResult;
-
-/**
- * Standardized error handling for API operations
- * Provides consistent error logging and return values
- * Note: Toast notifications should be handled at the component level
- */
-export class ErrorHandler {
- /**
- * Handle API errors with consistent logging
- */
- static handleApiError(
- error: unknown,
- context: string,
- userMessage?: string
- ): ErrorResult {
- const errorMessage = userMessage || 'An unexpected error occurred';
-
- // Log the full error for debugging
- console.error(`${context}:`, error);
-
- return {
- ok: false,
- error: errorMessage,
- };
- }
-
- /**
- * Handle successful API operations
- */
- static handleSuccess<T>(value: T): SuccessResult<T> {
- return {
- ok: true,
- value,
- };
- }
-
- /**
- * Handle API operations with automatic error handling
- */
- static async handleApiCall<T>(
- apiCall: () => Promise<T>,
- context: string,
- userMessage?: string
- ): Promise<ApiResult<T>> {
- try {
- const result = await apiCall();
- return this.handleSuccess(result);
- } catch (error) {
- return this.handleApiError(error, context, userMessage);
- }
- }
-
- /**
- * Handle validation errors (no API call needed)
- */
- static handleValidationError(message: string): ErrorResult {
- return {
- ok: false,
- error: message,
- };
- }
-}
-
/**
* Common error messages for consistency
+ * Organized by category: properties, options, validation
*/
export const ERROR_MESSAGES = {
- FETCH_PROPERTIES: 'Failed to load properties',
- SAVE_PROPERTY: 'Failed to save property value',
- DELETE_PROPERTY: 'Failed to delete property',
- ADD_PROPERTY: 'Failed to add property',
- CREATE_PROPERTY: 'Failed to create property',
- FETCH_OPTIONS: 'Failed to load property options',
- ADD_OPTION: 'Failed to add option',
+ // Property operations
+ PROPERTY_FETCH: 'Unable to load properties',
+ PROPERTY_SAVE: 'Unable to save property',
+ PROPERTY_DELETE: 'Unable to delete property',
+ PROPERTY_ADD: 'Unable to add property',
+ PROPERTY_CREATE: 'Unable to create property',
+
+ // Option operations
+ OPTION_FETCH: 'Unable to load options',
+ OPTION_ADD: 'Unable to add option',
+ OPTION_CREATE: 'Unable to create option',
+
+ // Validation
VALIDATION_REQUIRED: 'This field is required',
- VALIDATION_DUPLICATE: 'Duplicate values are not allowed',
- VALIDATION_MIN_OPTIONS: 'Must have at least one option',
+ VALIDATION_DUPLICATE: 'Duplicate values not allowed',
+ VALIDATION_MIN_OPTIONS: 'At least one option required',
} as const;
diff --git a/js/app/packages/core/component/Properties/utils/focus.ts b/js/app/packages/core/component/Properties/utils/focus.ts
new file mode 100644
index 0000000000..b35a0685d6
--- /dev/null
+++ b/js/app/packages/core/component/Properties/utils/focus.ts
@@ -0,0 +1,74 @@
+import { createEffect, onCleanup } from 'solid-js';
+import { FOCUS_CONFIG } from '../constants';
+
+/**
+ * Consolidated hook for auto-focusing elements with reliable focus handling.
+ * Uses IntersectionObserver to detect when element becomes visible, then focuses after delay.
+ */
+export function useAutoFocus(
+ inputRef: () => HTMLElement | undefined,
+ shouldFocus: () => boolean = () => true,
+ delay: number = FOCUS_CONFIG.DELAY
+) {
+ createEffect(() => {
+ if (!shouldFocus()) return;
+
+ const element = inputRef();
+ if (!element) return;
+
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+
+ // IntersectionObserver fires when element becomes visible (or immediately if already visible)
+ const intersectionObserver = new IntersectionObserver(
+ (entries) => {
+ const entry = entries[0];
+ if (!entry?.isIntersecting) return;
+
+ // Element is visible, disconnect and focus after delay
+ intersectionObserver.disconnect();
+ timeoutId = setTimeout(() => {
+ const currentElement = inputRef();
+ if (
+ currentElement &&
+ !('disabled' in currentElement && currentElement.disabled) &&
+ currentElement.tabIndex >= 0
+ ) {
+ try {
+ currentElement.focus();
+ } catch (_error) {
+ // Focus failed silently
+ }
+ }
+ }, delay);
+ },
+ {
+ threshold: 0.01,
+ }
+ );
+
+ intersectionObserver.observe(element);
+
+ onCleanup(() => {
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ intersectionObserver.disconnect();
+ });
+ });
+
+ return { focusElement: () => inputRef()?.focus() };
+}
+
+export function useSearchInputFocus(
+ inputRef: () => HTMLInputElement | undefined,
+ shouldFocus: () => boolean = () => true
+) {
+ return useAutoFocus(inputRef, shouldFocus);
+}
+
+export function usePropertyNameFocus(
+ inputRef: () => HTMLInputElement | undefined,
+ isCreating: () => boolean
+) {
+ return useAutoFocus(inputRef, isCreating);
+}
diff --git a/js/app/packages/core/component/Properties/utils/formatting.ts b/js/app/packages/core/component/Properties/utils/formatting.ts
new file mode 100644
index 0000000000..17ee6cabdb
--- /dev/null
+++ b/js/app/packages/core/component/Properties/utils/formatting.ts
@@ -0,0 +1,158 @@
+import { NUMBER_DECIMAL_PLACES } from '../constants';
+import type { Property, PropertyOptionValue } from '../types';
+
+type PropertyValueUnion = string | number | Date | boolean;
+
+/**
+ * Format a number to show up to 4 decimal places
+ * Uses exponential notation for numbers beyond safe integer range
+ */
+export function formatNumber(value: number): string {
+ // Use exponential notation for numbers beyond 15 digits
+ // 15 is the largest js can handle
+ if (Math.abs(value) >= 1e15 || (value !== 0 && Math.abs(value) < 1e-15)) {
+ return value.toExponential(NUMBER_DECIMAL_PLACES);
+ }
+ // Round to 4 decimal places and remove trailing zeros
+ const rounded = parseFloat(value.toFixed(NUMBER_DECIMAL_PLACES));
+ return rounded.toString();
+}
+
+/**
+ * Format a date value for display
+ */
+export function formatDate(value: Date | string): string {
+ const date = typeof value === 'string' ? new Date(value) : value;
+
+ // Parse as local date to avoid timezone issues
+ const dateStr = date.toISOString().split('T')[0];
+ const localDate = new Date(dateStr + 'T00:00:00');
+
+ return localDate.toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ });
+}
+
+/**
+ * Format a boolean value for display
+ */
+export function formatBoolean(value: boolean): string {
+ return value ? 'True' : 'False';
+}
+
+/**
+ * Extract domain from a URL for display
+ */
+export function extractDomain(url: string): string {
+ try {
+ const urlObj = new URL(url);
+ return urlObj.hostname;
+ } catch {
+ return url;
+ }
+}
+
+/**
+ * Format a property value for display
+ * Handles all value types including looking up select options by ID
+ * Returns '—' for undefined/null values
+ */
+export const formatPropertyValue = (
+ property: Property,
+ value: PropertyValueUnion | string | null | undefined
+): string => {
+ // Handle undefined/null values
+ if (value === undefined || value === null) {
+ return '';
+ }
+
+ // For select types, value is an option ID - look it up in property.options
+ if (
+ property.valueType === 'SELECT_STRING' ||
+ property.valueType === 'SELECT_NUMBER'
+ ) {
+ const optionId = typeof value === 'string' ? value : String(value);
+ return formatOptionValueById(optionId, property.options);
+ }
+
+ if (property.valueType === 'DATE' && value instanceof Date) {
+ return formatDate(value);
+ }
+
+ if (property.valueType === 'BOOLEAN' && typeof value === 'boolean') {
+ return formatBoolean(value);
+ }
+
+ if (property.valueType === 'NUMBER' && typeof value === 'number') {
+ return formatNumber(value);
+ }
+
+ let formattedValue = value.toString();
+
+ // Filter out "macro|" prefix for system owner properties
+ if (property.displayName === 'Owner') {
+ formattedValue = formattedValue.replace('macro|', '');
+ }
+
+ return formattedValue;
+};
+
+/**
+ * Format a property option value by looking up its UUID in the options list
+ * Used when you have an option ID and need to display its value
+ *
+ * @param optionId - The UUID of the option
+ * @param options - The property's options array (from property.options)
+ * @returns Formatted display value or the ID if not found
+ */
+export const formatOptionValueById = (
+ optionId: string,
+ options: Array<{ id: string; value: PropertyOptionValue }> | undefined
+): string => {
+ if (!options) return optionId;
+
+ const option = options.find((opt) => opt.id === optionId);
+ if (!option) return optionId; // Fallback to showing the ID if option not found
+
+ return formatOptionValue(option);
+};
+
+/**
+ * Format a property option value for display (used when you already have the option object)
+ * Takes a PropertyOption object and extracts its display value
+ */
+export const formatOptionValue = (option: {
+ value: PropertyOptionValue;
+}): string => {
+ const optionValue = option.value;
+ if ('type' in optionValue && 'value' in optionValue) {
+ if (optionValue.type === 'string') {
+ return optionValue.value;
+ }
+ if (optionValue.type === 'number') {
+ return optionValue.value.toString();
+ }
+ }
+ return 'No value';
+};
+
+/**
+ * Get the raw option value (for comparison/selection)
+ * Takes a PropertyOption object and extracts its raw value
+ */
+export const getOptionValue = (option: {
+ value: PropertyOptionValue;
+}): string => {
+ const optionValue = option.value;
+ if ('type' in optionValue && 'value' in optionValue) {
+ if (optionValue.type === 'string') {
+ return optionValue.value;
+ }
+ if (optionValue.type === 'number') {
+ return optionValue.value.toString();
+ }
+ }
+ return '';
+};
diff --git a/js/app/packages/core/component/Properties/utils/index.ts b/js/app/packages/core/component/Properties/utils/index.ts
index 4d896893eb..bdfd0ec422 100644
--- a/js/app/packages/core/component/Properties/utils/index.ts
+++ b/js/app/packages/core/component/Properties/utils/index.ts
@@ -1,20 +1,9 @@
// Export all utility functions for consistent imports
-// Re-export main utilities from the root utils file
-export {
- formatBoolean,
- formatDate,
- formatNumber,
- formatOptionValue,
- formatOptionValueById,
- formatPropertyValue,
- getOptionValue,
- getPropertyDataTypeDropdownOptions,
- getPropertyDefinitionTypeDisplay,
- getValueTypeDisplay,
- useAutoFocus,
- usePropertyNameFocus,
- useSearchInputFocus,
-} from '../utils';
+// Re-export from focused utility modules
+export * from './display';
export * from './entityConversion';
export * from './errorHandling';
+export * from './focus';
+export * from './formatting';
+export * from './validation';
diff --git a/js/app/packages/core/component/Properties/utils/validation.ts b/js/app/packages/core/component/Properties/utils/validation.ts
new file mode 100644
index 0000000000..5f4298cd84
--- /dev/null
+++ b/js/app/packages/core/component/Properties/utils/validation.ts
@@ -0,0 +1,45 @@
+/**
+ * Normalize a URL by adding https:// if no protocol is present
+ */
+export function normalizeUrl(url: string): string {
+ const trimmed = url.trim();
+ if (!trimmed) return '';
+
+ // Check if URL has a protocol
+ if (!/^https?:\/\//i.test(trimmed)) {
+ return `https://${trimmed}`;
+ }
+
+ return trimmed;
+}
+
+/**
+ * Validate if a string is a valid URL
+ * Requires a proper domain with TLD (e.g., example.com)
+ */
+export function isValidUrl(url: string): boolean {
+ try {
+ const urlObj = new URL(url);
+
+ // Check if hostname has at least one dot (for TLD) or is localhost
+ const hostname = urlObj.hostname;
+ if (hostname === 'localhost' || hostname === '127.0.0.1') {
+ return true;
+ }
+
+ // Must have at least one dot for TLD
+ if (!hostname.includes('.')) {
+ return false;
+ }
+
+ // Must have something before and after the dot
+ const parts = hostname.split('.');
+ if (parts.some((part) => part.length === 0)) {
+ return false;
+ }
+
+ return true;
+ } catch {
+ return false;
+ }
+}