Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: Use node directly in getValidations instead of searching by id #2688

Merged
merged 1 commit into from
Nov 5, 2024
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
71 changes: 22 additions & 49 deletions src/features/validation/ValidationStorePlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import type {
import type { LayoutNode } from 'src/utils/layout/LayoutNode';
import type { IsHiddenOptions, NodesContext, NodesStoreFull } from 'src/utils/layout/NodesContext';
import type { NodeDataPluginSetState } from 'src/utils/layout/plugins/NodeDataPlugin';
import type { NodeData } from 'src/utils/layout/types';
import type { TraversalRestriction } from 'src/utils/layout/useNodeTraversal';

export type ValidationsSelector = (
Expand Down Expand Up @@ -135,35 +134,30 @@ export class ValidationStorePlugin extends NodeDataPlugin<ValidationStorePluginC
if (!node) {
return emptyArray;
}
const nodeData = state.nodeData[node.id];
return getValidations({ state, nodeData, mask: showAll ? 'showAll' : 'visible' });
return getValidations({ state, node, mask: showAll ? 'showAll' : 'visible' });
}),
useVisibleValidationsDeep: (node, mask, stopAtDepth, restriction, severity) =>
store.useMemoSelector((state) => {
if (!node) {
return emptyArray;
}
const nodeData = state.nodeData[node.id];
return getRecursiveValidations({ state, nodeData, mask, severity, stopAtDepth, restriction });
return getRecursiveValidations({ state, node, mask, severity, stopAtDepth, restriction });
}),
useValidationsSelector: () =>
store.useDelayedSelector({
mode: 'simple',
selector:
(node: LayoutNode, mask: NodeVisibility, severity?: ValidationSeverity, includeHidden: boolean = false) =>
(state: NodesContext) => {
const nodeData = state.nodeData[node.id];
return getValidations({ state, nodeData, mask, severity, includeHidden });
},
(state: NodesContext) =>
getValidations({ state, node, mask, severity, includeHidden }),
}) satisfies ValidationsSelector,
useAllValidations: (mask, severity, includeHidden) =>
store.useLaxMemoSelector((state) => {
const out: NodeRefValidation[] = [];
for (const nodeId of Object.keys(state.nodeData)) {
const nodeData = state.nodeData[nodeId];
const validations = getValidations({ state, nodeData, mask, severity, includeHidden });
for (const node of state.nodes?.allNodes() ?? []) {
const validations = getValidations({ state, node, mask, severity, includeHidden });
for (const validation of validations) {
out.push({ ...validation, nodeId });
out.push({ ...validation, nodeId: node.id });
}
}

Expand All @@ -183,12 +177,10 @@ export class ValidationStorePlugin extends NodeDataPlugin<ValidationStorePluginC

const outNodes: string[] = [];
const outValidations: AnyValidation[] = [];
for (const nodeId of Object.keys(state.nodeData)) {
const nodeData = state.nodeData[nodeId];

const validations = getValidations({ state, nodeData, mask, severity, includeHidden });
for (const node of state.nodes?.allNodes() ?? []) {
const validations = getValidations({ state, node, mask, severity, includeHidden });
if (validations.length > 0) {
outNodes.push(nodeId);
outNodes.push(node.id);
outValidations.push(...validations);
}
}
Expand All @@ -203,13 +195,13 @@ export class ValidationStorePlugin extends NodeDataPlugin<ValidationStorePluginC
return false;
}

for (const nodeId of Object.keys(state.nodeData)) {
const nodeData = state.nodeData[nodeId];
for (const node of state.nodes?.allNodes() ?? []) {
const nodeData = state.nodeData[node.id];
if (!nodeData || nodeData.pageKey !== pageKey) {
continue;
}

const validations = getValidations({ state, nodeData, mask: 'visible', severity: 'error' });
const validations = getValidations({ state, node, mask: 'visible', severity: 'error' });
for (const validation of validations) {
if (validation.source === FrontendValidationSource.EmptyField) {
return true;
Expand All @@ -223,33 +215,20 @@ export class ValidationStorePlugin extends NodeDataPlugin<ValidationStorePluginC
}
}

function getNodeFromState(state: NodesContext, nodeId: string): LayoutNode | undefined {
if (state.nodes) {
return state.nodes.findById(new TraversalTask(state, state.nodes, undefined, undefined), nodeId);
}
return undefined;
}

interface GetValidationsProps {
state: NodesContext;
nodeData: NodeData | undefined;
node: LayoutNode;
mask: NodeVisibility;
severity?: ValidationSeverity;
includeHidden?: boolean;
}

function getValidations({
state,
nodeData,
mask,
severity,
includeHidden = false,
}: GetValidationsProps): AnyValidation[] {
function getValidations({ state, node, mask, severity, includeHidden = false }: GetValidationsProps): AnyValidation[] {
const nodeData = state.nodeData[node.id];
if (!nodeData || !('validations' in nodeData) || !('validationVisibility' in nodeData)) {
return emptyArray;
}

const node = getNodeFromState(state, nodeData.layout.id);
if (!includeHidden && (!node || isHidden(state, node, hiddenOptions))) {
return emptyArray;
}
Expand All @@ -273,29 +252,23 @@ interface GetDeepValidationsProps extends GetValidationsProps {
}

function getRecursiveValidations(props: GetDeepValidationsProps): NodeRefValidation[] {
const nodeId = props.nodeData?.layout.id;
const out: NodeRefValidation[] = [];
const depth = props.depth ?? 0;
if (!nodeId) {
return emptyArray;
}

const nodeValidations = getValidations(props);
for (const validation of nodeValidations) {
out.push({ ...validation, nodeId });
out.push({ ...validation, nodeId: props.node.id });
}

if (props.stopAtDepth !== undefined && depth >= props.stopAtDepth) {
return out;
}

const directChildren = props.state.childrenMap[nodeId];
if (directChildren) {
for (const childId of directChildren) {
const childData = props.state.nodeData[childId];
if (childData && childData.rowIndex === props.restriction) {
out.push(...getRecursiveValidations({ ...props, nodeData: childData, depth: depth + 1 }));
}
if (props.state.nodes) {
for (const child of props.node.children(
new TraversalTask(props.state, props.state.nodes, undefined, props.restriction),
)) {
out.push(...getRecursiveValidations({ ...props, node: child, depth: depth + 1 }));
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/utils/layout/LayoutPage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { splitDashedKey } from 'src/utils/splitDashedKey';
import { getBaseComponentId } from 'src/utils/splitDashedKey';
import type { LayoutNode } from 'src/utils/layout/LayoutNode';
import type { LayoutObject } from 'src/utils/layout/LayoutObject';
import type { LayoutPages } from 'src/utils/layout/LayoutPages';
Expand Down Expand Up @@ -84,8 +84,8 @@ export class LayoutPage implements LayoutObject {
return children;
}

public flat(task: TraversalTask): LayoutNode[] {
return [...this.allChildren.values()].filter((n) => task.passes(n));
public flat(task?: TraversalTask): LayoutNode[] {
return task ? [...this.allChildren.values()].filter((n) => task.passes(n)) : [...this.allChildren.values()];
}

public findById(task: TraversalTask, id: string | undefined, traversePages = true): LayoutNode | undefined {
Expand All @@ -97,7 +97,7 @@ export class LayoutPage implements LayoutObject {
return this.allChildren.get(id);
}

const baseId = splitDashedKey(id).baseComponentId;
const baseId = getBaseComponentId(id);
if (this.allChildren.has(baseId)) {
return this.allChildren.get(baseId);
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/layout/LayoutPages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class LayoutPages implements LayoutObject<LayoutPage> {
return this.objects;
}

public allNodes(task: TraversalTask): LayoutNode[] {
public allNodes(task?: TraversalTask): LayoutNode[] {
return Object.values(this.objects).flatMap((layout) => layout.flat(task));
}

Expand Down
18 changes: 18 additions & 0 deletions src/utils/splitDashedKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,21 @@ export function splitDashedKey(componentId: string): SplitKey {
depth: [],
};
}
// If all you want is the baseId, use this instead
// If you see this, feel free to optimize this further ;)
export function getBaseComponentId(componentId: string): string {
const parts = componentId.split('-');

while (parts.length) {
const toConsider = parts.pop();

// Since our form component IDs are usually UUIDs, they will contain hyphens and may even end in '-<number>'.
// We'll assume the application has less than 5-digit repeating group elements (the last leg of UUIDs are always
// longer than 5 digits).
if (!toConsider?.match(/^\d{1,5}$/)) {
return [...parts, toConsider].join('-');
}
}

return componentId;
}
Loading