Open History to see the last commit
1import { displayedPlanMarkdown, proposedPlanTitle } from "@t3tools/shared/proposedPlanText";
2import { msg } from "gt-react";
3
4import { m, type MessageResolver } from "./i18n/messages";
5
6export function buildCollapsedProposedPlanPreviewMarkdown(
7 planMarkdown: string,
8 options?: {
9 maxLines?: number;
10 },
11 resolve: MessageResolver = m,
12): string {
13 const maxLines = options?.maxLines ?? 8;
14 const { markdown, separatorLine } = displayedPlanMarkdown(planMarkdown);
15 const lines = markdown.split(/\r?\n/);
16 const previewLines: string[] = [];
17 let visibleLineCount = 0;
18 let hasMoreContent = false;
19 let openFence: { marker: string; indent: string } | null = null;
20
21 for (const [index, line] of lines.entries()) {
22 const isVisibleLine = index !== separatorLine && line.trim().length > 0;
23 if (isVisibleLine && visibleLineCount >= maxLines) {
24 hasMoreContent = true;
25 break;
26 }
27 previewLines.push(line);
28 if (isVisibleLine) {
29 visibleLineCount += 1;
30 }
31 const match = /^( {0,3})(?:(`{3,})[^`]*|(~{3,}).*)$/s.exec(line);
32 const fence = match?.[2] ?? match?.[3];
33 if (match === null || fence === undefined) {
34 continue;
35 }
36 if (openFence === null) {
37 openFence = { marker: fence, indent: match[1] ?? "" };
38 } else if (
39 fence[0] === openFence.marker[0] &&
40 fence.length >= openFence.marker.length &&
41 line.trim() === fence
42 ) {
43 openFence = null;
44 }
45 }
46
47 while (previewLines.length > 0 && previewLines.at(-1)?.trim().length === 0) {
48 previewLines.pop();
49 }
50
51 if (previewLines.length === 0) {
52 return proposedPlanTitle(planMarkdown) ?? resolve(msg("Plan preview unavailable."));
53 }
54
55 if (openFence !== null) {
56 previewLines.push(openFence.indent + openFence.marker);
57 }
58
59 if (hasMoreContent) {
60 previewLines.push("", "...");
61 }
62
63 return previewLines.join("\n");
64}
65
66function sanitizePlanFileSegment(input: string): string {
67 const sanitized = input
68 .toLowerCase()
69 .replace(/[`'".,!?()[\]{}]+/g, "")
70 .replace(/[^a-z0-9]+/g, "-")
71 .replace(/^-+|-+$/g, "");
72 return sanitized.length > 0 ? sanitized : "plan";
73}
74
75export const PLAN_IMPLEMENTATION_PROMPT_PREFIX = "PLEASE IMPLEMENT THIS PLAN:\n";
76
77export function buildProposedPlanMarkdownFilename(planMarkdown: string): string {
78 const title = proposedPlanTitle(planMarkdown);
79 return `${sanitizePlanFileSegment(title ?? "plan")}.md`;
80}
81
82export function normalizePlanMarkdownForExport(planMarkdown: string): string {
83 return `${planMarkdown.trimEnd()}\n`;
84}
85
86export function downloadPlanAsTextFile(filename: string, contents: string): void {
87 const blob = new Blob([contents], { type: "text/markdown;charset=utf-8" });
88 const url = URL.createObjectURL(blob);
89 const anchor = document.createElement("a");
90 anchor.href = url;
91 anchor.download = filename;
92 anchor.click();
93 window.setTimeout(() => {
94 URL.revokeObjectURL(url);
95 }, 0);
96}