Skip to content
Draft
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ The app includes synthetic example questionnaires.
- Import a Questionnaire or select one from a FHIR Bundle.
- Organize questions and groups using the outline and edit their fields in the inspector.
- Configure conditional questions, coded answers, contained value sets, and quantity units.
- Follow which questions depend on which answers in the flow view, which also marks conditions on missing or later items and items that can never be shown.
- See validation findings while you edit and try the questionnaire in the interactive preview.
- Edit or export the questionnaire as JSON and undo or redo document edits.
- Resume the current draft from the browser's local storage.
Expand Down
15 changes: 15 additions & 0 deletions packages/anvil-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,21 @@ Hosts can subscribe to store changes to implement persistence.
`validateQuestionnaire(input, { validators })` checks structure (element names, cardinality, primitive formats), the Questionnaire invariants, contained resources and value sets, conditions and answer types, and common authoring mistakes.
Each `ValidationIssue` has a `severity`, a stable `code`, a `message`, a FHIRPath-style `path` and, for item issues, the item's `itemPath` and `linkId`.

## Flow

`layoutFlow(document)` lays out a questionnaire's conditional flow for display.
Its `rows` list every item in document order, each followed by its `enableWhen` conditions and then its nested items, with a `depth` for indentation.
Each condition names the linkId it refers to, its operator and a readable answer, and has a `status`: `ok`, `missing` when no item has the linkId, `not-a-question` for a group or display item, `self`, or `later` when the item comes after the condition's own item.
Each item row says how its conditions combine (`behavior`), which conditions refer to it (`dependents`), and whether any answers can enable it (`reachable`).
An item is unreachable when one of its conditions can never hold (or, with `any`, none can), for example because it refers to a missing question, to another unreachable item, to an item inside the item itself, or compares in a way that never matches.
Conditions that refer to each other in a cycle are unreachable unless initial answers enable them, and every item inside an unreachable group is unreachable too.
Conditions that can each hold but contradict each other, such as `q = 1` and `q = 2` with `all`, are not detected.
`edges` connect the row of each referenced item to the row of the condition, and `lane` assigns each edge a column so that edges sharing rows do not overlap.

```ts
const { rows, edges, lanes } = layoutFlow(store.getState().document);
```

## Plugins

`Plugin<V>` describes what a plugin contributes: inspector sections and fields, item templates, item controls, extension labels, validators and preview renderers.
Expand Down
343 changes: 343 additions & 0 deletions packages/anvil-core/src/document/flow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,343 @@
//
// This source file is part of the Anvil open-source project
//
// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md)
//
// SPDX-License-Identifier: MIT
//

import { defined } from "../assert";
import {
allowedEnableWhenAnswerTypes,
isItemType,
isQuestionType,
operatorsForAnswerType,
} from "../fhir/constants";
import type {
EnableWhenOperator,
QuestionnaireEnableWhen,
ValueType,
} from "../fhir/types";
import { formatValue, getChoice, valuesEqual } from "../fhir/values";
import { isObject } from "../json";
import { computeEnabled, initialAnswerMap } from "../preview/logic";
import type { EditorDocument, EditorItem } from "./model";
import { walkItems } from "./tree";

/**
* What a condition refers to: an earlier question (`ok`), no item at all (`missing`),
* a group or display item (`not-a-question`), the item itself (`self`), or an item that
* comes after the item in document order (`later`).
*/
export type FlowConditionStatus =
"ok" | "missing" | "not-a-question" | "self" | "later";

/** One enableWhen condition of an item. */
export interface FlowCondition {
/** Index in the item's `enableWhen`. */
index: number;
/** The linkId the condition refers to; empty when it has none. */
question: string;
operator: EnableWhenOperator | undefined;
/** The answer it compares with, formatted for reading; undefined for `exists` or no answer. */
answer: string | undefined;
/** For `exists`: whether the question must be answered (true) or unanswered (false). */
answered: boolean | undefined;
/** The item the condition refers to (the first one with that linkId). */
sourceUid: string | undefined;
status: FlowConditionStatus;
}

export interface FlowItemRow {
kind: "item";
item: EditorItem;
depth: number;
parentUid: string | null;
/** How the item's conditions combine. */
behavior: "all" | "any";
/** False when the layout finds that no answers can enable the item. */
reachable: boolean;
/** The conditions of other items (and the item itself) that refer to this item. */
dependents: Array<{ uid: string; index: number }>;
}

export interface FlowConditionRow {
kind: "condition";
/** The item that has the condition. */
uid: string;
depth: number;
condition: FlowCondition;
}

/** The rows of the flow in document order: each item, then its conditions, then its children. */
export type FlowRow = FlowItemRow | FlowConditionRow;

