beginSaveState method

void beginSaveState(
  1. FluentDocument document, {
  2. String description = 'Document change',
  3. bool forceNewAction = false,
})

Called BEFORE a mutation. Captures the old state of all top-level nodes so commitSaveState can compute a minimal delta afterwards.

Implementation

void beginSaveState(
  FluentDocument document, {
  String description = 'Document change',
  bool forceNewAction = false,
}) {
  if (_isRestoringState) return;

  final now = DateTime.now();

  if (!forceNewAction &&
      _pending != null &&
      !_forceNewAction &&
      _currentGroupDescription != null &&
      description == _currentGroupDescription &&
      _lastActionTime != null &&
      now.difference(_lastActionTime!) <= _groupingTimeout) {
    _pending!.description = description;
    _groupingTimer?.cancel();
    _groupingTimer = Timer(_groupingTimeout, _resetGrouping);
    return;
  }

  if (_pending != null) {
    _pending = null;
  }

  final nodes = document.content.nodes;
  final currentIds = <String>{};
  final oldJsonList = <Map<String, dynamic>>[];
  for (final node in nodes) {
    currentIds.add(node.id);
    final cached = _jsonCache[node.id];
    if (cached != null) {
      oldJsonList.add(cached);
    } else {
      final json = _deepCopyJsonMap(node.toJson());
      _jsonCache[node.id] = json;
      oldJsonList.add(json);
    }
  }
  // Evict stale entries for nodes no longer in the document.
  _jsonCache.removeWhere((id, _) => !currentIds.contains(id));
  _pending = _PendingSnapshot(
    description: description,
    timestamp: now,
    oldTopLevelNodes: oldJsonList,
    oldCursor: CursorSnapshot.fromDocument(document),
  );

  _forceNewAction = forceNewAction;
  _currentGroupDescription = description;
  _lastActionTime = now;
  _groupingTimer?.cancel();
  _groupingTimer = Timer(_groupingTimeout, _resetGrouping);
}