Compare commits

..
Author SHA1 Message Date
l0ng-ai 836e781e7c fix(editor): align the Find Usages source preview 2026-11-23 10:41:42 +08:00
21 changed files with 264 additions and 257 deletions

No files matched your search

-110
View File
@@ -1,110 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function openTable(page: Page, columns: number) {
await stubDesktop(page);
await page.evaluate(async (columns) => {
window.__ipc.handlers.debug_evaluate_in = ({ expression }) => {
const query = String(expression);
const sliced = query.includes("totals.iloc[:2, :2]");
const visibleColumns = sliced ? 2 : Math.min(30, columns);
const columnsInFrame = sliced ? 2 : columns;
const start = query.includes("100, 100,") ? 100 : 0;
const rows = sliced ? 2 : 220;
const count = sliced ? 2 : 100;
const result = query.includes("missing_table")
? { error: "NameError: missing_table" }
: {
kind: "frame",
shape: [rows, columnsInFrame],
rows,
columns: columnsInFrame,
headers: Array.from({ length: visibleColumns }, (_, i) => `Amount ${i + 1}`),
dtypes: Array.from({ length: visibleColumns }, () => "int64"),
index: Array.from({ length: count }, (_, i) => String(i + start)),
cells: Array.from({ length: count }, (_, row) =>
Array.from({ length: visibleColumns }, (_, column) => String((row + start + 1) * 10 + column)),
),
};
return {
name: "",
value: JSON.stringify(JSON.stringify(result)),
typeName: "str",
variablesReference: 0,
evaluateName: null,
};
};
const stateModule = "/src/features/debugger/state.ts";
const overlaysModule = "/src/features/debugger/ui/popoverStore.ts";
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
const { openTableView } = await import(/* @vite-ignore */ overlaysModule);
adoptSession(91, { name: "Settlement review", adapter: "debugpy", status: "paused", selectedFrame: 11 });
openTableView("totals", 91);
}, columns);
const dialog = page.getByRole("dialog", { name: "Table view of totals", exact: true });
await expect(dialog.getByRole("table")).toBeVisible();
return dialog;
}
test("View as Table gives the grid the dialog width and puts the expression below it", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const dialog = await openTable(page, 3);
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
const grid = dialog.getByRole("table");
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
const shape = dialog.getByText("Shape (220, 3)", { exact: true });
const body = (await scroll.boundingBox())!;
const input = (await expression.boundingBox())!;
expect(input.y).toBeGreaterThan(body.y + body.height);
expect((await shape.boundingBox())!.y).toBeLessThan(body.y);
expect(Math.abs((await grid.boundingBox())!.width - (await scroll.evaluate((el) => el.clientWidth)))).toBeLessThan(1);
expect((await dialog.boundingBox())!.width).toBeCloseTo(700, 0);
await expect(expression).toBeFocused();
await expect(grid).toHaveCSS("font-family", /Inter/);
await expect(grid.getByRole("columnheader").nth(1)).toHaveCSS("text-align", "center");
await expect(grid.getByRole("rowheader").first()).toHaveCSS("text-align", "center");
await expect(grid.getByRole("cell").first()).toHaveCSS("text-align", /^(start|left)$/);
});
test("View as Table keeps paging, slice input and Close usable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 450, height: 620 });
const dialog = await openTable(page, 36);
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
const rows = dialog.getByRole("button", { name: "Next Rows", exact: true });
const columns = dialog.getByRole("button", { name: "Next Columns", exact: true });
const close = dialog.getByRole("button", { name: "Close", exact: true }).filter({ hasText: /^Close$/ });
const input = (await expression.boundingBox())!;
const grid = (await scroll.boundingBox())!;
expect(input.y).toBeGreaterThan(grid.y + grid.height);
expect(input.width).toBeCloseTo(grid.width, 0);
for (const control of [expression, rows, columns, close]) await expect(control).toBeInViewport({ ratio: 0.98 });
await scroll.evaluate((el) => {
el.scrollLeft = 300;
el.scrollTop = 150;
});
await expect(dialog.getByRole("rowheader").filter({ hasText: /^9$/ })).toBeInViewport({ ratio: 0.98 });
await rows.click();
await expect(dialog.getByText("Rows 101–200 of 220", { exact: true })).toBeVisible();
await expect
.poll(() => ipcCalls(page, "debug_evaluate_in"))
.toContainEqual(expect.objectContaining({ expression: expect.stringContaining("100, 100, 0, 30") }));
await expression.fill("totals.iloc[:2, :2]");
await expression.press("Enter");
const sliced = page.getByRole("dialog", { name: "Table view of totals.iloc[:2, :2]", exact: true });
await expect(sliced.getByText("Shape (2, 2)", { exact: true })).toBeVisible();
const slicedExpression = sliced.getByRole("textbox", { name: "Expression", exact: true });
await slicedExpression.fill("missing_table");
await slicedExpression.press("Enter");
const failed = page.getByRole("dialog", { name: "Table view of missing_table", exact: true });
const alert = failed.getByRole("alert");
await expect(alert).toHaveText("NameError: missing_table");
expect((await alert.boundingBox())!.y).toBeGreaterThan(
(await failed.getByRole("textbox", { name: "Expression", exact: true }).boundingBox())!.y,
);
await failed
.getByRole("button", { name: "Close", exact: true })
.filter({ hasText: /^Close$/ })
.click();
await expect(failed).toHaveCount(0);
});
+1 -23
View File
@@ -75,7 +75,7 @@ for (const locale of ["en", "zh"]) {
const path = "/src/platform/i18n.ts";
await (await import(/* @vite-ignore */ path)).setLocale(locale);
}, locale);
for (const id of ["appearance", "editor.font", "general", "general.httpProxy", "vcs.log"]) {
for (const id of ["appearance", "editor.font", "general", "general.httpProxy"]) {
await selectPage(page, id);
const body = page.locator("[class*='pageBody']");
for (const width of [1000, 784, 640, 520]) {
@@ -108,28 +108,6 @@ test("keeps Open project in options within narrow System Settings", async ({ wor
expect(overflow).toBeLessThanOrEqual(1);
});
test("Git Log settings group display and column options with aligned checkboxes", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await selectPage(page, "vcs.log");
const view = dialog.getByRole("region", { name: "View Options" });
const columns = dialog.getByRole("region", { name: "Visible columns" });
const tagNames = view.getByRole("checkbox", { name: "Show tag names" });
const hash = columns.getByRole("checkbox", { name: "Hash" });
await expect(view.getByRole("checkbox")).toHaveCount(5);
await expect(columns.getByRole("checkbox")).toHaveCount(4);
for (const width of [1000, 520]) {
await page.setViewportSize({ width, height: 760 });
expect((await tagNames.boundingBox())!.x).toBeCloseTo((await hash.boundingBox())!.x, 0);
}
await expect(hash).not.toBeChecked();
await hash.focus();
await page.keyboard.press("Space");
await expect(hash).toBeChecked();
});
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
+95
View File
@@ -0,0 +1,95 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
async function setEditorMetrics(page: Page, fontSize: number, lineHeight: number) {
await page.evaluate(
async ({ fontSize, lineHeight }) => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { settings, project } = useProject.getState();
const current = settings ?? project?.settings;
if (!current) throw new Error("Expected project settings");
useProject.setState({ settings: { ...current, editor: { ...current.editor, fontSize, lineHeight } } });
},
{ fontSize, lineHeight },
);
}
async function openResults(page: Page) {
await page.setViewportSize({ width: 1120, height: 720 });
await stubDesktop(page);
await setEditorMetrics(page, 20, 34);
await page.evaluate(async () => {
const lines = Array.from({ length: 1240 }, () => "");
lines[1233] = " record(orderTotal);";
lines[1237] = " return orderTotal;";
window.__ipc.handlers.fs_read_text = () => lines.join("\n");
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("find.showUsageResults", {
symbol: "orderTotal",
locations: [
{
path: "/dev/acme-api/src/orderTotals.ts",
range: { start: { line: 1233, col: 9 }, end: { line: 1233, col: 19 } },
},
{
path: "/dev/acme-api/src/orderTotals.ts",
range: { start: { line: 1237, col: 9 }, end: { line: 1237, col: 19 } },
},
],
});
});
const view = page.getByRole("region", { name: "Find Usages", exact: true });
await view.getByRole("treeitem").filter({ hasText: "1234" }).click();
const preview = view.getByRole("region", { name: "Preview", exact: true });
await expect(preview.locator("mark")).toHaveCount(2);
return { view, preview };
}
test("Find Usages preview follows editor line height and fits long line numbers", async ({ workbench: page }) => {
const { preview } = await openResults(page);
await expect(preview).toHaveCSS("font-size", "20px");
await expect(preview).toHaveCSS("line-height", "34px");
const number = preview.getByText("1234", { exact: true });
const gutter = await number.evaluate((element) => {
const range = document.createRange();
range.selectNodeContents(element);
const text = range.getBoundingClientRect();
const box = element.getBoundingClientRect();
return { textInset: text.left - box.left, width: box.width };
});
expect(gutter.textInset).toBeGreaterThanOrEqual(1);
await expect(number).toBeInViewport({ ratio: 0.98 });
expect((await preview.getByText("999", { exact: true }).boundingBox())!.width).toBeCloseTo(gutter.width, 0);
await page.setViewportSize({ width: 560, height: 720 });
await setEditorMetrics(page, 20, 39);
await expect(preview).toHaveCSS("line-height", "39px");
await expect(number).toBeInViewport({ ratio: 0.98 });
});
test("Find Usages starts with equal panes and keeps a separate saved size for each orientation", async ({
workbench: page,
}) => {
const { view } = await openResults(page);
const divider = view.locator('[id="usages-preview-split"]').getByRole("separator");
await expect(divider).toHaveAttribute("aria-valuenow", "50");
await divider.press("ArrowRight");
await expect(divider).not.toHaveAttribute("aria-valuenow", "50");
const horizontal = (await divider.getAttribute("aria-valuenow"))!;
await page.setViewportSize({ width: 560, height: 720 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(divider).toHaveAttribute("aria-valuenow", "50");
await divider.press("ArrowDown");
await expect(divider).not.toHaveAttribute("aria-valuenow", "50");
const vertical = (await divider.getAttribute("aria-valuenow"))!;
await page.setViewportSize({ width: 1120, height: 720 });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(divider).toHaveAttribute("aria-valuenow", horizontal);
await page.setViewportSize({ width: 560, height: 720 });
await expect(divider).toHaveAttribute("aria-valuenow", vertical);
});
@@ -159,7 +159,7 @@
flex-direction: column;
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 1.45;
line-height: var(--lh-code);
}
.sourcePreview .sourceText[role="region"] {
font: inherit;
+13 -2
View File
@@ -406,6 +406,8 @@ export function useUsagesHeaderMenu(): MenuItem[] {
];
}
const DEFAULT_PREVIEW_LAYOUT = { usages: 50, preview: 50 };
function UsagesSplit({ preview, children }: { preview: ReactNode; children: ReactNode }) {
const show = useUsagesOptions((s) => s.preview);
const frame = useRef<HTMLDivElement>(null);
@@ -427,12 +429,13 @@ function UsagesSplit({ preview, children }: { preview: ReactNode; children: Reac
orientation={stacked ? "vertical" : "horizontal"}
id="usages-preview-split"
storageKey={stacked ? "openidea.usages.previewSplit.vertical" : "openidea.usages.previewSplit"}
defaultLayout={DEFAULT_PREVIEW_LAYOUT}
>
<SplitPanel id="usages" minSize={stacked ? "30%" : 160} className={styles.panel}>
{children}
</SplitPanel>
<SplitHandle />
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} defaultSize="45%" className={styles.panel}>
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
@@ -455,13 +458,21 @@ function UsagesPreview({ node }: { node: Node | null }) {
return (group?.usages ?? []).map((u) => ({ line: u.line, ranges: [[u.col, u.endCol] as const] }));
}, [usage, search?.groups]);
return (
<div className={styles.sourcePreview} style={{ fontFamily, fontSize: settings?.fontSize ?? undefined }}>
<div
className={styles.sourcePreview}
style={{
fontFamily,
fontSize: settings?.fontSize ?? undefined,
lineHeight: settings?.lineHeight != null ? `${settings.lineHeight}px` : undefined,
}}
>
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
editorLayout
className={styles.sourceText}
/>
</div>
+5
View File
@@ -12,6 +12,11 @@ export function isTableType(typeName: string | null | undefined): boolean {
return !!typeName && TABLE_TYPES.has(typeName);
}
/** Numbers are right-aligned, as in the database grid. */
export function isNumericDtype(dtype: string | undefined): boolean {
return !!dtype && /^(u?int|float|complex|Int|UInt|Float)\d*$/.test(dtype);
}
export const ROW_PAGE = 100;
export const COLUMN_PAGE = 30;
@@ -1,35 +1,39 @@
.dialog {
height: 500px;
height: clamp(320px, 60vh, 760px);
}
/* Scroll only the grid between the toolbar and the expression field. */
/* The table scrolls under a fixed bar, not the whole dialog body. */
.content {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
padding: var(--space-2) var(--space-3) 0;
gap: var(--space-2);
}
.bar {
flex: none;
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: space-between;
gap: var(--space-1) var(--space-2);
gap: var(--space-2);
padding-bottom: var(--space-2);
}
.expression {
flex: none;
flex: 1 1 200px;
min-width: 0;
height: var(--h-list-row);
padding: 0 6px;
font-family: var(--font-mono);
font-size: var(--fs-ui);
color: var(--fg);
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.pagers {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1) var(--space-2);
.expression:focus {
outline: none;
border-color: var(--focus-ring);
}
.summary,
@@ -55,8 +59,7 @@
.table {
border-collapse: separate;
border-spacing: 0;
min-width: 100%;
font-family: var(--font-ui);
font-family: var(--font-mono);
font-size: var(--fs-ui);
color: var(--fg);
}
@@ -74,7 +77,7 @@
position: sticky;
top: 0;
z-index: 1;
text-align: center;
text-align: left;
font-weight: normal;
color: var(--fg-secondary);
background: var(--bg-island);
@@ -83,8 +86,7 @@
.table .index {
position: sticky;
left: 0;
text-align: center;
font-variant-numeric: tabular-nums;
text-align: right;
font-weight: normal;
color: var(--fg-secondary);
background: var(--bg-island);
@@ -98,22 +100,16 @@
background: var(--bg-hover);
}
.numeric {
text-align: right;
}
.dtype {
margin-left: var(--space-1);
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.message {
flex: 1;
min-height: 0;
padding: var(--space-3) 0;
color: var(--fg-secondary);
}
.error {
max-height: 5em;
overflow: auto;
overflow-wrap: anywhere;
color: var(--danger);
}
+58 -44
View File
@@ -1,10 +1,19 @@
/** View as Table: a DataFrame / Series / ndarray of the paused frame, one page of rows and columns at a time. */
import { useEffect, useRef, useState } from "react";
import clsx from "clsx";
import type { DebugSessionId } from "@/platform/ipc";
import { Dialog, IconButton, Input } from "@/ui";
import { Dialog, IconButton } from "@/ui";
import { formatMessage, tx } from "@/platform/i18n";
import { evaluate, useDebug } from "../state";
import { COLUMN_PAGE, ROW_PAGE, clampWindow, parseTableResult, tableExpression, type TableResult } from "../tableView";
import {
COLUMN_PAGE,
ROW_PAGE,
clampWindow,
isNumericDtype,
parseTableResult,
tableExpression,
type TableResult,
} from "../tableView";
import styles from "./TableViewDialog.module.css";
export function TableViewDialog({
@@ -54,7 +63,7 @@ export function TableViewDialog({
};
}, [expression, win, session, stops, frame, paused]);
const page = paused && result && "page" in result ? result.page : null;
const page = result && "page" in result ? result.page : null;
const error = !paused
? tx("Values are available while the program is paused")
: result && "error" in result
@@ -105,37 +114,54 @@ export function TableViewDialog({
open
onClose={onClose}
// An element, not a string: Dialog would translate a variable named like a catalog text ("tasks").
title={<span>{expression}</span>}
width={700}
title={<span>{initial}</span>}
width="clamp(520px, 70vw, 1100px)"
minWidth={420}
minHeight={260}
resizable="both"
aria-label={formatMessage(tx("Table view of {label}"), { label: expression })}
buttons={[{ label: "Close", role: "cancel" }]}
aria-label={formatMessage(tx("Table view of {label}"), { label: initial })}
className={styles.dialog}
>
<div className={styles.content}>
{page && (
<div className={styles.bar}>
<div className={styles.bar}>
<input
className={styles.expression}
value={draft}
spellCheck={false}
autoComplete="off"
aria-label={tx("Expression")}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key !== "Enter" || !draft.trim()) return;
e.preventDefault();
setExpression(draft.trim());
setWin({ row: 0, column: 0 });
}}
/>
{page && (
<span className={styles.summary}>
{formatMessage(tx("Shape ({shape})"), { shape: page.shape.join(", ") })}
{page.kind !== "frame" ? ` · ${page.dtypes[0]}` : ""}
</span>
<div className={styles.pagers}>
{pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), {
range: tx("Rows {from}–{to} of {total}"),
previous: tx("Previous Rows"),
next: tx("Next Rows"),
})}
{pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), {
range: tx("Columns {from}–{to} of {total}"),
previous: tx("Previous Columns"),
next: tx("Next Columns"),
})}
</div>
)}
{page &&
pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), {
range: tx("Rows {from}–{to} of {total}"),
previous: tx("Previous Rows"),
next: tx("Next Rows"),
})}
{page &&
pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), {
range: tx("Columns {from}–{to} of {total}"),
previous: tx("Previous Columns"),
next: tx("Next Columns"),
})}
</div>
{error ? (
<div className={styles.message} role="alert">
{error}
</div>
)}
{page ? (
) : page ? (
<div className={styles.scroll} tabIndex={0} role="region" aria-label={tx("Table")}>
<table className={styles.table}>
<thead>
@@ -156,7 +182,14 @@ export function TableViewDialog({
{page.index[r]}
</th>
{row.map((cell, c) => (
<td key={c}>{cell}</td>
<td
key={c}
className={clsx(
isNumericDtype(page.kind === "frame" ? page.dtypes[c] : page.dtypes[0]) && styles.numeric,
)}
>
{cell}
</td>
))}
</tr>
))}
@@ -164,26 +197,7 @@ export function TableViewDialog({
</table>
</div>
) : (
<div className={styles.message}>{!error && tx("Loading…")}</div>
)}
<Input
className={styles.expression}
mono
data-autofocus=""
value={draft}
aria-label="Expression"
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key !== "Enter" || !draft.trim()) return;
e.preventDefault();
setExpression(draft.trim());
setWin({ row: 0, column: 0 });
}}
/>
{error && (
<div className={styles.error} role="alert">
{error}
</div>
<div className={styles.message}>{tx("Loading…")}</div>
)}
</div>
</Dialog>
+14 -25
View File
@@ -1,33 +1,22 @@
.page {
display: grid;
gap: var(--space-4);
display: flex;
flex-direction: column;
gap: 10px;
color: var(--fg);
font-size: var(--fs-ui);
}
.heading {
.section {
display: flex;
align-items: center;
flex-direction: column;
gap: var(--space-2);
min-height: var(--h-field);
margin: 0 0 var(--space-1);
color: var(--fg-strong);
font-size: inherit;
font-weight: 500;
margin-top: 6px;
}
.heading::after {
content: "";
flex: 1;
height: 1px;
background: var(--border);
.header {
color: var(--fg-muted);
}
.options {
display: grid;
gap: var(--space-1);
padding-inline-start: var(--space-4);
}
.options > label {
min-height: var(--h-field);
.columns {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding-left: 18px;
}
+8 -15
View File
@@ -1,8 +1,8 @@
/** Settings › Version Control › Log: how the Git Log shows references, dates and columns. */
import { useId, type ReactNode } from "react";
import { Checkbox, T } from "@/ui";
import { setLogOptions, useLogOptions, type LogOptions } from "./logOptions";
import styles from "./LogSettingsPage.module.css";
import { tx } from "@/platform/i18n";
type Flag = { [K in keyof LogOptions]: LogOptions[K] extends boolean ? K : never }[keyof LogOptions];
@@ -21,18 +21,6 @@ const COLUMNS: { key: Flag; label: string }[] = [
{ key: "showGitHubChecks", label: "GitHub Commit Checks" },
];
function OptionGroup({ title, children }: { title: string; children: ReactNode }) {
const heading = useId();
return (
<section aria-labelledby={heading}>
<h2 id={heading} className={styles.heading}>
<T>{title}</T>
</h2>
<div className={styles.options}>{children}</div>
</section>
);
}
export function LogSettingsPage() {
const o = useLogOptions();
// Display options only: the log needs no reload.
@@ -41,8 +29,13 @@ export function LogSettingsPage() {
);
return (
<div className={styles.page}>
<OptionGroup title="View Options">{OPTIONS.map(flag)}</OptionGroup>
<OptionGroup title="Visible columns">{COLUMNS.map(flag)}</OptionGroup>
{OPTIONS.map(flag)}
<section className={styles.section} aria-label={tx("Visible columns")}>
<div className={styles.header}>
<T>Visible columns:</T>
</div>
<div className={styles.columns}>{COLUMNS.map(flag)}</div>
</section>
</div>
);
}
+1 -3
View File
@@ -3707,7 +3707,5 @@
"Previous Rows": "Previous Rows",
"Next Rows": "Next Rows",
"Previous Columns": "Previous Columns",
"Next Columns": "Next Columns",
"View Options": "View Options",
"Visible columns": "Visible columns"
"Next Columns": "Next Columns"
}
+1
View File
@@ -4751,6 +4751,7 @@
"Show commit time rather than author time": "Mostrar fecha y hora de la confirmación en lugar de la del autor",
"Show references on the left": "Mostrar referencias a la izquierda",
"Visible columns": "Columnas visibles",
"Visible columns:": "Columnas visibles:",
"Get from Revision": "Obtener de la revisión",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "¿Reemplazar '{path}' con su contenido de la revisión? Los cambios locales se perderán.",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "¿Reemplazar {length} archivos con su contenido de la revisión? Los cambios locales en ellos se perderán.",
+1
View File
@@ -4606,6 +4606,7 @@
"Show commit time rather than author time": "Afficher l'heure du commit plutôt que celle de l'auteur",
"Show references on the left": "Afficher les références à gauche",
"Visible columns": "Colonnes visibles",
"Visible columns:": "Colonnes visibles :",
"Get from Revision": "Récupérer depuis la révision",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "Remplacer '{path}' par son contenu de la révision ? Ses modifications locales seront perdues.",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "Remplacer {length} fichiers par leur contenu de la révision ? Leurs modifications locales seront perdues.",
+1
View File
@@ -4823,6 +4823,7 @@
"Show commit time rather than author time": "작성자 시간 대신 커밋 시간 표시",
"Show references on the left": "왼쪽에 참조 표시",
"Visible columns": "표시할 열",
"Visible columns:": "표시할 열:",
"Get from Revision": "리비전에서 가져오기",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "'{path}'을(를) 리비전의 내용으로 바꾸시겠습니까? 해당 파일의 로컬 변경 사항은 손실됩니다.",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "파일 {length}개를 리비전의 내용으로 바꾸시겠습니까? 해당 파일의 로컬 변경 사항은 손실됩니다.",
+1
View File
@@ -4702,6 +4702,7 @@
"Show commit time rather than author time": "Pokaż czas zatwierdzenia zamiast czasu autora",
"Show references on the left": "Pokaż odnośniki po lewej stronie",
"Visible columns": "Widoczne kolumny",
"Visible columns:": "Widoczne kolumny:",
"Get from Revision": "Pobierz z wersji",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "Zastąpić '{path}' zawartością z tej wersji? Lokalne zmiany w tym pliku zostaną utracone.",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "Zastąpić pliki w liczbie {length} ich zawartością z tej wersji? Lokalne zmiany w nich zostaną utracone.",
+1
View File
@@ -4717,6 +4717,7 @@
"Show commit time rather than author time": "Mostrar data/hora do commit em vez da do autor",
"Show references on the left": "Mostrar referências à esquerda",
"Visible columns": "Colunas visíveis",
"Visible columns:": "Colunas visíveis:",
"Get from Revision": "Obter da revisão",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "Substituir '{path}' pelo seu conteúdo da revisão? Alterações locais nele serão perdidas.",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "Substituir {length} arquivos pelo seu conteúdo da revisão? Alterações locais neles serão perdidas.",
+1
View File
@@ -7428,6 +7428,7 @@
"Show commit time rather than author time": "Yazar zamanı yerine commit zamanını göster",
"Show references on the left": "Başvuruları solda göster",
"Visible columns": "Görünür sütunlar",
"Visible columns:": "Görünür sütunlar:",
"Get from Revision": "Revizyondan Al",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "'{path}' dosyası revizyondaki içeriğiyle değiştirilsin mi? Yerel değişiklikleri kaybolacak.",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "{length} dosya revizyondaki içerikleriyle değiştirilsin mi? Yerel değişiklikleri kaybolacak.",
+1
View File
@@ -5736,6 +5736,7 @@
"Show commit time rather than author time": "顯示提交時間而非作者時間",
"Show references on the left": "在左側顯示引用",
"Visible columns": "可見欄",
"Visible columns:": "可見欄:",
"Get from Revision": "從修訂取得",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "用修訂中的內容取代「{path}」?其本機更改將遺失。",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "用修訂中的內容取代 {length} 個檔案?它們的本機更改將遺失。",
+1
View File
@@ -6227,6 +6227,7 @@
"Show commit time rather than author time": "显示提交时间而非作者时间",
"Show references on the left": "在左侧显示引用",
"Visible columns": "可见列",
"Visible columns:": "可见列:",
"Get from Revision": "从修订获取",
"Replace '{path}' with its content from the revision? Local changes to it are lost.": "用修订中的内容替换“{path}”?其本地更改将丢失。",
"Replace {length} files with their content from the revision? Local changes to them are lost.": "用修订中的内容替换 {length} 个文件?它们的本地更改将丢失。",
+2 -2
View File
@@ -41,8 +41,8 @@
flex: none;
position: sticky;
left: 0;
width: 48px;
padding-right: 12px;
width: var(--source-preview-gutter-width, 48px);
padding-right: var(--space-3);
text-align: right;
color: var(--fg-gutter);
background-color: var(--bg-app);
+34 -4
View File
@@ -9,7 +9,7 @@
* Usages. Files beyond `MAX_PARSE` stay plain rather than colouring the window
* with the wrong block-comment context.
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import clsx from "clsx";
import { T } from "./T";
import { tokenSpans, type SourceToken } from "./tokenSpans";
@@ -46,6 +46,8 @@ export interface SourcePreviewProps {
version?: number;
/** Stable (module-level) syntax colouring; without it lines stay plain. */
colorize?: SourceColorizer;
/** Fit the gutter to the line numbers and keep the selected line visible when the pane resizes. */
editorLayout?: boolean;
className?: string;
}
@@ -56,6 +58,7 @@ export function SourcePreview({
load,
version = 0,
colorize,
editorLayout,
className,
}: SourcePreviewProps) {
const [text, setText] = useState<{ path: string; lines: string[] } | null>(null);
@@ -160,6 +163,7 @@ export function SourcePreview({
lines={current.lines}
tokensByLine={tokensByLine}
highlights={highlights}
editorLayout={editorLayout}
className={className}
/>
);
@@ -176,6 +180,7 @@ function PreviewBody({
lines,
tokensByLine,
highlights,
editorLayout,
className,
}: {
path: string;
@@ -183,6 +188,7 @@ function PreviewBody({
lines: string[];
tokensByLine: Map<number, SourceToken[]> | null;
highlights: readonly SourceHighlight[];
editorLayout?: boolean;
className?: string;
}) {
const scrollRef = useRef<HTMLDivElement>(null);
@@ -192,8 +198,21 @@ function PreviewBody({
useLayoutEffect(() => {
const box = scrollRef.current;
const el = box?.querySelector<HTMLElement>(`[data-line="${line}"]`);
if (box && el) box.scrollTop = el.offsetTop - box.clientHeight / 2 + el.offsetHeight / 2;
}, [line, path, lines]);
if (!box || !el) return;
const center = () => {
box.scrollTop = el.offsetTop - box.clientHeight / 2 + el.offsetHeight / 2;
};
center();
if (!editorLayout || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
if (el.offsetTop < box.scrollTop || el.offsetTop + el.offsetHeight > box.scrollTop + box.clientHeight) {
center();
}
});
observer.observe(box);
observer.observe(el);
return () => observer.disconnect();
}, [editorLayout, line, path, lines]);
const byLine = new Map(highlights.map((h) => [h.line, h.ranges]));
const start = Math.max(0, line - WINDOW);
@@ -214,7 +233,18 @@ function PreviewBody({
}
return (
<div ref={scrollRef} className={clsx(styles.preview, className)} role="region" aria-label={tx("Preview")}>
<pre className={styles.pre}>{rows}</pre>
<pre
className={styles.pre}
style={
editorLayout
? ({
"--source-preview-gutter-width": `calc(${String(lines.length).length}ch + var(--space-4))`,
} as CSSProperties)
: undefined
}
>
{rows}
</pre>
</div>
);
}