дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Merge remote-tracking branch 'origin/main' into fix/editor-breadcrumb-layout
Цей коміт міститься в:
коміт
3eff08d2f8
82 files changed
+2861
-379
No files matched your search
@@ -16,6 +16,7 @@ import {
|
||||
type DocumentInfo,
|
||||
type DocumentLanguage,
|
||||
type FoldRange,
|
||||
type IdeEvent,
|
||||
type LanguageInfo_Serialize,
|
||||
type LineEnding,
|
||||
type OutlineItem,
|
||||
@@ -38,6 +39,8 @@ export interface DocPatchedEvent {
|
||||
changes: TextChange[];
|
||||
}
|
||||
|
||||
export type DocDirtyEvent = Extract<IdeEvent, { type: "docDirty" }>;
|
||||
|
||||
export interface DocBackend {
|
||||
open(path: string): Promise<DocumentInfo>;
|
||||
/** Opens a read-only language-server document (library or disk class contents). */
|
||||
@@ -71,7 +74,7 @@ export interface DocBackend {
|
||||
*/
|
||||
languageOf?(path: string, firstLine?: string): Promise<DocumentLanguage>;
|
||||
onPatched(handler: (e: DocPatchedEvent) => void): () => void;
|
||||
onDirty(handler: (e: { doc: DocId; dirty: boolean }) => void): () => void;
|
||||
onDirty(handler: (e: DocDirtyEvent) => void): () => void;
|
||||
/** Files changed on disk (used to refresh nothing but closed-file state). */
|
||||
onFsChanged?(handler: (e: { removed: string[] }) => void): () => void;
|
||||
/**
|
||||
@@ -393,7 +396,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
const docs = new Map<DocId, MemDoc>();
|
||||
const byPath = new Map<string, DocId>();
|
||||
const patched = new Set<(e: DocPatchedEvent) => void>();
|
||||
const dirtyHandlers = new Set<(e: { doc: DocId; dirty: boolean }) => void>();
|
||||
const dirtyHandlers = new Set<(e: DocDirtyEvent) => void>();
|
||||
let nextId = 1;
|
||||
const store = new Map(Object.entries(files));
|
||||
const savedBoms = new Map<string, boolean>();
|
||||
@@ -442,7 +445,8 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
};
|
||||
const setDirty = (d: MemDoc, before: boolean) => {
|
||||
const now = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
if (now !== before) dirtyHandlers.forEach((h) => h({ doc: d.id, dirty: now }));
|
||||
if (now !== before)
|
||||
dirtyHandlers.forEach((h) => h({ type: "docDirty", doc: d.id, dirty: now, version: d.version }));
|
||||
};
|
||||
const delay = <T>(v: () => T): Promise<T> =>
|
||||
backend.latency > 0
|
||||
|
||||
@@ -30,6 +30,14 @@ async function settle() {
|
||||
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function setup(files: Record<string, string>, settings = {}) {
|
||||
_resetLanguages();
|
||||
const backend: MemoryBackend = createMemoryBackend(files);
|
||||
@@ -217,6 +225,166 @@ describe("DocumentManager + slots", () => {
|
||||
expect(useDocMeta.getState()["/p/a.txt"]?.dirty).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["dirty before response", "dirty after response", "clean and dirty after response"] as const)(
|
||||
"keeps a newer edit dirty with %s",
|
||||
async (order) => {
|
||||
const path = "/p/a.txt";
|
||||
const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } });
|
||||
const model = await manager.acquire(path);
|
||||
const slot = new EditorSlot(model, "t1", host);
|
||||
const events: Array<() => void> = [];
|
||||
const originalOnDirty = backend.onDirty.bind(backend);
|
||||
let deferDirty = false;
|
||||
const onDirty = vi.spyOn(backend, "onDirty").mockImplementation((handler) =>
|
||||
originalOnDirty((event) => {
|
||||
if (deferDirty) events.push(() => handler(event));
|
||||
else handler(event);
|
||||
}),
|
||||
);
|
||||
manager.stop();
|
||||
manager.start();
|
||||
const response = deferred();
|
||||
const originalSave = backend.save.bind(backend);
|
||||
const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => {
|
||||
await originalSave(doc);
|
||||
await response.promise;
|
||||
});
|
||||
const transitions: boolean[] = [];
|
||||
const unsubscribe = useDocMeta.subscribe((state, previous) => {
|
||||
const dirty = state[path]?.dirty;
|
||||
if (dirty !== undefined && dirty !== previous[path]?.dirty) transitions.push(dirty);
|
||||
});
|
||||
let pending: Promise<void> | undefined;
|
||||
try {
|
||||
slot.dispatchLocal({ changes: { from: 4, insert: " saved" } });
|
||||
await model.sync.whenIdle();
|
||||
expect(transitions).toEqual([true]);
|
||||
|
||||
deferDirty = order === "clean and dirty after response";
|
||||
pending = model.save("explicit");
|
||||
await vi.waitFor(() => expect(backend.files.get(path)).toBe("base saved\n"));
|
||||
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false });
|
||||
|
||||
transitions.length = 0;
|
||||
deferDirty = order !== "dirty before response";
|
||||
slot.dispatchLocal({ changes: { from: 10, insert: " newer" } });
|
||||
await model.sync.whenIdle();
|
||||
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: true });
|
||||
|
||||
response.resolve();
|
||||
await pending;
|
||||
expect(slot.currentState().doc.toString()).toBe("base saved newer\n");
|
||||
expect(backend.files.get(path)).toBe("base saved\n");
|
||||
expect(model.getMeta().dirty).toBe(true);
|
||||
const deferredCount = order === "dirty before response" ? 0 : order === "dirty after response" ? 1 : 2;
|
||||
expect(events).toHaveLength(deferredCount);
|
||||
events.splice(0).forEach((deliver) => deliver());
|
||||
expect(useDocMeta.getState()[path]?.dirty).toBe(true);
|
||||
expect(transitions).not.toContain(false);
|
||||
|
||||
deferDirty = false;
|
||||
await model.save("explicit");
|
||||
expect(backend.files.get(path)).toBe("base saved newer\n");
|
||||
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: false });
|
||||
expect(useDocMeta.getState()[path]?.dirty).toBe(false);
|
||||
expect(transitions.at(-1)).toBe(false);
|
||||
} finally {
|
||||
response.resolve();
|
||||
try {
|
||||
await pending;
|
||||
} finally {
|
||||
unsubscribe();
|
||||
save.mockRestore();
|
||||
onDirty.mockRestore();
|
||||
slot.dispose();
|
||||
manager.releaseProjectDocuments();
|
||||
manager.stop();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("marks an unchanged buffer clean when its save succeeds", async () => {
|
||||
const path = "/p/a.txt";
|
||||
const { backend, manager } = setup({ [path]: "base\n" });
|
||||
const model = await manager.acquire(path);
|
||||
const slot = new EditorSlot(model, "t1", host);
|
||||
const transitions: Array<{ dirty: boolean; persisted: string | undefined }> = [];
|
||||
const unsubscribe = useDocMeta.subscribe((state, previous) => {
|
||||
const dirty = state[path]?.dirty;
|
||||
if (dirty !== undefined && dirty !== previous[path]?.dirty)
|
||||
transitions.push({ dirty, persisted: backend.files.get(path) });
|
||||
});
|
||||
try {
|
||||
slot.dispatchLocal({ changes: { from: 4, insert: " saved" } });
|
||||
await model.save("explicit");
|
||||
expect(slot.currentState().doc.toString()).toBe("base saved\n");
|
||||
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false });
|
||||
expect(transitions).toEqual([
|
||||
{ dirty: true, persisted: "base\n" },
|
||||
{ dirty: false, persisted: "base saved\n" },
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
slot.dispose();
|
||||
manager.releaseProjectDocuments();
|
||||
manager.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("reconciles a save that includes an edit whose acknowledgement is still pending", async () => {
|
||||
const path = "/p/a.txt";
|
||||
const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } });
|
||||
const model = await manager.acquire(path);
|
||||
const slot = new EditorSlot(model, "t1", host);
|
||||
const write = deferred();
|
||||
const editReply = deferred();
|
||||
const originalSave = backend.save.bind(backend);
|
||||
const originalEdit = backend.edit.bind(backend);
|
||||
const edit = vi.spyOn(backend, "edit");
|
||||
const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => {
|
||||
await write.promise;
|
||||
await originalSave(doc);
|
||||
});
|
||||
let pending: Promise<void> | undefined;
|
||||
try {
|
||||
slot.dispatchLocal({ changes: { from: 4, insert: " first" } });
|
||||
await model.sync.whenIdle();
|
||||
pending = model.save("explicit");
|
||||
await vi.waitFor(() => expect(save).toHaveBeenCalledWith(model.doc));
|
||||
|
||||
edit.mockImplementationOnce(async (...args) => {
|
||||
const version = await originalEdit(...args);
|
||||
await editReply.promise;
|
||||
return version;
|
||||
});
|
||||
slot.dispatchLocal({ changes: { from: 10, insert: " second" } });
|
||||
const synced = model.sync.whenIdle();
|
||||
await vi.waitFor(async () => {
|
||||
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base first second\n", dirty: true });
|
||||
});
|
||||
write.resolve();
|
||||
await pending;
|
||||
editReply.resolve();
|
||||
await synced;
|
||||
expect(slot.currentState().doc.toString()).toBe("base first second\n");
|
||||
expect(backend.files.get(path)).toBe("base first second\n");
|
||||
expect(useDocMeta.getState()[path]?.dirty).toBe(false);
|
||||
} finally {
|
||||
editReply.resolve();
|
||||
write.resolve();
|
||||
try {
|
||||
await pending;
|
||||
} finally {
|
||||
edit.mockRestore();
|
||||
save.mockRestore();
|
||||
slot.dispose();
|
||||
manager.releaseProjectDocuments();
|
||||
manager.stop();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["explicit", "auto"] as const)(
|
||||
"%s save leaves untouched documents byte-for-byte unchanged",
|
||||
async (reason) => {
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
} from "@/editor/api";
|
||||
import { isUntitledUri, isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { DocSync, type Scheduler, frameScheduler } from "../sync/DocSync";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
import type { DocBackend, DocDirtyEvent, LanguageInfo } from "../backend";
|
||||
import {
|
||||
findLanguageDescription,
|
||||
languageInfo,
|
||||
@@ -261,6 +261,7 @@ export class DocModel {
|
||||
handoffRelease = false;
|
||||
private refreshTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private saving: Promise<void> = Promise.resolve();
|
||||
private backendDirty: DocDirtyEvent | null = null;
|
||||
private meta: DocMeta;
|
||||
|
||||
constructor(
|
||||
@@ -321,6 +322,7 @@ export class DocModel {
|
||||
changes: eventChanges,
|
||||
});
|
||||
},
|
||||
onSynced: () => this.applyBackendClean(),
|
||||
onDiscarded: (reason) => {
|
||||
logError(`document ${this.path}: unsaved edits replaced by the file's content`, reason);
|
||||
manager.notify({
|
||||
@@ -345,6 +347,26 @@ export class DocModel {
|
||||
if (!this.closed) useDocMeta.setState({ [this.path]: this.meta });
|
||||
}
|
||||
|
||||
onBackendDirty(event: DocDirtyEvent) {
|
||||
if (this.backendDirty && event.version < this.backendDirty.version) return;
|
||||
this.backendDirty = event;
|
||||
if (event.dirty) {
|
||||
if (!this.meta.dirty) this.setMeta({ dirty: true });
|
||||
} else this.applyBackendClean();
|
||||
}
|
||||
|
||||
private applyBackendClean() {
|
||||
const event = this.backendDirty;
|
||||
if (event && !event.dirty) this.markClean(event.version);
|
||||
}
|
||||
|
||||
private markClean(version: number) {
|
||||
// A clean event can arrive before an edit acknowledgement or after a newer edit.
|
||||
if (!this.meta.dirty || !this.sync.idle || this.sync.serverVersion !== version) return;
|
||||
this.modified.clear();
|
||||
this.setMeta({ dirty: false });
|
||||
}
|
||||
|
||||
ctx(): EditorDocContext {
|
||||
return {
|
||||
doc: this.doc,
|
||||
@@ -713,16 +735,20 @@ export class DocModel {
|
||||
// an explicit save asks for one (Save As re-points the buffer, or stays
|
||||
// dirty on Cancel).
|
||||
if (reason === "auto") return;
|
||||
if (await this.manager.saveAs(this)) this.modified.clear();
|
||||
await this.manager.saveAs(this);
|
||||
return;
|
||||
}
|
||||
const backend = this.manager.backend;
|
||||
const version = this.sync.serverVersion;
|
||||
const observedDirty = this.backendDirty;
|
||||
// Autosave never overwrites external changes made after the buffer was edited.
|
||||
if (reason === "auto" && backend.autosave) {
|
||||
if (!(await backend.autosave(this.doc))) return;
|
||||
} else await backend.save(this.doc);
|
||||
this.modified.clear();
|
||||
this.setMeta({ dirty: false });
|
||||
// The reply does not identify what was saved. It only confirms the version
|
||||
// we sent if the buffer and the observed backend dirty state haven't moved on.
|
||||
if (this.backendDirty === observedDirty && (!observedDirty || observedDirty.version <= version))
|
||||
this.markClean(version);
|
||||
_emitEditorEvent({ type: "docSaved", doc: this.doc, path: this.path });
|
||||
};
|
||||
this.saving = this.saving.then(run, run);
|
||||
@@ -732,6 +758,7 @@ export class DocModel {
|
||||
/** Save As turned this untitled buffer into the file `info` points at. */
|
||||
retarget(info: DocumentInfo) {
|
||||
const old = this.path;
|
||||
if (!this.backendDirty?.dirty || this.backendDirty.version < info.version) this.markClean(info.version);
|
||||
this.path = info.path;
|
||||
this.info = languageInfo(info.language);
|
||||
this.editorconfig = info.editorconfig ?? null;
|
||||
@@ -743,7 +770,6 @@ export class DocModel {
|
||||
hasBom: info.hasBom,
|
||||
lineEnding: info.lineEnding,
|
||||
canReloadEncoding: info.canReloadEncoding,
|
||||
dirty: false,
|
||||
};
|
||||
useDocMeta.setState((s) => {
|
||||
const next = { ...s };
|
||||
@@ -803,13 +829,7 @@ export class DocumentManager {
|
||||
this.workspaceHistory.start(),
|
||||
this.backend.onPatched((e) => this.byId.get(e.doc)?.sync.remote(e)),
|
||||
this.backend.onLanguage?.((e) => this.byId.get(e.doc)?.setLanguage(e.language, e.uiMode)) ?? (() => {}),
|
||||
this.backend.onDirty((e) => {
|
||||
const m = this.byId.get(e.doc);
|
||||
if (m && m.getMeta().dirty !== e.dirty) {
|
||||
m.setMeta({ dirty: e.dirty });
|
||||
if (!e.dirty) m.modified.clear();
|
||||
}
|
||||
}),
|
||||
this.backend.onDirty((e) => this.byId.get(e.doc)?.onBackendDirty(e)),
|
||||
);
|
||||
let prev = useEditorRegistry.getState().contributions;
|
||||
this.disposers.push(
|
||||
|
||||
@@ -38,6 +38,8 @@ export interface SyncHost {
|
||||
applyRemote(changes: ChangeSet, workspaceEdit?: boolean): void;
|
||||
/** A locally produced batch accepted by the versioned backend. */
|
||||
onLocalCommitted?(baseVersion: number, version: number, changes: ChangeSet): void;
|
||||
/** The local buffer has no pending edits or resync. */
|
||||
onSynced?(): void;
|
||||
/** Called after a hard resync discarded local changes the backend never saw. */
|
||||
onDiscarded?(reason: unknown): void;
|
||||
/** Non-recoverable transport errors (logged by default). */
|
||||
@@ -157,6 +159,7 @@ export class DocSync {
|
||||
if (this.disposed || patch.version <= this.serverVersion) return;
|
||||
this.pendingRemote.push(patch);
|
||||
this.drainRemote();
|
||||
this.resolveIdle();
|
||||
}
|
||||
|
||||
dispose() {
|
||||
@@ -356,6 +359,7 @@ export class DocSync {
|
||||
|
||||
private resolveIdle(force = false) {
|
||||
if (!force && !this.idle) return;
|
||||
if (this.idle && !this.disposed) this.host.onSynced?.();
|
||||
const waiters = this.idleWaiters;
|
||||
this.idleWaiters = [];
|
||||
waiters.forEach((w) => w());
|
||||
|
||||
@@ -101,6 +101,40 @@ describe("untitled editor input", () => {
|
||||
expect(JSON.stringify(session)).not.toContain("untitled:");
|
||||
});
|
||||
|
||||
it("keeps edits made after a Save As write dirty when retargeting the tab", async () => {
|
||||
await ctrl!.openUntitled({ focus: false });
|
||||
const slot = ctrl!.slotFor(activeTab().id)!;
|
||||
const model = await editActive("draft");
|
||||
const path = "/p/saved.txt";
|
||||
vi.mocked(save).mockResolvedValue(path);
|
||||
let release!: () => void;
|
||||
const response = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const originalSaveAs = backend.saveAs.bind(backend);
|
||||
const saveAs = vi.spyOn(backend, "saveAs").mockImplementationOnce(async (...args) => {
|
||||
const info = await originalSaveAs(...args);
|
||||
await response;
|
||||
return info;
|
||||
});
|
||||
const pending = model.save("explicit");
|
||||
try {
|
||||
await vi.waitFor(() => expect(backend.files.get(path)).toBe("draft\n"));
|
||||
slot.dispatchLocal({ changes: { from: 5, insert: " newer" } });
|
||||
await model.sync.whenIdle();
|
||||
release();
|
||||
await pending;
|
||||
expect(activeTab().input.path).toBe(path);
|
||||
expect(slot.currentState().doc.toString()).toBe("draft newer\n");
|
||||
expect(backend.files.get(path)).toBe("draft\n");
|
||||
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "draft newer\n", dirty: true });
|
||||
expect(useDocMeta.getState()[path]?.dirty).toBe(true);
|
||||
} finally {
|
||||
release();
|
||||
await pending.finally(() => saveAs.mockRestore());
|
||||
}
|
||||
});
|
||||
|
||||
it("offers the registered languages as save-as types", async () => {
|
||||
await ctrl!.openUntitled({ focus: false });
|
||||
const slot = ctrl!.slotFor(activeTab().id)!;
|
||||
|
||||
@@ -30,8 +30,7 @@
|
||||
}
|
||||
.withPreview {
|
||||
flex-direction: row;
|
||||
width: auto;
|
||||
max-width: min(1160px, 94vw);
|
||||
min-width: 0;
|
||||
}
|
||||
.listMain {
|
||||
display: flex;
|
||||
@@ -39,6 +38,11 @@
|
||||
min-width: 0;
|
||||
flex: none;
|
||||
}
|
||||
.withPreview .listMain {
|
||||
flex: 1 1 320px;
|
||||
min-width: 300px;
|
||||
min-height: 0;
|
||||
}
|
||||
.mnemonic {
|
||||
width: 10px;
|
||||
flex: none;
|
||||
@@ -48,14 +52,39 @@
|
||||
text-align: right;
|
||||
}
|
||||
.previewPanel {
|
||||
width: 420px;
|
||||
flex: none;
|
||||
flex: 0 1 var(--list-preview-width);
|
||||
min-width: 300px;
|
||||
min-height: 60px;
|
||||
max-height: 340px;
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
border-left: 1px solid var(--border-popup);
|
||||
background: var(--bg-popup-inline, var(--bg-elev));
|
||||
}
|
||||
.previewLeft {
|
||||
flex-direction: row-reverse;
|
||||
}
|
||||
.previewLeft .previewPanel {
|
||||
border-left: 0;
|
||||
border-right: 1px solid var(--border-popup);
|
||||
}
|
||||
.previewBelow {
|
||||
flex-direction: column;
|
||||
}
|
||||
.previewBelow .listMain {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.previewBelow .previewPanel {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
max-height: min(300px, 40vh);
|
||||
border-left: 0;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
}
|
||||
.previewBelow .previewPanel[aria-busy] {
|
||||
height: 60px;
|
||||
}
|
||||
.previewText {
|
||||
padding: 8px 10px;
|
||||
font-size: var(--fs-small);
|
||||
@@ -66,12 +95,13 @@
|
||||
padding: 6px 0;
|
||||
font-family: var(--openidea-editor-font, var(--font-mono));
|
||||
font-weight: var(--fw-code);
|
||||
font-size: var(--fs-small);
|
||||
font-size: var(--openidea-editor-font-size, var(--fs-code));
|
||||
color: var(--fg-editor);
|
||||
}
|
||||
.diffLine {
|
||||
padding: 0 10px;
|
||||
white-space: pre;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
min-height: 1.4em;
|
||||
}
|
||||
.diff-added {
|
||||
@@ -238,6 +268,10 @@
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.docPopup:not([data-resized]) {
|
||||
width: max-content;
|
||||
min-width: min(300px, 90vw);
|
||||
}
|
||||
.docScope {
|
||||
display: contents;
|
||||
}
|
||||
@@ -246,21 +280,32 @@
|
||||
}
|
||||
.docPopup .docFrame {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.docPopup:not([data-resized]) .docFrame {
|
||||
max-width: min(600px, 90vw);
|
||||
max-height: 420px;
|
||||
max-width: min(500px, 90vw);
|
||||
max-height: 500px;
|
||||
}
|
||||
.docPopup .docBody {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
padding: var(--space-2) var(--space-4) var(--space-1);
|
||||
}
|
||||
.docPopup .docToolbar {
|
||||
position: static;
|
||||
flex: none;
|
||||
align-self: flex-end;
|
||||
margin: 0 var(--space-2) var(--space-1);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.docPopup .docToolbar .spacer {
|
||||
display: none;
|
||||
}
|
||||
.docWindowFrame {
|
||||
height: 100%;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** React popups for LSP editor features, rendered as a workbench overlay. */
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
Checkbox,
|
||||
@@ -49,11 +49,17 @@ function ItemIcon({ item }: { item: ListPopupItem }) {
|
||||
return <span className={styles.iconSpacer} />;
|
||||
}
|
||||
|
||||
function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading" }) {
|
||||
function ListPreviewPanel({
|
||||
preview,
|
||||
themeClasses,
|
||||
}: {
|
||||
preview: ListPreview | null | "loading";
|
||||
themeClasses?: string;
|
||||
}) {
|
||||
if (preview === "loading") return <div className={styles.previewPanel} aria-busy="true" />;
|
||||
if (!preview) return null;
|
||||
return (
|
||||
<div className={styles.previewPanel} aria-label={tx("Preview")}>
|
||||
<div className={clsx(styles.previewPanel, themeClasses)} role="region" aria-label={tx("Preview")}>
|
||||
{preview.kind === "text" ? (
|
||||
<div className={styles.previewText}>{preview.text}</div>
|
||||
) : (
|
||||
@@ -70,6 +76,9 @@ function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading"
|
||||
);
|
||||
}
|
||||
|
||||
const LIST_PREVIEW_WIDTH = 420;
|
||||
const MIN_SIDE_BY_SIDE_WIDTH = 660;
|
||||
|
||||
function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const filtered = useMemo(() => {
|
||||
@@ -91,6 +100,13 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
|
||||
const [preview, setPreview] = useState<{ id: string; data: ListPreview | null } | null>(null);
|
||||
const fetchPreview = popup.preview;
|
||||
const [viewportWidth, setViewportWidth] = useState(() => window.innerWidth);
|
||||
useEffect(() => {
|
||||
if (!fetchPreview) return;
|
||||
const resize = () => setViewportWidth(window.innerWidth);
|
||||
window.addEventListener("resize", resize);
|
||||
return () => window.removeEventListener("resize", resize);
|
||||
}, [fetchPreview]);
|
||||
useEffect(() => {
|
||||
if (!fetchPreview || !activeItem || activeItem.disabled) return;
|
||||
const ctrl = new AbortController();
|
||||
@@ -164,22 +180,46 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
? ("loading" as const)
|
||||
: null
|
||||
: null;
|
||||
const hasPreview = shownPreview !== null;
|
||||
const previewBelow = hasPreview && viewportWidth <= MIN_SIDE_BY_SIDE_WIDTH;
|
||||
const previewLeft =
|
||||
hasPreview &&
|
||||
!previewBelow &&
|
||||
popup.anchor.x + width + LIST_PREVIEW_WIDTH > viewportWidth - 6 &&
|
||||
popup.anchor.x >= LIST_PREVIEW_WIDTH + 6;
|
||||
const anchor = useMemo(() => {
|
||||
if (!fetchPreview) return popup.anchor;
|
||||
const x = popup.anchor.x - (previewLeft ? LIST_PREVIEW_WIDTH : 0);
|
||||
return {
|
||||
getBoundingClientRect: () =>
|
||||
new DOMRect(
|
||||
Math.max(0, Math.min(x, window.innerWidth)),
|
||||
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
|
||||
0,
|
||||
0,
|
||||
),
|
||||
};
|
||||
}, [fetchPreview, popup.anchor, previewLeft]);
|
||||
const popupSize = {
|
||||
width: hasPreview ? width + LIST_PREVIEW_WIDTH : width,
|
||||
"--list-preview-width": `${LIST_PREVIEW_WIDTH}px`,
|
||||
} as CSSProperties;
|
||||
const indexOf = (item: ListPopupItem) => popup.items.indexOf(item);
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={popup.anchor}
|
||||
anchor={anchor}
|
||||
onClose={closePopup}
|
||||
aria-label={popup.title}
|
||||
className={clsx(styles.listPopup, popup.preview && styles.withPreview)}
|
||||
style={popup.preview ? undefined : { width }}
|
||||
className={clsx(
|
||||
styles.listPopup,
|
||||
hasPreview && styles.withPreview,
|
||||
previewBelow && styles.previewBelow,
|
||||
previewLeft && styles.previewLeft,
|
||||
)}
|
||||
style={popupSize}
|
||||
>
|
||||
<div
|
||||
className={styles.listMain}
|
||||
style={popup.preview ? { width } : undefined}
|
||||
data-testid="list-popup"
|
||||
aria-busy={popup.busy || undefined}
|
||||
>
|
||||
<div className={styles.listMain} data-testid="list-popup" aria-busy={popup.busy || undefined}>
|
||||
<div className={styles.listHeader}>
|
||||
<span className={styles.listTitle}>{popup.title}</span>
|
||||
{popup.busy && <Spinner size={12} />}
|
||||
@@ -260,7 +300,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{popup.preview && <ListPreviewPanel preview={shownPreview} />}
|
||||
{popup.preview && <ListPreviewPanel preview={shownPreview} themeClasses={popup.themeClasses} />}
|
||||
{sub?.item.submenu && (
|
||||
<Popup
|
||||
open
|
||||
@@ -356,6 +396,19 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
|
||||
const focusSeq = useLspPopup((s) => s.focusSeq);
|
||||
const scope = useRef<HTMLDivElement>(null);
|
||||
const opened = useRef(focusSeq);
|
||||
// The captured caret can end up outside the viewport while the popup is open.
|
||||
const anchor = useMemo(
|
||||
() => ({
|
||||
getBoundingClientRect: () =>
|
||||
new DOMRect(
|
||||
Math.max(0, Math.min(popup.anchor.x, window.innerWidth)),
|
||||
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
|
||||
0,
|
||||
0,
|
||||
),
|
||||
}),
|
||||
[popup.anchor],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (focusSeq !== opened.current)
|
||||
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
|
||||
@@ -364,7 +417,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={popup.anchor}
|
||||
anchor={anchor}
|
||||
onClose={closePopup}
|
||||
aria-label="Documentation"
|
||||
className={styles.docPopup}
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
type CompletionSource,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view";
|
||||
import { EditorView, ViewPlugin, getTooltip, keymap, showTooltip, type Rect, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
@@ -59,6 +59,8 @@ import { showHint } from "./hint";
|
||||
import { inplaceRenameActive } from "./inplaceRename";
|
||||
import { languageSemantics } from "./semantic";
|
||||
import { remoteChange } from "@/editor/api";
|
||||
import { tooltipBounds } from "@/editor/core/cm/setup";
|
||||
import { completionLabelOffset } from "./theme";
|
||||
|
||||
interface RequestContext {
|
||||
doc: number;
|
||||
@@ -983,36 +985,45 @@ function sortToggle(view: EditorView): HTMLElement {
|
||||
return button;
|
||||
}
|
||||
|
||||
/** IDEA's advertiser bar under the list (one tip: "Press ↵ to insert, ⇥ to replace") and its Sort by Name toggle. */
|
||||
const completionFooter = ViewPlugin.fromClass(
|
||||
const completionPopup = ViewPlugin.fromClass(
|
||||
class {
|
||||
constructor(private view: EditorView) {}
|
||||
update(u: ViewUpdate) {
|
||||
if (completionStatus(u.state) !== "active") return;
|
||||
this.view.requestMeasure({
|
||||
read: () => null,
|
||||
write: () => {
|
||||
const scope = this.view.dom.ownerDocument;
|
||||
const tooltips = [
|
||||
...this.view.dom.querySelectorAll<HTMLElement>(".cm-tooltip-autocomplete"),
|
||||
...scope.querySelectorAll<HTMLElement>(".cm-tooltip-autocomplete"),
|
||||
];
|
||||
for (const t of tooltips) {
|
||||
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
|
||||
if (footer) {
|
||||
// CodeMirror rebuilds the option list by appending a fresh <ul>,
|
||||
// which would leave an existing footer above the list.
|
||||
const list = t.querySelector(":scope > ul");
|
||||
if (list && list.nextElementSibling !== footer) list.after(footer);
|
||||
continue;
|
||||
}
|
||||
key: this,
|
||||
read: () => {
|
||||
const { left, right } = tooltipBounds(this.view);
|
||||
return {
|
||||
width: `${Math.max(0, Math.floor(right - left))}px`,
|
||||
fontSize: getComputedStyle(this.view.contentDOM).fontSize,
|
||||
};
|
||||
},
|
||||
write: ({ width, fontSize }) => {
|
||||
const popup = this.view.state
|
||||
.facet(showTooltip)
|
||||
.map((tooltip) => tooltip && getTooltip(this.view, tooltip))
|
||||
.find((tooltip) => tooltip?.dom.classList.contains("cm-lsp-completion"));
|
||||
if (!popup) return;
|
||||
// Apply the label alignment inside CodeMirror's viewport clamp.
|
||||
popup.offset = { x: -completionLabelOffset, y: 0 };
|
||||
const t = popup.dom;
|
||||
if (t.style.getPropertyValue("--cm-completion-max-width") !== width)
|
||||
t.style.setProperty("--cm-completion-max-width", width);
|
||||
// The body-level tooltip does not inherit the editor's temporary font zoom.
|
||||
if (t.style.getPropertyValue("--openidea-editor-font-size") !== fontSize)
|
||||
t.style.setProperty("--openidea-editor-font-size", fontSize);
|
||||
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
|
||||
if (!footer) {
|
||||
footer = document.createElement("div");
|
||||
footer.className = "cm-lsp-completion-footer";
|
||||
const tip = document.createElement("span");
|
||||
tip.textContent = tx("Press ↵ to insert, ⇥ to replace");
|
||||
footer.append(tip, sortToggle(this.view));
|
||||
t.appendChild(footer);
|
||||
}
|
||||
// CodeMirror appends a fresh list when the candidates change.
|
||||
const list = t.querySelector(":scope > ul");
|
||||
if (list && list.nextElementSibling !== footer) list.after(footer);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1067,7 +1078,7 @@ export function completionExtension() {
|
||||
tooltipClass: () => "cm-lsp-completion",
|
||||
positionInfo: positionCompletionInfo,
|
||||
}),
|
||||
completionFooter,
|
||||
completionPopup,
|
||||
lookupTracker,
|
||||
serverInsertAt,
|
||||
caretAfterServerInsert,
|
||||
|
||||
@@ -552,6 +552,7 @@ export async function showIntentions(view: EditorView) {
|
||||
items,
|
||||
busy,
|
||||
preview,
|
||||
themeClasses: view.themeClasses,
|
||||
onClose: () => {
|
||||
dismissed = true;
|
||||
},
|
||||
|
||||
@@ -104,6 +104,7 @@ export type LspPopup =
|
||||
pin?: { label: string; run: () => void };
|
||||
/** Side panel for the selected row, fetched lazily; `signal` aborts when the selection moves. */
|
||||
preview?: (item: ListPopupItem, signal: AbortSignal) => Promise<ListPreview | null>;
|
||||
themeClasses?: string;
|
||||
/** Runs when the popup goes away (closed, replaced or a row ran). */
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
@@ -10,19 +10,17 @@ const tooltipSurface = {
|
||||
color: "var(--fg)",
|
||||
};
|
||||
|
||||
/**
|
||||
* Row metrics that put a label one icon column right of the popup's left edge. They live on the
|
||||
* popup as custom properties so every rule consuming them — including the popup's negative
|
||||
* offset below — changes together. The remaining 1px is tooltipSurface's border, shared with
|
||||
* the hover and signature tooltips.
|
||||
*/
|
||||
const completionInsets = { edge: 4, padding: 6, icon: 16, gap: 6 };
|
||||
export const completionLabelOffset =
|
||||
1 + completionInsets.edge + completionInsets.padding + completionInsets.icon + completionInsets.gap;
|
||||
|
||||
const completionRowMetrics = {
|
||||
// Rows grow with the editor font size (lookup text uses the editor font, as typed text does).
|
||||
"--cm-completion-row": "max(var(--h-list-row), calc(var(--openidea-editor-font-size, var(--fs-code)) * 1.7))",
|
||||
"--cm-completion-edge": "4px",
|
||||
"--cm-completion-inset": "6px",
|
||||
"--cm-completion-icon": "16px",
|
||||
"--cm-completion-gap": "6px",
|
||||
"--cm-completion-edge": `${completionInsets.edge}px`,
|
||||
"--cm-completion-inset": `${completionInsets.padding}px`,
|
||||
"--cm-completion-icon": `${completionInsets.icon}px`,
|
||||
"--cm-completion-gap": `${completionInsets.gap}px`,
|
||||
};
|
||||
|
||||
const markdown = {
|
||||
@@ -103,22 +101,19 @@ export const lspTheme = EditorView.theme({
|
||||
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
|
||||
fontWeight: "var(--fw-code, 400)",
|
||||
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
|
||||
// CodeMirror anchors the popup at the completed word's start. Pull it left by one row's
|
||||
// leading inset so the labels, not the icon column, sit on the text. CodeMirror's horizontal
|
||||
// clamp measures the border box (margins excluded), so this offset sits outside its math:
|
||||
// near the right edge it leaves that much extra space, and a word starting within one inset
|
||||
// of the viewport's left edge would let the popup clip there. The normal editor layout
|
||||
// (gutter + project sidebar) keeps the word well clear of that edge.
|
||||
marginLeft:
|
||||
"calc(-1 * (1px + var(--cm-completion-edge) + var(--cm-completion-inset) + var(--cm-completion-icon) + var(--cm-completion-gap)))",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
width: "max-content",
|
||||
maxWidth: "min(720px, var(--cm-completion-max-width, 100vw))",
|
||||
// No overflow clipping: CodeMirror nests the documentation pane in this box and
|
||||
// positions it outside it (see `positionCompletionInfo`). The footer rounds itself.
|
||||
},
|
||||
".cm-tooltip.cm-tooltip-autocomplete.cm-lsp-completion > ul": {
|
||||
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
|
||||
fontWeight: "var(--fw-code, 400)",
|
||||
minWidth: "420px",
|
||||
maxWidth: "min(720px, 80vw)",
|
||||
minWidth: "0",
|
||||
maxWidth: "100%",
|
||||
height: "auto",
|
||||
maxHeight: "calc(var(--cm-completion-row) * 11 + 8px)",
|
||||
padding: "4px 0",
|
||||
},
|
||||
@@ -153,9 +148,15 @@ export const lspTheme = EditorView.theme({
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
".cm-lsp-completion .cm-completionLabel": { flex: "none", overflow: "hidden", textOverflow: "ellipsis" },
|
||||
".cm-lsp-completion .cm-completionLabel": {
|
||||
flex: "0 1 auto",
|
||||
minWidth: "0",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
},
|
||||
".cm-lsp-completion .cm-completionDetail": {
|
||||
flex: "0 1 auto",
|
||||
minWidth: "0",
|
||||
marginLeft: "0",
|
||||
fontStyle: "normal",
|
||||
color: "var(--fg-subtle)",
|
||||
@@ -172,7 +173,8 @@ export const lspTheme = EditorView.theme({
|
||||
marginLeft: "calc(-1 * var(--cm-completion-gap))",
|
||||
},
|
||||
".cm-lsp-completion .cm-lsp-type": {
|
||||
flex: "1 0 auto",
|
||||
flex: "0 1 auto",
|
||||
minWidth: "0",
|
||||
maxWidth: "60%",
|
||||
marginLeft: "auto",
|
||||
paddingLeft: "16px",
|
||||
@@ -188,18 +190,21 @@ export const lspTheme = EditorView.theme({
|
||||
},
|
||||
".cm-lsp-completion-footer": {
|
||||
display: "flex",
|
||||
flex: "none",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
padding: "5px 12px",
|
||||
backgroundColor: "var(--bg-popup-inline, var(--bg-elev))",
|
||||
color: "var(--fg-subtle)",
|
||||
fontFamily: "var(--font-ui)",
|
||||
fontSize: "var(--fs-small)",
|
||||
whiteSpace: "nowrap",
|
||||
gap: "12px",
|
||||
gap: "var(--space-1) var(--space-3)",
|
||||
justifyContent: "space-between",
|
||||
borderRadius: "0 0 calc(var(--radius-popup) - 1px) calc(var(--radius-popup) - 1px)",
|
||||
},
|
||||
".cm-lsp-completion-sort": {
|
||||
flex: "none",
|
||||
maxWidth: "100%",
|
||||
padding: "0",
|
||||
border: "none",
|
||||
background: "none",
|
||||
|
||||
Reference in new issue
Заблокувати користувача