| 50 | } |
| 51 | |
| 52 | export function stream(text: string, live: boolean): Block[] { |
| 53 | if (!live) return [{ raw: text, src: text, mode: "full" }] satisfies Block[] |
| 54 | if (refs(text)) return [{ raw: text, src: heal(text), mode: "live" }] satisfies Block[] |
| 55 | const tokens = marked.lexer(text) |
| 56 | const tail = tokens.findLastIndex((token) => token.type !== "space") |
| 57 | if (tail < 0) return [{ raw: text, src: heal(text), mode: "live" }] satisfies Block[] |
| 58 | const last = tokens[tail] |
| 59 | if (!last) return [{ raw: text, src: heal(text), mode: "live" }] satisfies Block[] |
| 60 | |
| 61 | const result: Block[] = [] |
| 62 | for (let index = 0; index < tail; index++) { |
| 63 | const token = tokens[index] |
| 64 | if (!token || token.type === "space") continue |
| 65 | let raw = token.raw |
| 66 | while (tokens[index + 1]?.type === "space" && index + 1 < tail) raw += tokens[++index]!.raw |
| 67 | if (token.type === "code") { |
| 68 | const code = token as Tokens.Code |
| 69 | result.push({ raw, src: code.text, mode: "code", language: language(code.lang), complete: true }) |
| 70 | continue |
| 71 | } |
| 72 | result.push({ raw, src: raw, mode: "full" }) |
| 73 | } |
| 74 | |
| 75 | const raw = tokens |
| 76 | .slice(tail) |
| 77 | .map((token) => token.raw) |
| 78 | .join("") |
| 79 | if (last.type !== "code") return [...result, { raw, src: heal(raw), mode: "live" }] |
| 80 | |
| 81 | const code = last as Tokens.Code |
| 82 | if (!open(code.raw)) |
| 83 | return [...result, { raw, src: code.text, mode: "code", language: language(code.lang), complete: true }] |
| 84 | return [...result, { raw, src: openCode(code.raw), mode: "code", language: language(code.lang) }] |
| 85 | } |
| 86 | |
| 87 | export function canReusePendingBlock(current: Pick<Block, "mode" | "raw"> | undefined, next: Block) { |
| 88 | if (!current || current.mode !== next.mode) return false |