/** A condition drawn from the row of the item it refers to to its own row. */
export interface FlowEdge {
/** Row of the item the condition refers to. */
from: number;
/** Row of the condition. */
to: number;
/**
* Column of the edge, from 0 next to the rows outwards. Edges that share rows have
* different lanes, unless they leave the same item in the same direction.
*/
lane: number;
sourceUid: string;
/** The item that has the condition. */
targetUid: string;
/** Index in the target's `enableWhen`. */
index: number;
status: FlowConditionStatus;
}

export interface FlowLayout {
rows: FlowRow[];
edges: FlowEdge[];
/** The number of lanes the edges use. */
lanes: number;
}

const OPERATORS: readonly string[] = [
"exists",
"=",
"!=",
">",
"<",
">=",
"<=",
];

/** An item's conditions with their indexes. Imported JSON: the entries are not guaranteed to be objects. */
const rawConditions = (
item: EditorItem,
): Array<[number, QuestionnaireEnableWhen]> =>
(Array.isArray(item.data.enableWhen) ? item.data.enableWhen : []).flatMap(
(ew, index): Array<[number, QuestionnaireEnableWhen]> =>
isObject<QuestionnaireEnableWhen>(ew) ? [[index, ew]] : [],
);

/** The answer a condition compares with, preferring the display of the source's matching option. */
const answerText = (
condition: QuestionnaireEnableWhen,
source: EditorItem | undefined,
): string | undefined => {
const answer = getChoice(condition, "answer");
if (!answer || condition.operator === "exists") return undefined;
const options =
Array.isArray(source?.data.answerOption) ? source.data.answerOption : [];
const option = options.find((o) => {
const value = getChoice(o, "value");
return (
value?.type === answer.type &&
valuesEqual(answer.type, value.value, answer.value)
);
});
if (answer.type === "Coding") {
if (!isObject(answer.value)) return undefined;
const fromOption = getChoice(option, "value")?.value;
const text = (value: unknown, key: string) =>
isObject(value) && typeof value[key] === "string" ?
value[key]
: undefined;
return formatValue("Coding", {
code: text(answer.value, "code"),
display: text(answer.value, "display") ?? text(fromOption, "display"),
});
}
const text = formatValue(answer.type, answer.value);
return answer.type === "String" ? `“${text}”` : text;
};

const statusOf = (
item: EditorItem,
source: EditorItem | undefined,
order: ReadonlyMap<string, number>,
): FlowConditionStatus => {
if (!source) return "missing";
if (!isQuestionType(source.data.type)) return "not-a-question";
if (source === item) return "self";
return (order.get(source.uid) ?? 0) > (order.get(item.uid) ?? 0) ?
"later"
: "ok";
};

/**
* Whether one condition can hold on its own, given which items can be enabled, by the
* rules of `evaluateCondition`: an unanswered question only satisfies `exists` with
* `false`, a comparison with an answer type the question cannot have only satisfies
* `!=`, and an ordering operator needs an ordered answer type. The answers different
* conditions need are not compared with each other.
*/
const canHold = (
condition: QuestionnaireEnableWhen,
sources: readonly EditorItem[],
reachable: ReadonlySet<string>,
): boolean => {
const { operator } = condition;
if (operator === "exists" && condition.answerBoolean === false) return true;
// Answers are kept by linkId, so any enabled question with the linkId can answer.
const source = sources.find(
(item) =>
isItemType(item.data.type) &&
isQuestionType(item.data.type) &&
reachable.has(item.uid),
);
if (!source || !isItemType(source.data.type)) return false;
if (operator === "exists") {
// Imported JSON: any other value, such as the text "true", never matches.
const expected: unknown = condition.answerBoolean;
return expected === undefined || expected === true;
}
const answer = getChoice(condition, "answer");
if (!answer || !OPERATORS.includes(operator)) return false;
const type = answer.type as ValueType;
if (!allowedEnableWhenAnswerTypes(source.data.type).includes(type))
return operator === "!=";
return operatorsForAnswerType(type).includes(operator);
};

/** Assign lanes so that edges sharing rows do not overlap: shorter edges get the inner lanes. */
const assignLanes = (
edges: ReadonlyArray<Omit<FlowEdge, "lane">>,
): FlowEdge[] => {
const spans = edges.map((edge, i) => ({
i,
edge,
low: Math.min(edge.from, edge.to),
high: Math.max(edge.from, edge.to),
down: edge.to > edge.from,
}));
spans.sort(
(a, b) => a.high - a.low - (b.high - b.low) || a.low - b.low || a.i - b.i,
);
const lanes: Array<typeof spans> = [];
const out: FlowEdge[] = [];
for (const span of spans) {
const conflicts = (other: (typeof spans)[number]) =>
span.low <= other.high &&
other.low <= span.high &&
// Edges that leave one item in the same direction share a trunk.
!(other.edge.from === span.edge.from && other.down === span.down);
let lane = lanes.findIndex((list) => !list.some(conflicts));
if (lane < 0) lane = lanes.push([]) - 1;
defined(lanes[lane], "the lane").push(span);
out[span.i] = { ...span.edge, lane };
}
return out;
};

