copyItemsetAnswer method

void copyItemsetAnswer(
  1. QuestionDef question,
  2. TreeElement targetNode,
  3. AnswerValue? data
)

Deprecated <copy> itemsets: replaces the copies under targetNode with the subtrees of the selected choices (reusing existing copies of still-selected values). Port of copyItemsetAnswer.

Implementation

void copyItemsetAnswer(
  QuestionDef question,
  TreeElement targetNode,
  AnswerValue? data,
) {
  final itemset = question.dynamicChoices!;
  final targetRef = targetNode.ref;
  final destRef = itemset.destRef!.contextualize(targetRef)!;
  final selections = switch (data) {
    MultipleItemsValue(:final selections) => selections,
    SelectOneValue(:final selection) => [selection],
    // JavaRosa fails with a NullPointerException.
    _ => throw ArgumentError.value(data, 'data', 'not a selection'),
  };
  final selectedValues = itemset.valueRef != null
      ? [for (final s in selections) s.choice!.value]
      : const <String>[];
  final existingValues = <String, TreeElement>{};
  for (final existing in evaluationContext.expandReference(destRef)!) {
    final node = mainInstance.resolveReference(existing)!;
    if (itemset.valueRef != null) {
      final value = itemset.relativeValue!.evalReadable(
        mainInstance,
        EvaluationContext.withContext(evaluationContext, node.ref),
      );
      if (selectedValues.contains(value)) existingValues[value] = node;
    }
    targetNode.removeChild(node);
  }
  for (final (i, selection) in selections.indexed) {
    final choice = selection.choice!;
    final cached = itemset.valueRef != null
        ? existingValues[choice.value]
        : null;
    if (cached != null) {
      cached.multiplicity = i;
      targetNode.addChild(cached);
    } else {
      final template = mainInstance.getTemplate(destRef)!;
      final newNode = mainInstance.copyNode(template, destRef);
      _populateTemplate(newNode, choice.copyNode!);
    }
  }
  _dag.copyItemsetAnswer(
    mainInstance,
    evaluationContext,
    destRef,
    targetNode,
  );
}