oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

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