applyStyleProperty<T> function

bool applyStyleProperty<T>(
  1. FluentDocument document,
  2. T value, {
  3. required void modifyLeaf(
    1. Fragment leaf,
    2. T value
    ),
  4. required void setPending(
    1. FluentDocument document,
    2. T value
    ),
  5. String? description,
})

Generic helper for applying a style property to the selection or cursor. When a selection exists, modifyLeaf is applied to each leaf fragment and the cursor moves to the end of the modified range. When collapsed, setPending stores the value for subsequently typed text.

Implementation

bool applyStyleProperty<T>(
  FluentDocument document,
  T value, {
  required void Function(Fragment leaf, T value) modifyLeaf,
  required void Function(FluentDocument document, T value) setPending,
  String? description,
}) {
  document.saveState(description: description ?? 'Change style property');
  final selection = resolveSelectionFromCursor(document);
  if (selection != null) {
    final cursor = document.cursor;
    final result = splitAndApplyToLeaves(
      document,
      selection,
      modifyBatch: (leaves) {
        final res = document.registry.dispatchLeavesStyleMutation(
          document,
          leaves,
          (l) => modifyLeaf(l, value),
        );
        return res;
      },
      modify: (leaf) {
        final res = document.registry.dispatchStyleMutation(
          document,
          leaf,
          (l) => modifyLeaf(l, value),
        );
        if (res != null) return res;

        modifyLeaf(leaf, value);
        return leaf;
      },
    );
    if (result.firstModified != null && result.lastModified != null) {
      cursor.anchorId = result.firstModified!.id;
      cursor.anchorOffset = 0;
      cursor.focusId = result.lastModified!.id;
      cursor.focusOffset = result.lastModified!.text.length;
    } else if (result.lastModified != null) {
      cursor.moveTo(result.lastModified!.id, result.lastModified!.text.length);
    }
    setPending(document, value);
    document.updateContent();
    return true;
  }
  setPending(document, value);
  document.updateContent();
  return true;
}