/**
* Lay out a questionnaire's flow: its items in document order with their enableWhen
* conditions, and an edge from each item a condition refers to to that condition.
* Also works out which items can never be enabled: items whose conditions refer to a
* missing question, a group or display item, an item that can never be enabled, each
* other in a cycle, or an item inside themselves, or compare in a way that never
* matches. Conditions that each can hold but contradict each other, such as `q = 1`
* and `q = 2` with `all`, are not detected.
*/
export const layoutFlow = (doc: EditorDocument): FlowLayout => {
const order = new Map<string, number>();
const byLinkId = new Map<string, EditorItem[]>();
const parents = new Map<string, EditorItem | null>();
const all: EditorItem[] = [];
walkItems(doc.items, (item, parent) => {
order.set(item.uid, all.length);
all.push(item);
parents.set(item.uid, parent);
const { linkId } = item.data;
if (typeof linkId === "string" && linkId)
byLinkId.set(linkId, [...(byLinkId.get(linkId) ?? []), item]);
});
const sourcesOf = (condition: QuestionnaireEnableWhen) =>
(typeof condition.question === "string" ?
byLinkId.get(condition.question)
: undefined) ?? [];
// Like validation, a condition refers to the first item with the linkId.
const sourceOf = (condition: QuestionnaireEnableWhen) =>
sourcesOf(condition)[0];

// The items that can be enabled: the least set that contains the items enabled with
// the initial answers and is closed under "the parent can be enabled and the
// conditions can hold". Cycles without initial answers stay out of it.
const reachable = computeEnabled(doc.items, initialAnswerMap(doc.items));
for (let changed = true; changed;) {
changed = false;
for (const item of all) {
if (reachable.has(item.uid)) continue;
const parent = parents.get(item.uid);
if (parent && !reachable.has(parent.uid)) continue;
const results = rawConditions(item).map(([, c]) =>
canHold(c, sourcesOf(c), reachable),
);
const enabled =
results.length === 0 ||
(item.data.enableBehavior === "any" ?
results.some(Boolean)
: results.every(Boolean));
if (enabled) {
reachable.add(item.uid);
changed = true;
}
}
}

const rows: FlowRow[] = [];
const itemRows = new Map<string, FlowItemRow>();
const rowOf = new Map<string, number>();
const pending: Array<Omit<FlowEdge, "lane" | "from">> = [];
walkItems(doc.items, (item, parent, path) => {
const depth = path.length - 1;
const row: FlowItemRow = {
kind: "item",
item,
depth,
parentUid: parent?.uid ?? null,
behavior: item.data.enableBehavior === "any" ? "any" : "all",
reachable: reachable.has(item.uid),
dependents: [],
};
rowOf.set(item.uid, rows.length);
itemRows.set(item.uid, row);
rows.push(row);
for (const [index, ew] of rawConditions(item)) {
const source = sourceOf(ew);
const condition: FlowCondition = {
index,
question: typeof ew.question === "string" ? ew.question : "",
operator: OPERATORS.includes(ew.operator) ? ew.operator : undefined,
answer: answerText(ew, source),
answered:
ew.operator === "exists" ? ew.answerBoolean !== false : undefined,
sourceUid: source?.uid,
status: statusOf(item, source, order),
};
if (source)
pending.push({
to: rows.length,
sourceUid: source.uid,
targetUid: item.uid,
index,
status: condition.status,
});
rows.push({
kind: "condition",
uid: item.uid,
depth: depth + 1,
condition,
});
}
return undefined;
});

for (const edge of pending)
itemRows.get(edge.sourceUid)?.dependents.push({
uid: edge.targetUid,
index: edge.index,
});
const edges = assignLanes(
pending.map((edge) => ({ ...edge, from: rowOf.get(edge.sourceUid) ?? 0 })),
);
const lanes = edges.reduce((n, edge) => Math.max(n, edge.lane + 1), 0);
return { rows, edges, lanes };
};
1 change: 1 addition & 0 deletions packages/anvil-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export * from "./document/io";
export * from "./document/codes";
export * from "./document/valueSets";
export * from "./document/diff";
export * from "./document/flow";

// Validation
export * from "./validation";
Expand Down
Loading
Loading