20bf6202b3
Reuse unchanged transcript rows, the composer bar and the header across streamed deltas, and share parsed markdown by text so rows scrolled back into view are not parsed again. Adds a rebuild/parse harness and a release-web frame-timing probe with a long-transcript fixture.
75 lines
2.4 KiB
Dart
75 lines
2.4 KiB
Dart
import 'package:flutter/widgets.dart';
|
|
|
|
/// Reuses a built widget while the content and inputs it was built from are
|
|
/// unchanged: one per transcript row, or per piece of conversation chrome.
|
|
///
|
|
/// Every streamed delta rebuilds the conversation, and each build makes a new
|
|
/// message widget for every row. Handing Flutter the identical widget instance
|
|
/// for an unchanged row lets it skip that row's whole subtree, so during
|
|
/// streaming only the live turn rebuilds. Inherited changes (theme, platform
|
|
/// style, text scale) still reach the reused subtree through its own
|
|
/// dependencies.
|
|
class ChatRowWidgets {
|
|
final Map<String, ({Object? row, Object? inputs, Widget widget})> _held = {};
|
|
Set<String> _seen = {};
|
|
|
|
/// The widget held for [key] when [row] and [inputs] deep-equal the ones it
|
|
/// was built from, else a fresh [build] that is held instead.
|
|
///
|
|
/// [row] is decoded JSON (maps, lists and scalars); [inputs] are the other
|
|
/// values the row's widget depends on, compared the same way.
|
|
Widget widgetFor(
|
|
String key,
|
|
Object? row,
|
|
Object? inputs,
|
|
Widget Function() build,
|
|
) {
|
|
_seen.add(key);
|
|
final held = _held[key];
|
|
if (held != null &&
|
|
chatJsonEquals(held.row, row) &&
|
|
chatJsonEquals(held.inputs, inputs)) {
|
|
return held.widget;
|
|
}
|
|
final widget = build();
|
|
_held[key] = (row: row, inputs: inputs, widget: widget);
|
|
return widget;
|
|
}
|
|
|
|
/// Drops rows the last build did not ask for. Call once after each build.
|
|
void prune() {
|
|
_held.removeWhere((key, _) => !_seen.contains(key));
|
|
_seen = {};
|
|
}
|
|
|
|
void clear() {
|
|
_held.clear();
|
|
_seen = {};
|
|
}
|
|
}
|
|
|
|
/// Structural equality for decoded JSON. Strings shared between snapshots are
|
|
/// identical, so an unchanged transcript compares in near-constant time per
|
|
/// field.
|
|
bool chatJsonEquals(Object? a, Object? b) {
|
|
if (identical(a, b)) return true;
|
|
if (a is Map && b is Map) {
|
|
if (a.length != b.length) return false;
|
|
for (final entry in a.entries) {
|
|
if (!b.containsKey(entry.key) ||
|
|
!chatJsonEquals(entry.value, b[entry.key])) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
if (a is List && b is List) {
|
|
if (a.length != b.length) return false;
|
|
for (var index = 0; index < a.length; index++) {
|
|
if (!chatJsonEquals(a[index], b[index])) return false;
|
|
}
|
|
return true;
|
|
}
|
|
return a == b;
|
|
}
|