fix(desktop): restore legacy webview dialog and highlight fixes
This commit is contained in:
19 files changed
+810
-332
No files matched your search
@@ -25,4 +25,21 @@ describe("createAiShikiBlockCodeHighlighter", () => {
|
||||
expect(html).not.toContain("<pre");
|
||||
expect(html).not.toContain("<code");
|
||||
});
|
||||
|
||||
it("can build the oniguruma WASM engine used on legacy WebViews", async () => {
|
||||
// Mirrors the exact wiring loadAiShikiHighlighter uses on WebKit engines
|
||||
// that cannot compile the JavaScript engine's lookbehind patterns, so a
|
||||
// broken shiki/wasm integration fails here instead of on a packaged app.
|
||||
const [{ createHighlighterCore }, { createOnigurumaEngine }, { default: sql }, { default: githubLight }] = await Promise.all([import("shiki/core"), import("shiki/engine/oniguruma"), import("shiki/langs/sql.mjs"), import("shiki/themes/github-light.mjs")]);
|
||||
const highlighter = await createHighlighterCore({
|
||||
engine: await createOnigurumaEngine(import("shiki/wasm")),
|
||||
langs: [sql],
|
||||
themes: [githubLight],
|
||||
});
|
||||
|
||||
const html = highlighter.codeToHtml("SELECT id FROM users", { lang: "sql", structure: "classic", theme: "github-light" });
|
||||
|
||||
expect(html).toContain('class="line"');
|
||||
expect(html).toMatch(/style="color:#/);
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AppThemeAppearance } from "@/lib/app/appTheme";
|
||||
import { supportsRegExpLookbehind } from "@/lib/ui/legacyWebView";
|
||||
|
||||
export type AiCodeHighlighter = (content: string, lang: string, appearance?: AppThemeAppearance) => string;
|
||||
|
||||
@@ -96,9 +97,15 @@ function getAiShikiHighlighter(): Promise<ShikiHighlighter> {
|
||||
}
|
||||
|
||||
async function loadAiShikiHighlighter(): Promise<ShikiHighlighter> {
|
||||
const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, bash, css, go, html, java, javascript, json, markdown, php, python, rust, shellscript, sql, tsx, typescript, vue, xml, yaml] = await Promise.all([
|
||||
const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, onigurumaEngineModules, githubDark, githubLight, bash, css, go, html, java, javascript, json, markdown, php, python, rust, shellscript, sql, tsx, typescript, vue, xml, yaml] = await Promise.all([
|
||||
import("shiki/core"),
|
||||
import("shiki/engine/javascript"),
|
||||
// Old WebKit (Safari < 16.4) throws SyntaxError while compiling the
|
||||
// lookbehind / named-group patterns the JavaScript engine generates from
|
||||
// TextMate grammars (code snapshots and AI code blocks then lose all
|
||||
// highlighting). Only fetch the heavier inlined-Oniguruma WASM bundle on
|
||||
// engines that need it.
|
||||
supportsRegExpLookbehind() ? Promise.resolve(null) : Promise.all([import("shiki/engine/oniguruma"), import("shiki/wasm")]),
|
||||
import("shiki/themes/github-dark.mjs"),
|
||||
import("shiki/themes/github-light.mjs"),
|
||||
import("shiki/langs/bash.mjs"),
|
||||
@@ -122,7 +129,7 @@ async function loadAiShikiHighlighter(): Promise<ShikiHighlighter> {
|
||||
]);
|
||||
|
||||
return createHighlighterCore({
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
engine: onigurumaEngineModules ? await onigurumaEngineModules[0].createOnigurumaEngine(onigurumaEngineModules[1]) : createJavaScriptRegexEngine(),
|
||||
langs: [bash.default, css.default, go.default, html.default, java.default, javascript.default, json.default, markdown.default, php.default, python.default, rust.default, shellscript.default, sql.default, tsx.default, typescript.default, vue.default, xml.default, yaml.default],
|
||||
themes: [githubDark.default, githubLight.default],
|
||||
});
|
||||
|
||||
@@ -119,6 +119,60 @@ describe("renderCodeSnapshotHtml", () => {
|
||||
expect(html).not.toContain('class="dbx-code-snapshot__pre dbx-code-snapshot__pre--numbered"');
|
||||
});
|
||||
|
||||
it("gives SQL table names their own color, distinct from quoted fields", async () => {
|
||||
// Mirror shiki's classic structure: one .line span per source line.
|
||||
highlightCode.mockImplementation((content: string) =>
|
||||
content
|
||||
.split(/\r\n|\r|\n/)
|
||||
.map((line) => `<span class="line">${line}</span>`)
|
||||
.join(""),
|
||||
);
|
||||
const html = await renderCodeSnapshotHtml({ code: "SELECT `id`, `title`\nFROM `tb_book`;", lang: "sql" }, { appearance: "light" });
|
||||
|
||||
expect(html).toContain('data-sql-token="table"');
|
||||
expect(html).toContain("color:#116329");
|
||||
// Only the table name is marked; the selected fields keep the identifier color.
|
||||
expect(html.match(/data-sql-token="table"/g)).toHaveLength(1);
|
||||
expect(html).toMatch(/data-sql-token="table"[^>]*>`?tb_book`</);
|
||||
expect(html).not.toMatch(/data-sql-token="table"[^>]*>`?id</);
|
||||
});
|
||||
|
||||
it("marks every table across FROM lists, aliases and JOIN clauses", async () => {
|
||||
highlightCode.mockImplementation((content: string) =>
|
||||
content
|
||||
.split(/\r\n|\r|\n/)
|
||||
.map((line) => `<span class="line">${line}</span>`)
|
||||
.join(""),
|
||||
);
|
||||
const html = await renderCodeSnapshotHtml({ code: "SELECT *\nFROM users u, orders o\nJOIN items i ON i.order_id = u.id", lang: "sql" }, { appearance: "dark" });
|
||||
|
||||
expect(html).toContain("color:#7ee787");
|
||||
for (const table of ["users", "orders", "items"]) {
|
||||
expect(html).toMatch(new RegExp(`data-sql-token="table"[^>]*>${table}</span>`));
|
||||
}
|
||||
// Fields referenced in the projection and join condition stay unmarked.
|
||||
expect(html.match(/data-sql-token="table"/g)).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("maps table offsets correctly across CRLF line breaks", async () => {
|
||||
highlightCode.mockImplementation((content: string) =>
|
||||
content
|
||||
.split(/\r\n|\r|\n/)
|
||||
.map((line) => `<span class="line">${line}</span>`)
|
||||
.join(""),
|
||||
);
|
||||
const html = await renderCodeSnapshotHtml({ code: "SELECT `id`\r\nFROM `tb_book`", lang: "sql" }, { appearance: "light" });
|
||||
|
||||
expect(html).toMatch(/data-sql-token="table"[^>]*>`?tb_book`</);
|
||||
expect(html).not.toMatch(/data-sql-token="table"[^>]*>`?id</);
|
||||
});
|
||||
|
||||
it("skips table-name marking for non-SQL languages", async () => {
|
||||
const html = await renderCodeSnapshotHtml({ code: "from app import models", lang: "python" }, { appearance: "light" });
|
||||
|
||||
expect(html).not.toContain('data-sql-token="table"');
|
||||
});
|
||||
|
||||
it("escapes the snapshot title", async () => {
|
||||
const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql", title: `<script>alert(1)</script>` }, { appearance: "dark" });
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
import type { AppThemeAppearance } from "@/lib/app/appTheme";
|
||||
import { createAiShikiBlockCodeHighlighter, type AiCodeHighlighter } from "@/lib/ai/aiCodeHighlighter";
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
import { sqlSemanticTableNameSpans } from "@/lib/sql/semantic/model";
|
||||
import { LEGACY_WEBVIEW_CLASS } from "@/lib/ui/legacyWebView";
|
||||
|
||||
export interface CodeSnapshotSource {
|
||||
@@ -61,6 +62,13 @@ const SNAPSHOT_CODE_TEXT: Record<AppThemeAppearance, string> = {
|
||||
dark: "#e1e4e8",
|
||||
};
|
||||
|
||||
const SNAPSHOT_TABLE_NAME_COLOR: Record<AppThemeAppearance, string> = {
|
||||
light: "#116329",
|
||||
dark: "#7ee787",
|
||||
};
|
||||
|
||||
const SQL_SNAPSHOT_LANGS = new Set(["sql", "mysql", "postgresql", "postgres", "tsql", "clickhouse", "sqlite"]);
|
||||
|
||||
const TRAFFIC_LIGHT_COLORS = ["#ff5f57", "#febc2e", "#28c840"] as const;
|
||||
const MAX_EXPORT_PIXEL_RATIO = 2;
|
||||
const MAX_EXPORT_CANVAS_EDGE = 16_384;
|
||||
@@ -218,6 +226,81 @@ export function materializeSnapshotCloneLineNumbers(root: ParentNode): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Give SQL table names their own color so they stand apart from field
|
||||
* identifiers — shiki renders quoted table and column identifiers with the
|
||||
* same string token color, while the editor marks table names semantically.
|
||||
* The same metadata-free analyzer as the editor's table-name highlight maps
|
||||
* table spans onto the highlighted HTML; the wrapper carries an inline color,
|
||||
* so the preview and both export paths (clipboard/PNG clone of this DOM) stay
|
||||
* identical.
|
||||
*/
|
||||
export function applySnapshotSqlTableColors(highlightedBody: string, rawCode: string, appearance: AppThemeAppearance): string {
|
||||
let tableSpans: Array<{ start: number; end: number }>;
|
||||
try {
|
||||
tableSpans = sqlSemanticTableNameSpans(rawCode);
|
||||
} catch {
|
||||
return highlightedBody;
|
||||
}
|
||||
if (tableSpans.length === 0) return highlightedBody;
|
||||
|
||||
const parsed = new DOMParser().parseFromString(`<t>${highlightedBody}</t>`, "text/html");
|
||||
const root = parsed.body.firstElementChild;
|
||||
if (!root) return highlightedBody;
|
||||
|
||||
// Line starts in the raw code; shiki splits lines into .line elements whose
|
||||
// text no longer contains the separators, so offsets are mapped per line.
|
||||
const lineStarts: number[] = [0];
|
||||
for (let index = 0; index < rawCode.length; index += 1) {
|
||||
if (rawCode[index] === "\n") lineStarts.push(index + 1);
|
||||
else if (rawCode[index] === "\r") lineStarts.push(index + (rawCode[index + 1] === "\n" ? 2 : 1));
|
||||
}
|
||||
|
||||
const lineElements = Array.from(root.querySelectorAll<HTMLElement>(".line"));
|
||||
const rawLines = rawCode.split(/\r\n|\r|\n/);
|
||||
const color = SNAPSHOT_TABLE_NAME_COLOR[appearance];
|
||||
|
||||
const wrapRanges = (textNode: Text, nodeStart: number, clipEnd: number, totalLength: number) => {
|
||||
const ranges: Array<[number, number]> = [];
|
||||
for (const span of tableSpans) {
|
||||
const start = Math.max(span.start, nodeStart);
|
||||
const end = Math.min(span.end, nodeStart + totalLength, clipEnd);
|
||||
if (start < end) ranges.push([start - nodeStart, end - nodeStart]);
|
||||
}
|
||||
ranges.sort((a, b) => b[0] - a[0]);
|
||||
for (const [relativeStart, relativeEnd] of ranges) {
|
||||
if (relativeEnd < totalLength) textNode.splitText(relativeEnd);
|
||||
const segment = relativeStart > 0 ? textNode.splitText(relativeStart) : textNode;
|
||||
const wrapper = textNode.ownerDocument!.createElement("span");
|
||||
wrapper.className = "dbx-code-snapshot__table-name";
|
||||
wrapper.setAttribute("data-sql-token", "table");
|
||||
// setAttribute (not style.color) keeps the literal color in the DOM;
|
||||
// style.color serializes engine-dependently (rgb() in WebKit/Chromium).
|
||||
wrapper.setAttribute("style", `color:${color}`);
|
||||
segment.parentNode?.insertBefore(wrapper, segment);
|
||||
wrapper.appendChild(segment);
|
||||
}
|
||||
};
|
||||
|
||||
lineElements.forEach((lineElement, lineIndex) => {
|
||||
const lineStart = lineStarts[lineIndex];
|
||||
const lineEnd = lineStart + (rawLines[lineIndex]?.length ?? 0);
|
||||
const walker = lineElement.ownerDocument!.createTreeWalker(lineElement, NodeFilter.SHOW_TEXT);
|
||||
const textNodes: Text[] = [];
|
||||
while (walker.nextNode()) textNodes.push(walker.currentNode as Text);
|
||||
let position = lineStart;
|
||||
for (const textNode of textNodes) {
|
||||
const totalLength = textNode.length;
|
||||
wrapRanges(textNode, position, lineEnd, totalLength);
|
||||
// splitText keeps the leading part in place; the consumed length is the
|
||||
// original node's length regardless of how the ranges split it.
|
||||
position += totalLength;
|
||||
}
|
||||
});
|
||||
|
||||
return root.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a self-contained snapshot DOM (as an HTML string) for the given code.
|
||||
* The returned string includes its own `<style>` tag and can be injected via
|
||||
@@ -233,6 +316,10 @@ export async function renderCodeSnapshotHtml(source: CodeSnapshotSource, options
|
||||
body = renderEscapedSnapshotLines(source.code);
|
||||
}
|
||||
|
||||
if (SQL_SNAPSHOT_LANGS.has(source.lang.trim().toLowerCase())) {
|
||||
body = applySnapshotSqlTableColors(body, source.code, options.appearance);
|
||||
}
|
||||
|
||||
const appearance = options.appearance;
|
||||
const showBar = options.showTrafficLights !== false || !!source.title;
|
||||
const showLineNumbers = options.showLineNumbers !== false;
|
||||
|
||||
+24
-1
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { applyLegacyWebViewClass, isLegacyWebView, LEGACY_WEBVIEW_CLASS, missingLegacyWebViewCapabilities } from "@/lib/ui/legacyWebView";
|
||||
import { applyLegacyWebViewClass, isLegacyWebView, LEGACY_WEBVIEW_CLASS, missingLegacyWebViewCapabilities, supportsRegExpLookbehind } from "@/lib/ui/legacyWebView";
|
||||
|
||||
const supportedFeatures = new Set(["oklch", "color-mix-oklab", "color-mix-oklch", "has-selector", "dynamic-viewport", "min-function", "media-query-range"]);
|
||||
|
||||
@@ -84,3 +84,26 @@ describe("legacy WebView detection", () => {
|
||||
expect(root.classList.contains(LEGACY_WEBVIEW_CLASS)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsRegExpLookbehind", () => {
|
||||
it("reports support when the engine compiles lookbehind patterns", () => {
|
||||
expect(supportsRegExpLookbehind()).toBe(true);
|
||||
});
|
||||
|
||||
it("reports no support when lookbehind patterns throw like old WebKit", () => {
|
||||
const OriginalRegExp = RegExp;
|
||||
vi.stubGlobal(
|
||||
"RegExp",
|
||||
class extends OriginalRegExp {
|
||||
constructor(pattern: string | RegExp, flags?: string) {
|
||||
if (typeof pattern === "string" && pattern.includes("(?<")) {
|
||||
throw new SyntaxError("Invalid regular expression: invalid group specifier name");
|
||||
}
|
||||
super(pattern, flags);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
expect(supportsRegExpLookbehind()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -43,6 +43,21 @@ export function missingLegacyWebViewCapabilities(): string[] {
|
||||
return MODERN_CSS_FEATURES.filter((feature) => !supports(feature)).map((feature) => feature.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Old WebKit (Safari < 16.4) throws SyntaxError when compiling regular
|
||||
* expressions with lookbehind or the named-group shapes Shiki's JavaScript
|
||||
* engine generates from TextMate grammars. Callers use this to pick a regex
|
||||
* engine (e.g. Shiki's Oniguruma WASM engine) that old WebKit can run.
|
||||
*/
|
||||
export function supportsRegExpLookbehind(): boolean {
|
||||
try {
|
||||
new RegExp("(?<=a)b");
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isLegacyWebView(): boolean {
|
||||
return missingLegacyWebViewCapabilities().length > 0;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user