import 'dart:collection'; import 'chat_markdown.dart'; /// Parsed markdown blocks shared by every markdown view, keyed by the text. /// /// A lazily built transcript disposes rows scrolled out of view, so scrolling /// back would parse the same answer again. Blocks are immutable and depend on /// the text alone, so one parse serves every later view of that text. Bounded /// by entries and by held characters, evicting the least recently used first, /// so a long streamed reply's intermediate texts cannot grow it without limit. class ChatMarkdownCache { ChatMarkdownCache({this.maxEntries = 400, this.maxChars = 1000000}); final int maxEntries; final int maxChars; /// Least recently used first. final LinkedHashMap> _blocks = LinkedHashMap(); int _chars = 0; /// How many texts were actually parsed (cache misses). int parses = 0; List blocksFor(String text) { final held = _blocks.remove(text); if (held != null) return _blocks[text] = held; final blocks = List.unmodifiable(parseMarkdown(text)); parses++; if (text.length > maxChars) return blocks; _blocks[text] = blocks; _chars += text.length; while (_blocks.length > maxEntries || _chars > maxChars) { final oldest = _blocks.keys.first; _blocks.remove(oldest); _chars -= oldest.length; } return blocks; } void clear() { _blocks.clear(); _chars = 0; parses = 0; } } /// The one cache the transcript's markdown views share. final chatMarkdownCache = ChatMarkdownCache();