@each1024/pi-mini-mode 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +214 -0
- package/README.zh-CN.md +210 -0
- package/extensions/footer-status.ts +1612 -0
- package/lib/agent-view.ts +518 -0
- package/lib/file-links.ts +80 -0
- package/lib/footer-tidy.ts +75 -0
- package/lib/input-enhancements.ts +622 -0
- package/lib/minimal-markdown.ts +181 -0
- package/lib/minimal-theme.ts +48 -0
- package/lib/settings-web.ts +119 -0
- package/lib/settings.html +209 -0
- package/lib/sticky-tool.ts +100 -0
- package/lib/title-plain.ts +57 -0
- package/lib/transcript-adapter.ts +578 -0
- package/package.json +61 -0
- package/themes/README.md +5 -0
- package/themes/cc-dark.json +91 -0
- package/themes/cc-light.json +91 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { Marked, Markdown, visibleWidth, type DefaultTextStyle, type MarkdownTheme } from "@earendil-works/pi-tui";
|
|
2
|
+
import { render } from "grok-mermaid";
|
|
3
|
+
|
|
4
|
+
const parser = new Marked();
|
|
5
|
+
|
|
6
|
+
/** A fence's info string is "language [options]"; only the first token names a language. */
|
|
7
|
+
const languageToken = (lang?: string) => lang?.trim().split(/\s+/)[0].toLowerCase() ?? "";
|
|
8
|
+
|
|
9
|
+
/** Theme emphasis remains visible when the terminal's CJK font lacks bold/italic faces. */
|
|
10
|
+
const REGISTERED_LANGUAGES = new Set([
|
|
11
|
+
"bash", "sh", "shell", "zsh", "fish", "powershell", "javascript", "js", "typescript", "ts", "jsx", "tsx",
|
|
12
|
+
"python", "ruby", "rust", "go", "java", "kotlin", "swift", "c", "cpp", "csharp", "php", "sql", "html", "css",
|
|
13
|
+
"scss", "sass", "less", "yaml", "yml", "json", "json5", "jsonc", "toml", "xml", "markdown", "md", "lua", "perl",
|
|
14
|
+
"r", "scala", "clojure", "elixir", "erlang", "haskell", "ocaml", "vim", "graphql", "protobuf", "hcl", "dockerfile",
|
|
15
|
+
]);
|
|
16
|
+
const ANSI_FOREGROUND = /\x1b\[(?:38;(?:2;\d+;\d+;\d+|5;\d+)|3[0-9]|9[0-7])m/g;
|
|
17
|
+
|
|
18
|
+
export function minimalMarkdownTheme(base: MarkdownTheme, codeBackground = ""): MarkdownTheme {
|
|
19
|
+
// Inline prose arrives with its default foreground already applied. Remove
|
|
20
|
+
// those foreground codes before wrapping, otherwise they override emphasis.
|
|
21
|
+
const emphasis = (text: string) => base.heading(text.replace(/\x1b\[(?:38;(?:2;\d+;\d+;\d+|5;\d+)|3[0-9]|9[0-7])m/g, ""));
|
|
22
|
+
const highlightCode = base.highlightCode;
|
|
23
|
+
const neutralCode = (text: string) => base.codeBlock(text).replace(ANSI_FOREGROUND, "");
|
|
24
|
+
return {
|
|
25
|
+
...base,
|
|
26
|
+
bold: text => emphasis(base.bold(text)),
|
|
27
|
+
italic: text => emphasis(base.italic(text)),
|
|
28
|
+
codeBlock: neutralCode,
|
|
29
|
+
// A blank, background-painted row replaces the old language/border text.
|
|
30
|
+
codeBlockBorder: () => codeBackground ? `${codeBackground} ` : "",
|
|
31
|
+
codeBlockIndent: codeBackground ? `${codeBackground} ` : " ",
|
|
32
|
+
// ponytail: reuse installed grammars; only registered languages are sent to it.
|
|
33
|
+
...(highlightCode && { highlightCode: (code: string, lang?: string) => {
|
|
34
|
+
const language = languageToken(lang);
|
|
35
|
+
if (!REGISTERED_LANGUAGES.has(language) || /^(?:text|txt|plaintext)$/.test(language)) return code.split("\n").map(neutralCode);
|
|
36
|
+
return highlightCode(code, /^json[5c]$/.test(language) ? "javascript" : language);
|
|
37
|
+
} }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Render Markdown with A's code-only background, after native wrapping has settled. */
|
|
42
|
+
export function renderMinimalMarkdown(source: string, width: number, base: MarkdownTheme, codeBackground: string,
|
|
43
|
+
defaultTextStyle?: DefaultTextStyle, transform?: (source: string, available: number) => string): string[] {
|
|
44
|
+
const rows = new Markdown(source, 0, 0, minimalMarkdownTheme(base, codeBackground), defaultTextStyle,
|
|
45
|
+
transform ? { transform } : undefined).render(width);
|
|
46
|
+
if (!codeBackground) return rows;
|
|
47
|
+
return rows.map(row => row.startsWith(codeBackground)
|
|
48
|
+
? `${row}${" ".repeat(Math.max(0, width - visibleWidth(row)))}\x1b[49m`
|
|
49
|
+
: row);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type MarkdownNode = {
|
|
53
|
+
type?: string;
|
|
54
|
+
raw?: string;
|
|
55
|
+
text?: string;
|
|
56
|
+
tokens?: MarkdownNode[];
|
|
57
|
+
items?: MarkdownNode[];
|
|
58
|
+
header?: MarkdownNode[] | boolean;
|
|
59
|
+
rows?: MarkdownNode[][];
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** Tolerate model-generated emphasis in prose, preserving code, escapes and URLs. */
|
|
63
|
+
export function normalizeProseMarkdown(source: string): string {
|
|
64
|
+
if (!/[*_~]/.test(source)) return source;
|
|
65
|
+
const repairInline = (raw: string, mask: string): string => {
|
|
66
|
+
// Mask parsed constructs so delimiters in code, links or existing emphasis
|
|
67
|
+
// cannot be mistaken for an opening/closing pair. Their contents can still
|
|
68
|
+
// sit between a pair of otherwise unparsed prose delimiters.
|
|
69
|
+
const pattern = /(?<![\\*_~])(\*\*|__|~~|\*|_)(?![*_~])([^\n]*?)\1(?![*_~])/g;
|
|
70
|
+
const edits: { start: number; end: number; text: string }[] = [];
|
|
71
|
+
for (const match of mask.matchAll(pattern)) {
|
|
72
|
+
const start = match.index!;
|
|
73
|
+
const marker = match[1];
|
|
74
|
+
if (marker.includes("_") && /[\p{L}\p{N}_]/u.test(raw[start - 1] ?? "")) continue;
|
|
75
|
+
const body = raw.slice(start + marker.length, start + match[0].length - marker.length);
|
|
76
|
+
if (marker.length === 1 && /^\s/.test(body)) continue; // e.g. prose multiplication: a * b * c
|
|
77
|
+
const trimmed = body.trim();
|
|
78
|
+
if (!trimmed || trimmed.endsWith("\\")) continue;
|
|
79
|
+
const punctuation = /[,。!?;:、]+$/.exec(trimmed)?.[0] ?? "";
|
|
80
|
+
const content = trimmed.slice(0, trimmed.length - punctuation.length);
|
|
81
|
+
if (!content) continue;
|
|
82
|
+
const delimiter = marker.replace(/_/g, "*");
|
|
83
|
+
edits.push({ start, end: start + match[0].length,
|
|
84
|
+
text: `${body.match(/^\s*/)?.[0] ?? ""}${delimiter}${content}${delimiter}${punctuation}${body.match(/\s*$/)?.[0] ?? ""}` });
|
|
85
|
+
}
|
|
86
|
+
for (const edit of edits.reverse()) raw = raw.slice(0, edit.start) + edit.text + raw.slice(edit.end);
|
|
87
|
+
return raw;
|
|
88
|
+
};
|
|
89
|
+
const rewrite = (node: MarkdownNode): string => {
|
|
90
|
+
const raw = node.raw ?? node.text ?? "";
|
|
91
|
+
const children = node.tokens ?? node.items ?? (Array.isArray(node.header) ? [...node.header, ...(node.rows ?? []).flat()] : undefined);
|
|
92
|
+
if (!children) return raw;
|
|
93
|
+
const inline = ["paragraph", "heading", "text", "strong", "em", "del", "link"].includes(node.type ?? "") || !node.type;
|
|
94
|
+
let cursor = 0;
|
|
95
|
+
let result = "";
|
|
96
|
+
let mask = "";
|
|
97
|
+
for (const child of children) {
|
|
98
|
+
const original = child.raw ?? child.text;
|
|
99
|
+
if (!original) continue;
|
|
100
|
+
const replacement = rewrite(child);
|
|
101
|
+
const start = raw.indexOf(original, cursor);
|
|
102
|
+
if (start < 0) {
|
|
103
|
+
// Blockquote/list prefixes interrupt multiline raw tokens. Map each
|
|
104
|
+
// line separately, retaining those prefixes and the original layout.
|
|
105
|
+
const before = original.split("\n");
|
|
106
|
+
const after = replacement.split("\n");
|
|
107
|
+
if (inline || before.length !== after.length) return raw;
|
|
108
|
+
for (let i = 0; i < before.length; i++) {
|
|
109
|
+
if (!before[i]) continue;
|
|
110
|
+
const position = raw.indexOf(before[i], cursor);
|
|
111
|
+
if (position < 0) return raw;
|
|
112
|
+
result += raw.slice(cursor, position) + after[i];
|
|
113
|
+
cursor = position + before[i].length;
|
|
114
|
+
}
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
result += raw.slice(cursor, start) + replacement;
|
|
118
|
+
mask += raw.slice(cursor, start).replace(/[^\n]/g, "\0")
|
|
119
|
+
+ (child.type === "text" && !child.tokens ? replacement : replacement.replace(/[^\n]/g, "\0"));
|
|
120
|
+
cursor = start + original.length;
|
|
121
|
+
}
|
|
122
|
+
result += raw.slice(cursor);
|
|
123
|
+
mask += raw.slice(cursor).replace(/[^\n]/g, "\0");
|
|
124
|
+
return inline ? repairInline(result, mask) : result;
|
|
125
|
+
};
|
|
126
|
+
return parser.lexer(source).map(rewrite).join("");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Lexer tokens that are Markdown block structure regardless of how the body looks. */
|
|
130
|
+
const BLOCK_TOKENS = new Set(["code", "heading", "blockquote", "list", "table", "hr"]);
|
|
131
|
+
/** A hard break alone may be a shell continuation, not Markdown prose. */
|
|
132
|
+
const INLINE_TOKENS = new Set(["strong", "em", "del", "codespan", "link", "image"]);
|
|
133
|
+
/** Source that opens like code stays literal even when it also parses as inline Markdown. */
|
|
134
|
+
const LOOKS_LIKE_SOURCE = /^(?:const|let|var|function|class|import|export|SELECT|INSERT|UPDATE|DELETE)\b/m;
|
|
135
|
+
/** Preserve the existing tolerance for unfinished or malformed inline markup. */
|
|
136
|
+
const SLOPPY_EMPHASIS = /(?:\*\*|__|~~|`[^`\n]+`|\[[^\]\n]+\]\([^\n)]+\))/;
|
|
137
|
+
|
|
138
|
+
/** A body that is only a closed or streaming fence must not be sliced mid-block. */
|
|
139
|
+
export function isFencedMarkdown(source: string): boolean {
|
|
140
|
+
const tokens = parser.lexer(source.trim()).filter(token => token.type !== "space");
|
|
141
|
+
return tokens.length === 1 && tokens[0].type === "code";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Markdown is rendered only for semantic prose bodies; structured tool output stays literal. */
|
|
145
|
+
export function isMarkdownProse(source: string): boolean {
|
|
146
|
+
const text = source.trim();
|
|
147
|
+
if (!text) return false;
|
|
148
|
+
if (/^(?:\{[\s\S]*\}|\[[\s\S]*\])$/.test(text)) {
|
|
149
|
+
try { JSON.parse(text); return false; } catch { /* a Markdown list may start with [ */ }
|
|
150
|
+
}
|
|
151
|
+
// The lexer decides what the body actually is: block structure first, then
|
|
152
|
+
// inline structure. Raw HTML alone is not prose, so `html` tokens are ignored.
|
|
153
|
+
let block = false;
|
|
154
|
+
let inline = false;
|
|
155
|
+
parser.walkTokens(parser.lexer(text), (token) => {
|
|
156
|
+
if (BLOCK_TOKENS.has(token.type)) block = true;
|
|
157
|
+
else if (INLINE_TOKENS.has(token.type)) inline = true;
|
|
158
|
+
});
|
|
159
|
+
if (block) return true;
|
|
160
|
+
if (LOOKS_LIKE_SOURCE.test(text)) return false;
|
|
161
|
+
return inline || SLOPPY_EMPHASIS.test(text);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A malformed diagram must not break the render, so its own source is the fallback. */
|
|
165
|
+
function diagramArt(source: string) {
|
|
166
|
+
try { return render(source); } catch { return undefined; }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Keep incomplete, unsupported and over-wide diagrams readable as source. */
|
|
170
|
+
export function diagramMarkdown(source: string, width: number): string {
|
|
171
|
+
return parser.lexer(normalizeProseMarkdown(source)).map((token) => {
|
|
172
|
+
if (token.type !== "code" || languageToken(token.lang) !== "mermaid") return token.raw;
|
|
173
|
+
const art = diagramArt(token.text);
|
|
174
|
+
if (!art || art.width > width || art.warnings.length) return token.raw;
|
|
175
|
+
return art.plain.map((line) => {
|
|
176
|
+
const content = line || "\u00a0";
|
|
177
|
+
const fence = "`".repeat(Math.max(0, ...Array.from(content.matchAll(/`+/g), (match) => match[0].length)) + 1);
|
|
178
|
+
return `${fence} ${content} ${fence}`;
|
|
179
|
+
}).join(" \n") + "\n\n";
|
|
180
|
+
}).join("");
|
|
181
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
type RGB = [number, number, number];
|
|
4
|
+
function ansiColor(ansi: string): RGB | undefined {
|
|
5
|
+
const rgb = ansi.match(/(?:38|48);2;(\d+);(\d+);(\d+)/);
|
|
6
|
+
if (rgb) return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
|
|
7
|
+
const indexed = ansi.match(/(?:38|48);5;(\d+)/);
|
|
8
|
+
if (!indexed) return;
|
|
9
|
+
const n = Number(indexed[1]);
|
|
10
|
+
if (n >= 232) return [8 + (n - 232) * 10, 8 + (n - 232) * 10, 8 + (n - 232) * 10];
|
|
11
|
+
if (n >= 16) {
|
|
12
|
+
const levels = [0, 95, 135, 175, 215, 255];
|
|
13
|
+
return [levels[Math.floor((n - 16) / 36)], levels[Math.floor((n - 16) / 6) % 6], levels[(n - 16) % 6]];
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Expanded heading: full-width selectedBg, keeping inner fg after resets.
|
|
18
|
+
* theme.bg only wraps the ends; older themes without getBgAnsi lose fill after \x1b[0m. */
|
|
19
|
+
export function paintExpandedHeading(theme: ExtensionContext["ui"]["theme"], line: string): string {
|
|
20
|
+
const background = theme.getBgAnsi?.("selectedBg") ?? "";
|
|
21
|
+
return background
|
|
22
|
+
? background + line.replace(/\x1b\[(?:0|49)?m/g, reset => reset + background) + "\x1b[49m"
|
|
23
|
+
: theme.bg("selectedBg", line);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** User uses the theme's soft surface directly; process keeps its secondary tint.
|
|
27
|
+
* A row inside an expanded heading (selected) keeps the band instead: the
|
|
28
|
+
* blended tint and the user surface both collapse into it. */
|
|
29
|
+
export function minimalSurface(theme: ExtensionContext["ui"]["theme"], text: string, user = false, selected = false): string {
|
|
30
|
+
if (selected) return paintExpandedHeading(theme, text);
|
|
31
|
+
const background = theme.getBgAnsi?.("userMessageBg") ?? "";
|
|
32
|
+
if (user) return background
|
|
33
|
+
? background + text.replace(/\x1b\[(?:0|49)?m/g, (reset) => reset + background) + "\x1b[49m"
|
|
34
|
+
: theme.bg("userMessageBg", text);
|
|
35
|
+
const base = ansiColor(background);
|
|
36
|
+
const accent = ansiColor(theme.fg("accent", "")) ?? ansiColor(theme.fg("success", ""));
|
|
37
|
+
if (!base || !accent) return theme.bg("userMessageBg", text);
|
|
38
|
+
const weight = 0.07;
|
|
39
|
+
const rgb = base.map((value, i) => Math.round(value * (1 - weight) + accent[i] * weight));
|
|
40
|
+
let prefix = `\x1b[48;2;${rgb.join(";")}m`;
|
|
41
|
+
if (theme.getColorMode?.() === "256color") {
|
|
42
|
+
const levels = [0, 95, 135, 175, 215, 255];
|
|
43
|
+
const indices = rgb.map((value) => levels.reduce((best, level, i) => Math.abs(level - value) < Math.abs(levels[best] - value) ? i : best, 0));
|
|
44
|
+
prefix = `\x1b[48;5;${16 + indices[0] * 36 + indices[1] * 6 + indices[2]}m`;
|
|
45
|
+
}
|
|
46
|
+
// Restore the surface after Markdown's inline reset sequences.
|
|
47
|
+
return prefix + text.replace(/\x1b\[(?:0|49)?m/g, (reset) => reset + prefix) + "\x1b[49m";
|
|
48
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
|
|
5
|
+
export interface SettingsWebOptions {
|
|
6
|
+
idleTimeoutMs?: number;
|
|
7
|
+
onClose?: () => void;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const DEFAULT_IDLE_TIMEOUT_MS = 300_000;
|
|
11
|
+
const MIN_IDLE_TIMEOUT_MS = 1_000;
|
|
12
|
+
const MAX_IDLE_TIMEOUT_MS = 3_600_000;
|
|
13
|
+
|
|
14
|
+
/** Env override is validated to 1s..1h; a test override wins and is trusted. */
|
|
15
|
+
function configuredIdleTimeout(override: number | undefined): number {
|
|
16
|
+
if (override !== undefined) {
|
|
17
|
+
if (!Number.isFinite(override) || override <= 0) throw new TypeError("Invalid idle timeout");
|
|
18
|
+
return override;
|
|
19
|
+
}
|
|
20
|
+
const raw = process.env.PI_MINI_MODE_SETTINGS_IDLE_MS;
|
|
21
|
+
const value = Number(raw);
|
|
22
|
+
return raw !== undefined && Number.isInteger(value) && value >= MIN_IDLE_TIMEOUT_MS && value <= MAX_IDLE_TIMEOUT_MS
|
|
23
|
+
? value : DEFAULT_IDLE_TIMEOUT_MS;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** On-demand, loopback-only settings bridge; no polling or third-party runtime. */
|
|
27
|
+
export async function startSettingsWeb(snapshot: () => unknown, update: (value: unknown) => Promise<void>, options: SettingsWebOptions = {}) {
|
|
28
|
+
const token = randomBytes(24).toString("hex");
|
|
29
|
+
const html = await readFile(new URL("./settings.html", import.meta.url));
|
|
30
|
+
const idleTimeoutMs = configuredIdleTimeout(options.idleTimeoutMs);
|
|
31
|
+
let origin = "";
|
|
32
|
+
let queue = Promise.resolve();
|
|
33
|
+
let idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
34
|
+
let idleDeadline = Date.now() + idleTimeoutMs;
|
|
35
|
+
let closed = false;
|
|
36
|
+
let activeRequests = 0;
|
|
37
|
+
const close = () => {
|
|
38
|
+
if (closed) return;
|
|
39
|
+
closed = true;
|
|
40
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
41
|
+
idleTimer = undefined;
|
|
42
|
+
server.close();
|
|
43
|
+
server.closeAllConnections();
|
|
44
|
+
options.onClose?.();
|
|
45
|
+
};
|
|
46
|
+
const armIdle = () => {
|
|
47
|
+
if (closed || activeRequests > 0) return;
|
|
48
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
49
|
+
idleTimer = setTimeout(close, Math.max(0, idleDeadline - Date.now()));
|
|
50
|
+
idleTimer.unref();
|
|
51
|
+
};
|
|
52
|
+
/** Successful authorized traffic renews; failed or anonymous requests keep the old deadline. */
|
|
53
|
+
const touch = () => {
|
|
54
|
+
idleDeadline = Date.now() + idleTimeoutMs;
|
|
55
|
+
armIdle();
|
|
56
|
+
};
|
|
57
|
+
const server = createServer(async (req, res) => {
|
|
58
|
+
res.setHeader("Cache-Control", "no-store");
|
|
59
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
60
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
61
|
+
res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'");
|
|
62
|
+
if (req.headers.host !== origin.slice(7) || (req.headers.origin && req.headers.origin !== origin)) {
|
|
63
|
+
res.writeHead(403).end(); return;
|
|
64
|
+
}
|
|
65
|
+
if (req.url === "/" && req.method === "GET") {
|
|
66
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return;
|
|
67
|
+
}
|
|
68
|
+
if (req.url !== "/settings" || req.headers.authorization !== `Bearer ${token}`) {
|
|
69
|
+
res.writeHead(403).end(); return;
|
|
70
|
+
}
|
|
71
|
+
// Suspend the idle lease while handling so a slow save cannot be cut off;
|
|
72
|
+
// only a successful response re-arms it.
|
|
73
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
74
|
+
idleTimer = undefined;
|
|
75
|
+
let renewed = false;
|
|
76
|
+
activeRequests++;
|
|
77
|
+
try {
|
|
78
|
+
if (req.method === "PUT") {
|
|
79
|
+
if (req.headers["content-type"] !== "application/json") { res.writeHead(415).end(); return; }
|
|
80
|
+
let body = "";
|
|
81
|
+
for await (const chunk of req) {
|
|
82
|
+
body += chunk;
|
|
83
|
+
if (Buffer.byteLength(body) > 16384) { res.writeHead(413).end(); return; }
|
|
84
|
+
}
|
|
85
|
+
const value: unknown = JSON.parse(body);
|
|
86
|
+
const saving = queue.then(() => update(value));
|
|
87
|
+
queue = saving.catch(() => {});
|
|
88
|
+
await saving;
|
|
89
|
+
} else if (req.method !== "GET") { res.writeHead(405).end(); return; }
|
|
90
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
91
|
+
res.end(JSON.stringify(snapshot()));
|
|
92
|
+
renewed = true;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
res.writeHead(error instanceof TypeError || error instanceof SyntaxError ? 400 : 500);
|
|
95
|
+
res.end("无法保存设置,请检查配置文件权限后重试。");
|
|
96
|
+
} finally {
|
|
97
|
+
activeRequests--;
|
|
98
|
+
if (renewed) touch();
|
|
99
|
+
else armIdle();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
server.requestTimeout = 10000;
|
|
103
|
+
server.headersTimeout = 10000;
|
|
104
|
+
await new Promise<void>((resolve, reject) => {
|
|
105
|
+
server.once("error", reject);
|
|
106
|
+
server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); });
|
|
107
|
+
});
|
|
108
|
+
const address = server.address();
|
|
109
|
+
if (!address || typeof address === "string") throw new Error("无法启动设置服务");
|
|
110
|
+
origin = `http://127.0.0.1:${address.port}`;
|
|
111
|
+
server.unref();
|
|
112
|
+
touch();
|
|
113
|
+
return {
|
|
114
|
+
url: `${origin}/#${token}`,
|
|
115
|
+
get closed() { return closed; },
|
|
116
|
+
touch,
|
|
117
|
+
close,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4
|
+
<title>Pi Mini Mode 设置</title>
|
|
5
|
+
<style>
|
|
6
|
+
:root{color-scheme:light dark;--background:light-dark(#f4f3ef,#141614);--foreground:light-dark(#1f241f,#eceee8);--surface:light-dark(#fffcf7,#1d211d);--muted:light-dark(#667066,#a8b0a4);--border:light-dark(#e2ddd4,#3a4038);--accent:light-dark(#2f5a3e,#b7d4b0);--destructive:light-dark(#a52c26,#ffafa5);--ring:var(--accent);--text-sm:.875rem;--text-base:1rem;--text-lg:2.75rem;--radius:8px}
|
|
7
|
+
*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font:var(--text-base)/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:1080px;margin:auto;padding:40px 24px 72px}header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}h1{font:italic 400 var(--text-lg)/1.05 "Didot","Bodoni 72","Iowan Old Style","Songti SC","STSong",serif;letter-spacing:.04em;margin:0}h2{font-size:var(--text-sm);font-weight:600;margin:0 0 12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}.tagline{margin:8px 0 0;color:var(--muted);font-size:var(--text-sm)}nav{display:flex;gap:8px;align-items:center}.hint{margin:12px 0 0;color:var(--accent);font-weight:600}section{margin:28px 0}button{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid var(--ring);outline-offset:3px}#preview{padding:16px 20px;background:var(--surface);border:1px dashed var(--accent);border-radius:var(--radius);font:var(--text-sm)/1.8 ui-monospace,monospace;display:flex;align-items:center;gap:12px;overflow-x:auto;min-height:72px;white-space:nowrap}#preview button{flex:none;font:inherit;padding:4px 2px;border-color:transparent;cursor:grab;white-space:nowrap}#preview button:hover{border-color:var(--border)}#preview button.over{border-left:2px solid var(--accent)}#preview #preview-context{flex:1;display:flex;align-items:center;gap:8px;min-width:180px}.progress{flex:1;overflow:hidden;text-align:left;color:var(--accent);min-width:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:4px 16px}label{display:flex;align-items:center;gap:10px;padding:10px 0;cursor:pointer}input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}.dragging{opacity:.45}#status{min-height:24px;color:var(--accent)}#status.error{color:var(--destructive)}#retry{margin-left:12px}[hidden]{display:none!important}nav button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.features{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}.feature{display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px}.feature-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.feature-head h3{margin:0;font-size:var(--text-base);font-weight:600}.feature-body{margin:10px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.65}.feature-points{margin:10px 0 0;padding-left:1.15em;font-size:var(--text-sm);line-height:1.7}.feature-points li{margin:2px 0}.feature-points li::marker{color:var(--accent)}.feature-hint{margin:auto 0 0;padding-top:12px;color:var(--muted);font:var(--text-sm)/1.6 ui-monospace,monospace;overflow-wrap:anywhere}.feature-hint::before{content:'› ';color:var(--accent)}.switch{display:flex;align-items:center;gap:8px;padding:0;font-size:var(--text-sm);color:var(--muted)}.notice{display:flex;gap:16px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;margin:20px 0 0;padding:14px 16px;background:var(--surface);border:1px solid var(--accent);border-left-width:4px;border-radius:var(--radius)}.notice strong{font-size:var(--text-sm)}.notice p{margin:6px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.6;max-width:640px}.notice code{display:block;margin:0 0 8px;padding:8px 10px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius);font:var(--text-sm)/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-width:520px;color:var(--foreground)}#preview{margin-top:12px}@media(max-width:450px){h1{font-size:2rem}main{padding:24px 16px}}
|
|
8
|
+
</style>
|
|
9
|
+
<main>
|
|
10
|
+
<header>
|
|
11
|
+
<div><h1 id="title"></h1><p class="tagline" id="tagline"></p></div>
|
|
12
|
+
<nav>
|
|
13
|
+
<button type="button" id="lang-zh" aria-pressed="false">中文</button>
|
|
14
|
+
<button type="button" id="lang-en" aria-pressed="false">EN</button>
|
|
15
|
+
<button type="button" id="reset" disabled></button>
|
|
16
|
+
</nav>
|
|
17
|
+
</header>
|
|
18
|
+
<div class="notice" id="notice" hidden>
|
|
19
|
+
<div><strong id="noticeTitle"></strong><p id="noticeBody"></p></div>
|
|
20
|
+
<div><code id="noticePrompt"></code><button type="button" id="copyPrompt"></button></div>
|
|
21
|
+
</div>
|
|
22
|
+
<div role="status" aria-live="polite"><span id="status"></span><button id="retry" hidden></button></div>
|
|
23
|
+
<section><h2 id="featuresHeading"></h2><div class="features" id="features"></div></section>
|
|
24
|
+
<section><h2 id="fieldsHeading"></h2><p class="hint" id="dragHint"></p><div id="preview" role="group" tabindex="0"></div><div class="grid" id="fields"></div></section>
|
|
25
|
+
<section><h2 id="optionsHeading"></h2><div class="grid" id="options"></div></section>
|
|
26
|
+
</main>
|
|
27
|
+
<script>
|
|
28
|
+
const $=id=>document.getElementById(id),token=location.hash.slice(1);
|
|
29
|
+
history.replaceState(null,'',location.pathname);
|
|
30
|
+
const I18N={
|
|
31
|
+
title:{zh:'Pi Mini Mode',en:'Pi Mini Mode'},
|
|
32
|
+
documentTitle:{zh:'Pi Mini Mode 设置',en:'Pi Mini Mode Settings'},
|
|
33
|
+
tagline:{zh:'极简状态栏配置',en:'Minimal status bar setup'},
|
|
34
|
+
dragHint:{zh:'拖拽预览中的字段可调整顺序,松手自动保存',en:'Drag items in the preview to reorder · Auto-saves on drop'},
|
|
35
|
+
featuresHeading:{zh:'功能说明',en:'Features'},
|
|
36
|
+
fieldsHeading:{zh:'状态栏字段与预览',en:'Status bar items & preview'},
|
|
37
|
+
optionsHeading:{zh:'状态栏样式',en:'Status bar style'},
|
|
38
|
+
on:{zh:'开启',en:'On'},off:{zh:'关闭',en:'Off'},
|
|
39
|
+
featureList:{
|
|
40
|
+
zh:[
|
|
41
|
+
{id:'status',title:'状态栏指标',body:'一行看清会话状态,随终端宽度自动取舍,不换行。',points:['模型与思考等级,会话与缓存 Token、缓存命中率、费用估算','上下文用量进度条与百分比','生成速度 tok/s,从第一个输出 token 起算,不含等待首字'],hint:'勾选需要的字段,拖拽预览中的条目即可排序。'},
|
|
42
|
+
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'把对话收成结论:思考、工具与技能汇成一棵按时间排序的可折叠过程树。',points:['长用户消息默认保留前四行,点击折叠控件展开全文','子代理行可展开活动记录与最终输出','Ctrl+O 展开或收起完整过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
|
|
43
|
+
{id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['光标移入图片路径即可预览,全屏编辑器也支持悬停','图片路径收纳为 [image1] 标签,提交时保留原图','空白后输入 / 就地搜索技能,并在光标处插入','点击图片标签或消息中的文件路径,用系统默认应用打开'],hint:'Ctrl+V 粘贴图片(Windows/WSL 使用 Alt+V)'},
|
|
44
|
+
{id:'themes',title:'明暗主题',body:'内置 cc-dark 与 cc-light 两套主题,Markdown、代码高亮、表格与 Mermaid 图表一并适配明暗。',points:['用户消息使用主题的用户背景色,与正文清晰区分','不支持、不完整或过宽的图表保留源文本'],hint:'/pi-mini-mode-setup 重新选择主题与全局全屏模式'}
|
|
45
|
+
],
|
|
46
|
+
en:[
|
|
47
|
+
{id:'status',title:'Status bar metrics',body:'The whole session state on one line, trimmed to fit narrow terminals instead of wrapping.',points:['Model and thinking level, session and cache tokens, cache hit rate, cost estimate','Context usage bar with percentage','Speed in tok/s, measured from the first output token, excluding time to first token'],hint:'Enable the items you need, then drag entries in the preview to reorder.'},
|
|
48
|
+
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'Minimal transcript',body:'Turns the conversation into conclusions: thinking, tools and skills collapse into one chronological, foldable tree.',points:['Long user messages keep four lines; click the fold control to expand','Subagent rows expand to activity and final output','Ctrl+O expands or collapses the full process tree; new questions start collapsed','Final Markdown streams plainly; failures and interrupts are marked'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
|
|
49
|
+
{id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'Input enhancements',body:'Makes images, skills and file paths usable right where you type.',points:['Preview an image as soon as the cursor enters its path; hovering works in fullscreen','Image paths collapse to [image1] labels while keeping the original path on submit','Type / after a space to search skills and insert one at the cursor','Click image labels or file paths in messages to open them in the default app'],hint:'Ctrl+V pastes images (Windows/WSL: Alt+V)'},
|
|
50
|
+
{id:'themes',title:'Light and dark themes',body:'Built-in cc-dark and cc-light adapt Markdown, code highlighting, tables and Mermaid diagrams to the color scheme.',points:['User messages use the theme user background to stand apart from the body','Unsupported, incomplete or overly wide diagrams keep their source text'],hint:'/pi-mini-mode-setup to pick a theme and global fullscreen mode again'}
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
reset:{zh:'恢复默认',en:'Reset defaults'},
|
|
54
|
+
retry:{zh:'重试',en:'Retry'},
|
|
55
|
+
confirmReset:{zh:'恢复默认排序与显示设置?',en:'Reset layout and visibility to defaults?'},
|
|
56
|
+
connecting:{zh:'正在同步…',en:'Connecting…'},
|
|
57
|
+
connected:{zh:'已同步',en:'In sync'},
|
|
58
|
+
unsaved:{zh:'未保存修改',en:'Unsaved changes'},
|
|
59
|
+
saving:{zh:'正在保存…',en:'Saving…'},
|
|
60
|
+
saved:{zh:'已保存',en:'Saved'},
|
|
61
|
+
saveFailed:{zh:'保存失败',en:'Failed to save'},
|
|
62
|
+
reconnect:{zh:'连接已断开,请从终端重新打开',en:'Disconnected. Please reopen from the terminal.'},
|
|
63
|
+
noticeTitle:{zh:'极简输出需要全屏渲染器',en:'Minimal transcript needs the fullscreen renderer'},
|
|
64
|
+
noticeBody:{zh:'极简输出已保存,但当前 Pi 运行在普通 TUI 模式,暂不生效。复制下面的提示词发给 Pi,让它帮你把 TUI 模式改为 fullscreen;重启 Pi 后生效(/reload 不会切换渲染器)。',en:'Minimal transcript is saved but inactive: Pi is running in regular TUI mode. Copy the prompt below into Pi to set TUI mode to fullscreen; it takes effect after restarting Pi (/reload does not switch the renderer).'},
|
|
65
|
+
noticePrompt:{zh:'把 Pi 全局设置中的 tuiMode 改为 fullscreen',en:'Set tuiMode to fullscreen in Pi global settings'},
|
|
66
|
+
copyPrompt:{zh:'复制提示词',en:'Copy prompt'},
|
|
67
|
+
copied:{zh:'已复制',en:'Copied'},
|
|
68
|
+
copyFailed:{zh:'复制失败,请手动选中',en:'Copy failed — select manually'},
|
|
69
|
+
emptyPreview:{zh:'(未启用任何字段)',en:'(No items enabled)'},
|
|
70
|
+
fields:{
|
|
71
|
+
'project-branch':{zh:'项目与分支',en:'Project & Branch'},
|
|
72
|
+
model:{zh:'模型名称',en:'Model'},
|
|
73
|
+
thinking:{zh:'思考等级',en:'Thinking Level'},
|
|
74
|
+
branch:{zh:'仅分支',en:'Branch Only'},
|
|
75
|
+
'session-tokens':{zh:'会话 Token',en:'Session Tokens'},
|
|
76
|
+
'cache-tokens':{zh:'缓存 Token',en:'Cache Tokens'},
|
|
77
|
+
ch:{zh:'缓存命中率',en:'Cache Hit Rate'},
|
|
78
|
+
cost:{zh:'累计费用',en:'Cost'},
|
|
79
|
+
mcp:{zh:'MCP 服务数',en:'MCP Count'},
|
|
80
|
+
context:{zh:'上下文进度条',en:'Context Bar'},
|
|
81
|
+
'context-percent':{zh:'上下文百分比',en:'Context %'},
|
|
82
|
+
speed:{zh:'生成速度',en:'Speed'},
|
|
83
|
+
'context-dots':{zh:'点阵进度条',en:'Dot-matrix bar'},
|
|
84
|
+
'speed-unit':{zh:'速度附带单位',en:'Speed unit (tok/s)'},
|
|
85
|
+
minimal:{zh:'极简对话输出',en:'Minimal transcript'},
|
|
86
|
+
'input-enhancements':{zh:'输入体验增强',en:'Input enhancements'}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const FIELD_KEY={minimal:'pi-mini-mode-minimal-show','input-enhancements':'pi-mini-mode-input-enhancements','context-dots':'pi-mini-mode-context-dots-show','speed-unit':'pi-mini-mode-speed-unit-show'};
|
|
90
|
+
let lang=localStorage.piMiniModeLang||(navigator.language.startsWith('zh')?'zh':'en');
|
|
91
|
+
let data,state,order,dragged,saving=false,dirty=false,timer,copyTimer;
|
|
92
|
+
const key=id=>'pi-mini-mode-'+id+'-show';
|
|
93
|
+
const t=(id,fallback='')=>(I18N[id]?.[lang]??fallback);
|
|
94
|
+
const fieldLabel=id=>I18N.fields[id]?.[lang]||id;
|
|
95
|
+
const examples={'project-branch':'pi-mini-mode(main)',model:'deepseek-v4-flash',thinking:'high',branch:'main','session-tokens':'Total 45K','cache-tokens':'Cached 25K',ch:'CH 40.0%',cost:'$0.012',mcp:'◇ MCP 3',context:'500/1.0M','context-percent':'1%',speed:'120 tok/s'};
|
|
96
|
+
function status(text,error=false){$('status').textContent=text;$('status').className=error?'error':''}
|
|
97
|
+
function applyLang(){
|
|
98
|
+
document.documentElement.lang=lang==='zh'?'zh-CN':'en';
|
|
99
|
+
document.title=t('documentTitle');
|
|
100
|
+
for(const id of ['title','tagline','featuresHeading','fieldsHeading','optionsHeading','dragHint']) $(id).textContent=t(id);
|
|
101
|
+
$('reset').textContent=t('reset');$('retry').textContent=t('retry');
|
|
102
|
+
$('lang-zh').setAttribute('aria-pressed',String(lang==='zh'));
|
|
103
|
+
$('lang-en').setAttribute('aria-pressed',String(lang==='en'));
|
|
104
|
+
$('preview').setAttribute('aria-label',t('dragHint'));
|
|
105
|
+
}
|
|
106
|
+
async function request(method,body){
|
|
107
|
+
const response=await fetch('/settings',{method,headers:{Authorization:'Bearer '+token,...(body?{'Content-Type':'application/json'}:{})},body:body?JSON.stringify(body):undefined});
|
|
108
|
+
if(!response.ok)throw Error(await response.text()||t('saveFailed'));
|
|
109
|
+
return response.json();
|
|
110
|
+
}
|
|
111
|
+
function preview(){
|
|
112
|
+
const panel=$('preview'),scroll=panel.scrollLeft;
|
|
113
|
+
panel.replaceChildren();
|
|
114
|
+
const visible=order.filter(id=>state[key(id)]);
|
|
115
|
+
const values={...examples,speed:state['pi-mini-mode-speed-unit-show']?'120 tok/s':'120'};
|
|
116
|
+
for(const id of visible){
|
|
117
|
+
const button=document.createElement('button');
|
|
118
|
+
button.id='preview-'+id;button.type='button';button.textContent=values[id];button.draggable=true;
|
|
119
|
+
if(id==='context'){const bar=document.createElement('span');bar.className='progress';bar.setAttribute('aria-hidden','true');bar.textContent=state['pi-mini-mode-context-dots-show']?'⣿'+'⣀'.repeat(300):'█'+'░'.repeat(300);button.append(bar)}
|
|
120
|
+
button.setAttribute('aria-label',fieldLabel(id)+' · '+t('dragHint'));
|
|
121
|
+
button.ondragstart=event=>{dragged=id;event.dataTransfer.setData('text/plain',id);event.dataTransfer.effectAllowed='move';button.classList.add('dragging')};
|
|
122
|
+
button.ondragend=()=>{dragged=undefined;button.classList.remove('dragging');document.querySelectorAll('.over').forEach(el=>el.classList.remove('over'))};
|
|
123
|
+
button.ondragover=event=>{if(dragged){event.preventDefault();button.classList.add('over')}};
|
|
124
|
+
button.ondragleave=()=>button.classList.remove('over');
|
|
125
|
+
button.ondrop=event=>{event.preventDefault();const source=dragged;dragged=undefined;if(source){move(order.indexOf(source),order.indexOf(id));$('preview-'+source)?.focus()}};
|
|
126
|
+
button.onkeydown=event=>{if(event.key!=='ArrowLeft'&&event.key!=='ArrowRight')return;event.preventDefault();const target=visible[visible.indexOf(id)+(event.key==='ArrowLeft'?-1:1)];if(target){move(order.indexOf(id),order.indexOf(target));$('preview-'+id)?.focus()}};
|
|
127
|
+
panel.append(button);
|
|
128
|
+
}
|
|
129
|
+
if(!visible.length)panel.textContent=t('emptyPreview');
|
|
130
|
+
panel.scrollLeft=scroll;
|
|
131
|
+
}
|
|
132
|
+
function change(){dirty=true;state.footerOrder=[...order];preview();renderNotice();status(t('unsaved'));clearTimeout(timer);timer=setTimeout(save,250)}
|
|
133
|
+
async function save(){
|
|
134
|
+
if(saving)return;saving=true;$('retry').hidden=true;
|
|
135
|
+
try{while(dirty){dirty=false;const body=structuredClone(state);status(t('saving'));await request('PUT',body)}status(t('saved'))}
|
|
136
|
+
catch(error){dirty=true;status(t('saveFailed')+':'+error.message,true);$('retry').hidden=false}
|
|
137
|
+
finally{saving=false}
|
|
138
|
+
}
|
|
139
|
+
function box(settingId,onToggle){
|
|
140
|
+
const input=document.createElement('input');
|
|
141
|
+
input.type='checkbox';input.checked=!!state[settingId];input.id=settingId;
|
|
142
|
+
input.onchange=()=>{state[settingId]=input.checked;onToggle?.(input.checked)};
|
|
143
|
+
return input;
|
|
144
|
+
}
|
|
145
|
+
function feature(item){
|
|
146
|
+
const card=document.createElement('article');card.className='feature';
|
|
147
|
+
const head=document.createElement('div');head.className='feature-head';
|
|
148
|
+
const title=document.createElement('h3');title.textContent=item.title;head.append(title);
|
|
149
|
+
if(item.setting){
|
|
150
|
+
const label=document.createElement('label');label.className='switch';label.htmlFor=item.setting;
|
|
151
|
+
const text=document.createElement('span');text.textContent=state[item.setting]?t('on'):t('off');
|
|
152
|
+
label.append(box(item.setting,checked=>{text.textContent=checked?t('on'):t('off');change()}),text);
|
|
153
|
+
head.append(label);
|
|
154
|
+
}
|
|
155
|
+
const body=document.createElement('p');body.className='feature-body';body.textContent=item.body;
|
|
156
|
+
const points=document.createElement('ul');points.className='feature-points';
|
|
157
|
+
points.append(...item.points.map(point=>{const li=document.createElement('li');li.textContent=point;return li}));
|
|
158
|
+
const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=item.hint;
|
|
159
|
+
card.append(head,body,points,hint);
|
|
160
|
+
return card;
|
|
161
|
+
}
|
|
162
|
+
function checkbox(id,settingId){
|
|
163
|
+
const label=document.createElement('label'),input=box(settingId,()=>{
|
|
164
|
+
if(state[settingId]&&(id==='project-branch'||id==='branch')){const other=key(id==='branch'?'project-branch':'branch');state[other]=false;const peer=$(other);if(peer)peer.checked=false}
|
|
165
|
+
change();
|
|
166
|
+
});
|
|
167
|
+
label.append(input,document.createTextNode(fieldLabel(id)));
|
|
168
|
+
return label;
|
|
169
|
+
}
|
|
170
|
+
function move(from,to){if(from===to||from<0||to<0||to>=order.length)return;const [id]=order.splice(from,1);order.splice(to,0,id);preview();change()}
|
|
171
|
+
function render(){
|
|
172
|
+
applyLang();
|
|
173
|
+
renderNotice();
|
|
174
|
+
$('fields').replaceChildren(...order.map(id=>checkbox(id,key(id))));
|
|
175
|
+
$('features').replaceChildren(...t('featureList').map(feature));
|
|
176
|
+
$('options').replaceChildren(...['context-dots','speed-unit'].map(id=>checkbox(id,FIELD_KEY[id])));
|
|
177
|
+
preview();
|
|
178
|
+
}
|
|
179
|
+
function renderNotice(){
|
|
180
|
+
// Minimal output needs the fullscreen renderer; only a known regular mode warrants the prompt.
|
|
181
|
+
const show=!!data&&data.tuiMode==='regular'&&!!state['pi-mini-mode-minimal-show'];
|
|
182
|
+
$('notice').hidden=!show;
|
|
183
|
+
if(!show)return;
|
|
184
|
+
$('noticeTitle').textContent=t('noticeTitle');
|
|
185
|
+
$('noticeBody').textContent=t('noticeBody');
|
|
186
|
+
$('noticePrompt').textContent=t('noticePrompt');
|
|
187
|
+
$('copyPrompt').textContent=t('copyPrompt');
|
|
188
|
+
}
|
|
189
|
+
$('copyPrompt').onclick=async()=>{
|
|
190
|
+
const button=$('copyPrompt');
|
|
191
|
+
try{await navigator.clipboard.writeText(t('noticePrompt'));button.textContent=t('copied')}
|
|
192
|
+
catch{
|
|
193
|
+
const range=document.createRange();range.selectNodeContents($('noticePrompt'));
|
|
194
|
+
const selection=getSelection();selection?.removeAllRanges();selection?.addRange(range);
|
|
195
|
+
button.textContent=t('copyFailed');
|
|
196
|
+
}
|
|
197
|
+
clearTimeout(copyTimer);
|
|
198
|
+
copyTimer=setTimeout(()=>button.textContent=t('copyPrompt'),1600);
|
|
199
|
+
};
|
|
200
|
+
function setLang(next){lang=next;localStorage.piMiniModeLang=lang;render()}
|
|
201
|
+
$('lang-zh').onclick=()=>setLang('zh');
|
|
202
|
+
$('lang-en').onclick=()=>setLang('en');
|
|
203
|
+
$('retry').onclick=save;
|
|
204
|
+
$('reset').onclick=()=>{if(!confirm(t('confirmReset')))return;state={...data.defaults};order=[...data.order];render();change()};
|
|
205
|
+
window.addEventListener('beforeunload',event=>{if(dirty||saving){event.preventDefault();event.returnValue=''}});
|
|
206
|
+
applyLang();status(t('connecting'));
|
|
207
|
+
request('GET').then(value=>{data=value;state={...data.settings};order=[...(state.footerOrder||data.order)];render();$('reset').disabled=false;status(t('connected'))}).catch(()=>status(t('reconnect'),true));
|
|
208
|
+
</script>
|
|
209
|
+
</html>
|