oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
2// native/apple/Sources/EquipoKit/Markdown/MarkdownRenderCache.swift). Base's changes are
3// marked "Base:"; keep the rest in step with Equipo's.
4import Foundation
5
6/// A bounded cache of message revisions, shared across transcript view lifetimes.
7/// The source and draft flag are the revision: completion must settle draft rules
8/// even when it does not append any bytes.
9@MainActor final class MarkdownRenderCache {
10 struct Request: Hashable {
11 let messageID: String
12 let text: String
13 let draft: Bool
14 }
15 struct Result {
16 let tree: [ChatMarkdownNode]
17 let complete: Bool
18 }
19 static let shared = MarkdownRenderCache()
20 private var entries: [Request: [ChatMarkdownNode]] = [:]
21 private var order: [Request] = []
22 private let parse: (String, Bool) -> [ChatMarkdownNode]
23 init(parse: @escaping (String, Bool) -> [ChatMarkdownNode] = { ChatMarkdown.parse($0, draft: $1) }) {
24 self.parse = parse
25 }
26 func initial(_ request: Request) -> Result {
27 if let tree = entries[request] { return Result(tree: tree, complete: true) }
28 if request.text.utf8.count <= 16_384 {
29 let tree = parse(request.text, request.draft)
30 store(tree, for: request)
31 return Result(tree: tree, complete: true)
32 }
33 // Large inputs never start at zero height. During streaming retain the
34 // previous revision; the first revision shows all its plain text.
35 let previous = order.last { $0.messageID == request.messageID }
36 let held = previous.flatMap { entries[$0] }
37 let fallback = held.flatMap { $0.isEmpty ? nil : $0 } ?? [ChatMarkdownNode(kind: "plain", text: request.text)]
38 return Result(tree: fallback, complete: false)
39 }
40 func store(_ tree: [ChatMarkdownNode], for request: Request) {
41 entries[request] = tree
42 order.removeAll { $0 == request }
43 order.append(request)
44 while order.count > 256 { entries[order.removeFirst()] = nil }
45 }
46}
47