Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions lib/form/hooks/useProtocolForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
type ComponentType,
type FormField,
} from '@codaco/protocol-validation';
import { type ReactNode } from 'react';
import { type ReactNode, useMemo } from 'react';
import { useSelector } from 'react-redux';
import {
getValidationContext,
Expand All @@ -11,11 +11,11 @@ import {
type Subject,
} from '~/lib/interviewer/selectors/forms';
import Field from '../components/Field/Field';
import FieldNamespace from '../components/FieldNamespace';
import {
type FieldValue,
type ValidationPropsCatalogue,
} from '../components/Field/types';
import FieldNamespace from '../components/FieldNamespace';
import BooleanField from '../components/fields/Boolean';
import CheckboxGroupField from '../components/fields/CheckboxGroup';
import DatePickerField from '../components/fields/DatePicker';
Expand Down Expand Up @@ -65,17 +65,25 @@ export default function useProtocolForm({
initialValues,
subject,
namespace,
currentEntityId,
}: {
fields: FormField[];
autoFocus?: boolean;
initialValues?: Record<string, FieldValue>;
subject?: Subject;
namespace?: string;
currentEntityId?: string;
}) {
const validationContext = useSelector(
const baseValidationContext = useSelector(
getValidationContext,
) as ValidationContext | null;

const validationContext = useMemo<ValidationContext | null>(() => {
if (!baseValidationContext) return null;
if (currentEntityId === undefined) return baseValidationContext;
return { ...baseValidationContext, currentEntityId };
}, [baseValidationContext, currentEntityId]);

const fieldsMetadata = useSelector((state) =>
subject
? selectFieldMetadataWithSubject(state, subject, fields)
Expand Down
1 change: 1 addition & 0 deletions lib/form/store/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export type ValidationContext = {
stageSubject: StageSubject;
codebook: Codebook;
network: NcNetwork;
currentEntityId?: string;
};

// ═══════════════════════════════════════════════════════════════
Expand Down
66 changes: 66 additions & 0 deletions lib/form/validation/functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,72 @@ describe('Validation Functions', () => {
.safeParse('test');
}).toThrow('Attribute must be specified for unique validation');
});

it("should accept the currently-edited entity's own value", () => {
const mockNetwork = {
nodes: [
{
_uid: 'node1',
type: 'person',
[entityAttributesProperty]: { name: 'John' },
},
{
_uid: 'node2',
type: 'person',
[entityAttributesProperty]: { name: 'Jane' },
},
],
edges: [],
ego: {
_uid: 'ego',
[entityAttributesProperty]: {},
},
} as NcNetwork;

const validator = validations.unique(
'name',
createMockContext({
network: mockNetwork,
currentEntityId: 'node1',
}),
)({});

const result = validator.safeParse('John');
expect(result.success).toBe(true);
});

it("should still reject other entities' values when editing", () => {
const mockNetwork = {
nodes: [
{
_uid: 'node1',
type: 'person',
[entityAttributesProperty]: { name: 'John' },
},
{
_uid: 'node2',
type: 'person',
[entityAttributesProperty]: { name: 'Jane' },
},
],
edges: [],
ego: {
_uid: 'ego',
[entityAttributesProperty]: {},
},
} as NcNetwork;

const validator = validations.unique(
'name',
createMockContext({
network: mockNetwork,
currentEntityId: 'node1',
}),
)({});

const result = validator.safeParse('Jane');
expect(result.success).toBe(false);
});
});

describe('differentFrom', () => {
Expand Down
7 changes: 5 additions & 2 deletions lib/form/validation/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ const unique: ValidationFunction<string> = (attribute, context) => () => {
context,
'Validation context must be provided when using unique validation',
);
const { stageSubject, network } = context;
const { stageSubject, network, currentEntityId } = context;

const hint = 'Must be unique.';

Expand All @@ -455,11 +455,14 @@ const unique: ValidationFunction<string> = (attribute, context) => () => {
'Attribute must be specified for unique validation',
);

// Collect other values of the same type.
// Collect other values of the same type, excluding the entity
// currently being edited (if any) so its own value isn't treated
// as a duplicate.
const existingValues = collectNetworkValues(
network,
stageSubject,
attribute,
currentEntityId,
);

if (existingValues.some((v) => isMatchingValue(value, v))) {
Expand Down
11 changes: 7 additions & 4 deletions lib/form/validation/utils/collectNetworkValues.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import { type StageSubject } from '@codaco/protocol-validation';
import {
entityAttributesProperty,
entityPrimaryKeyProperty,
type NcNetwork,
} from '@codaco/shared-consts';

export default function collectNetworkValues(
network: NcNetwork,
subject: Extract<StageSubject, { entity: 'node' | 'edge' }>,
attribute: string,
excludeEntityId?: string,
) {
if (subject.entity === 'node') {
return network.nodes.map((n) => n[entityAttributesProperty][attribute]);
}
const entities =
subject.entity === 'node' ? network.nodes : network.edges;

return network.edges.map((e) => e[entityAttributesProperty][attribute]);
return entities
.filter((e) => e[entityPrimaryKeyProperty] !== excludeEntityId)
.map((e) => e[entityAttributesProperty][attribute]);
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ const NodeForm = (props: NodeFormProps) => {
fields: form.fields,
autoFocus: true,
initialValues,
currentEntityId: selectedNode?.[entityPrimaryKeyProperty],
});

// Handle form submission
Expand Down
1 change: 1 addition & 0 deletions lib/interviewer/Interfaces/SlidesForm/SlidesForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ const SlideContentInner = forwardRef<SlideHandle, SlideContentProps>(
autoFocus: false,
initialValues,
subject,
currentEntityId: id,
});

const handleSubmit: FormSubmitHandler = (values) => {
Expand Down
Loading