Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 18 additions & 5 deletions packages/replay_bloc/lib/src/change_stack.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@ part of 'replay_cubit.dart';
typedef _Predicate<T> = bool Function(T);

class _ChangeStack<T> {
_ChangeStack({required _Predicate<T> shouldReplay, this.limit})
: _shouldReplay = shouldReplay;
_ChangeStack({required _Predicate<T> shouldReplay, int? limit})
: _shouldReplay = shouldReplay,
_limit = limit;

final Queue<_Change<T>> _history = ListQueue();
final Queue<_Change<T>> _redos = ListQueue();
final _Predicate<T> _shouldReplay;

int? limit;
int? _limit;

int? get limit => _limit;

set limit(int? limit) {
_limit = limit;
_trimHistory();
}

bool get canRedo => _redos.any((c) => _shouldReplay(c._newValue));
bool get canUndo => _history.any((c) => _shouldReplay(c._oldValue));
Expand All @@ -20,9 +28,14 @@ class _ChangeStack<T> {

_history.addLast(change);
_redos.clear();
_trimHistory();
}

if (limit != null && _history.length > limit!) {
if (limit! > 0) _history.removeFirst();
void _trimHistory() {
final limit = _limit;
if (limit == null || limit < 0) return;
while (_history.length > limit) {
_history.removeFirst();
}
}

Expand Down
33 changes: 33 additions & 0 deletions packages/replay_bloc/test/replay_cubit_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,39 @@ void main() {
expect(states, const <int>[1, 2, 1]);
});

test('loses history outside of a lowered limit', () async {
final states = <int>[];
final cubit = CounterCubit();
final subscription = cubit.stream.listen(states.add);
cubit
..increment()
..increment()
..increment()
..limit = 1
..undo()
..undo();
await cubit.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 3, 2]);
});

test('trims history to a lowered limit on the next change', () async {
final states = <int>[];
final cubit = CounterCubit();
final subscription = cubit.stream.listen(states.add);
cubit
..increment()
..increment()
..increment()
..limit = 1
..increment()
..undo()
..undo();
await cubit.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 3, 4, 3]);
});

test('reverts to initial state', () async {
final states = <int>[];
final cubit = CounterCubit();
Expand Down