From 2bb93366bbe5d08dce5a0bf19fe0d3af005b540d Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 14:27:01 +0800 Subject: [PATCH] fix(editor): show encodings in one searchable picker (#4697) The status-bar encoding item opens a searchable Change File Encoding popup (checked current encoding, BOM toggle, link to File Encodings settings). Picking an encoding asks whether to reload the file in it or convert the current text on save. --- src/editor/core/view/EditorArea.module.css | 26 ++++ src/editor/core/view/StatusItems.tsx | 149 +++++++++++++------ src/editor/core/view/encodingStatus.test.tsx | 63 ++++++-- src/platform/locales/text/en.json | 4 + src/platform/locales/text/zh.json | 4 + 5 files changed, 188 insertions(+), 58 deletions(-) diff --git a/src/editor/core/view/EditorArea.module.css b/src/editor/core/view/EditorArea.module.css index 86c654ecf..17a4bcf8a 100644 --- a/src/editor/core/view/EditorArea.module.css +++ b/src/editor/core/view/EditorArea.module.css @@ -356,6 +356,32 @@ align-items: center; } +.encodingPopup { + width: 264px; + padding-block: var(--space-1); +} +.encodingHeading { + padding: var(--space-1) var(--space-3) 0; + color: var(--fg-strong); + font-size: var(--fs-ui); + font-weight: 600; +} +.encodingCommands { + display: flex; + flex-direction: column; + margin-top: var(--space-1); + padding: var(--space-1) var(--space-1-5) 0; + border-top: 1px solid var(--border-popup); +} +.encodingCommands button { + justify-content: flex-start; + height: auto; + min-height: var(--h-list-row); + padding-block: var(--space-1); + text-align: left; + white-space: normal; +} + /* tab drag & drop target on the editor */ .dropZone { position: absolute; diff --git a/src/editor/core/view/StatusItems.tsx b/src/editor/core/view/StatusItems.tsx index cf3eaaada..51a896e44 100644 --- a/src/editor/core/view/StatusItems.tsx +++ b/src/editor/core/view/StatusItems.tsx @@ -6,7 +6,18 @@ import { executeAction } from "@/platform/actions"; import { shortcutLabel } from "@/platform/keymap"; import { basename, dirname, projectFolder, relativePath, useProject } from "@/platform/project"; import type { LineEnding, OutlineItem } from "@/platform/ipc"; -import { BarButton, Icon, Menu, badgeKind, fileIconName, revealHorizontally } from "@/ui"; +import { + BarButton, + Button, + Dialog, + Icon, + Menu, + Popup, + SelectListbox, + badgeKind, + fileIconName, + revealHorizontally, +} from "@/ui"; import { notifications, useProjectViewLead } from "@/workbench/contributions"; import { useDistractionFree } from "@/workbench/distractionFree"; import { ENCODING_CHOICES, useEditorPrefs } from "@/platform/editorSettings"; @@ -19,12 +30,12 @@ import { untitledTitle, } from "@/platform/virtualDocs"; import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs } from "../controller"; -import { useDocMeta, useOutline } from "../model/document"; +import { useDocMeta, useOutline, type DocMeta } from "../model/document"; import { symbolChain } from "./outline"; import { NavChildrenPopup } from "./NavBarPopup"; import type { NavSegment } from "./navBar"; import styles from "./EditorArea.module.css"; -import { tx } from "@/platform/i18n"; +import { tx, useTx } from "@/platform/i18n"; function useActiveMeta() { const path = useEditorStatus((s) => s.status?.path ?? null); @@ -438,18 +449,25 @@ export function LineEndingStatus() { ); } -const ENCODINGS = ENCODING_CHOICES; +const ENCODINGS = ENCODING_CHOICES.map(([value, label]) => ({ value, label, verbatim: true })); -/** File encoding widget (IDEA: click → choose an encoding, then Reload or Convert). */ export function EncodingStatus() { const meta = useActiveMeta(); + return meta ? : null; +} + +function EncodingPicker({ meta }: { meta: DocMeta }) { const prefs = useEditorPrefs(); + const tx = useTx(); const [open, setOpen] = useState(false); + const [target, setTarget] = useState<(typeof ENCODINGS)[number] | null>(null); const ref = useRef(null); - if (!meta) return null; + const canReload = meta.canReloadEncoding && !meta.dirty; + const canConvert = !meta.readOnly; const apply = (encoding: string, reload: boolean) => { + setTarget(null); const model = editorController().manager.get(meta.path); - if (!model) return; + if (!model || !(reload ? canReload : canConvert)) return; void editorController() .manager.backend.setEncoding(meta.doc, encoding, reload) .then((enc) => { @@ -468,7 +486,7 @@ export function EncodingStatus() { const current = meta.encoding.toLowerCase(); const nativeToAsciiProperties = prefs.encodings.nativeToAscii && meta.path.endsWith(".properties"); const canToggleBom = current === "utf-8" && !nativeToAsciiProperties; - const label = ENCODINGS.find(([id]) => id === current)?.[1] ?? meta.encoding; + const label = ENCODINGS.find(({ value }) => value === current)?.label ?? meta.encoding; const applyBom = (hasBom: boolean) => { const controller = editorController(); const model = controller.manager.get(meta.path); @@ -487,56 +505,99 @@ export function EncodingStatus() { }), ); }; - const group = (reload: boolean) => - ENCODINGS.filter(([id]) => id !== current).map(([id, label]) => ({ - id: `${reload ? "reload" : "convert"}.${id}`, - label, - run: () => apply(id, reload), - })); + const chooseEncoding = (value: string) => { + setOpen(false); + if (value === current) return; + ref.current?.focus({ preventScroll: true }); + setTarget(ENCODINGS.find((option) => option.value === value) ?? null); + }; + const encodings = + canReload || canConvert + ? ENCODINGS + : ENCODINGS.map((option) => ({ ...option, disabled: option.value !== current })); return ( <> setOpen((v) => !v)} > {meta.hasBom ? `${label} BOM` : label} - setOpen(false)} anchor={ref} placement="top-end" - aria-label="File encoding" - items={[ - { - id: "reload", - label: "Reload with Encoding", - disabled: meta.dirty || !meta.canReloadEncoding, - submenu: group(true), - }, - { id: "convert", label: "Convert to Encoding", disabled: meta.readOnly, submenu: group(false) }, - ...(canToggleBom - ? [ - { kind: "separator" as const }, - { - id: "toggle-bom", - label: meta.hasBom ? "Remove UTF-8 BOM" : "Add UTF-8 BOM", - disabled: meta.readOnly, - run: () => applyBom(!meta.hasBom), - }, - ] - : []), - { kind: "separator" }, - { - id: "configure", - label: "File Encodings Settings…", - run: () => void executeAction("file.settings", "editor.fileEncodings"), - }, - ]} - /> + aria-label={tx("File encoding")} + className={styles.encodingPopup} + trapFocus + > +
{tx("Change File Encoding")}
+ +
+ {canToggleBom && ( + + )} + +
+ + {target && ( + setTarget(null)} + buttons={[ + { + label: "Reload", + title: "Reload with Encoding", + disabled: !canReload, + onClick: () => apply(target.value, true), + }, + { + label: "Convert", + title: "Convert to Encoding", + disabled: !canConvert, + onClick: () => apply(target.value, false), + }, + { label: "Cancel", role: "cancel", autoFocus: true }, + ]} + > + {tx`Use ${target.label} for this file?`} + {"\n"} + {tx("Reload reads the file again. Convert keeps the current text and changes its encoding on save.")} + + )} ); } diff --git a/src/editor/core/view/encodingStatus.test.tsx b/src/editor/core/view/encodingStatus.test.tsx index 016b9d4c4..272580246 100644 --- a/src/editor/core/view/encodingStatus.test.tsx +++ b/src/editor/core/view/encodingStatus.test.tsx @@ -48,7 +48,7 @@ const meta = (patch: Partial = {}): DocMeta => ({ ...patch, }); -const openMenu = (m: DocMeta) => { +const openPicker = (m: DocMeta) => { useDocMeta.setState({ [m.path]: m }); useEditorStatus.setState({ status: { path: m.path, doc: m.doc, line: 0, col: 0, offset: 0, selectedChars: 0, selectedLines: 0, carets: 1 }, @@ -58,7 +58,8 @@ const openMenu = (m: DocMeta) => { return view; }; -const item = (name: string) => screen.getByRole("menuitem", { name }); +const choose = (name: string) => fireEvent.click(screen.getByRole("option", { name })); +const button = (name: string) => screen.getByRole("button", { name }); beforeEach(() => { vi.clearAllMocks(); @@ -68,33 +69,67 @@ beforeEach(() => { describe("encoding status of read-only library documents", () => { it("offers Reload for re-decodable sources, but never Convert or BOM changes", () => { - const view = openMenu(meta()); - expect(item("Reload with Encoding").getAttribute("aria-disabled")).toBeNull(); - expect(item("Convert to Encoding").getAttribute("aria-disabled")).toBe("true"); - expect(item("Add UTF-8 BOM").getAttribute("aria-disabled")).toBe("true"); + const view = openPicker(meta()); + expect(button("Add UTF-8 BOM").disabled).toBe(true); + choose("GBK"); + expect(button("Reload").disabled).toBe(false); + expect(button("Convert").disabled).toBe(true); view.unmount(); }); - it("disables Reload for server-generated content that cannot be re-decoded", () => { - const view = openMenu(meta({ canReloadEncoding: false })); - expect(item("Reload with Encoding").getAttribute("aria-disabled")).toBe("true"); + it("disables encoding changes for server-generated read-only content", () => { + const view = openPicker(meta({ canReloadEncoding: false })); + expect(screen.getByRole("option", { name: "GBK" }).querySelector("[aria-disabled=true]")).not.toBeNull(); + choose("GBK"); + expect(screen.queryByRole("dialog", { name: "Change File Encoding" })).toBeNull(); + expect(setEncoding).not.toHaveBeenCalled(); view.unmount(); }); it("keeps Reload disabled while a file has unsaved changes", () => { - const view = openMenu(meta({ path: "/p/Main.java", readOnly: false, dirty: true })); - expect(item("Reload with Encoding").getAttribute("aria-disabled")).toBe("true"); + const view = openPicker(meta({ path: "/p/Main.java", readOnly: false, dirty: true })); + choose("GBK"); + expect(button("Reload").disabled).toBe(true); + expect(button("Convert").disabled).toBe(false); view.unmount(); }); it("reloading a virtual document re-decodes it and refreshes the content cache", async () => { setEncoding.mockResolvedValue({ encoding: "gbk", hasBom: false }); - const view = openMenu(meta()); - fireEvent.mouseEnter(item("Reload with Encoding")); - fireEvent.click(await screen.findByRole("menuitem", { name: "GBK" })); + const view = openPicker(meta()); + choose("GBK"); + fireEvent.click(button("Reload")); expect(setEncoding).toHaveBeenCalledWith(1, "gbk", true); await waitFor(() => expect(setMeta).toHaveBeenCalledWith({ encoding: "gbk", hasBom: false })); expect(invalidateVirtualDocument).toHaveBeenCalledWith(JDT); view.unmount(); }); }); + +it("filters encodings by typing and allows cancelling without a document change", () => { + const view = openPicker(meta({ readOnly: false })); + const search = screen.getByPlaceholderText("Search…"); + expect(document.activeElement).toBe(search); + expect(screen.getByRole("option", { name: "UTF-8" })).toBeTruthy(); + fireEvent.change(search, { target: { value: "1252" } }); + expect(screen.queryByRole("option", { name: "GBK" })).toBeNull(); + fireEvent.keyDown(search, { key: "Enter" }); + const cancel = button("Cancel"); + expect(document.activeElement).toBe(cancel); + expect(setEncoding).not.toHaveBeenCalled(); + fireEvent.keyDown(cancel, { key: "Escape" }); + expect(screen.queryByRole("dialog", { name: "Change File Encoding" })).toBeNull(); + expect(setEncoding).not.toHaveBeenCalled(); + expect(document.activeElement).toBe(button("UTF-8")); + view.unmount(); +}); + +it("converts the current text when Convert is chosen", async () => { + setEncoding.mockResolvedValue({ encoding: "gbk", hasBom: false }); + const view = openPicker(meta({ path: "/p/Main.java", readOnly: false })); + choose("GBK"); + fireEvent.click(button("Convert")); + expect(setEncoding).toHaveBeenCalledWith(1, "gbk", false); + await waitFor(() => expect(setMeta).toHaveBeenCalledWith({ encoding: "gbk", hasBom: false, dirty: true })); + view.unmount(); +}); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7a07a6463..5a421b560 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2731,6 +2731,10 @@ "Code Structure": "Code Structure", "Presentation": "Presentation", "Code Assistance": "Code Assistance", + "Change File Encoding": "Change File Encoding", + "Convert": "Convert", + "Use {label} for this file?": "Use {label} for this file?", + "Reload reads the file again. Convert keeps the current text and changes its encoding on save.": "Reload reads the file again. Convert keeps the current text and changes its encoding on save.", "Managed version {version} in {location}": "Managed version {version} in {location}", "Managed in {location}": "Managed in {location}", "{name} changed on disk": "{name} changed on disk", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 843f8ba87..207e227ad 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9096,6 +9096,10 @@ "GitHub account": "GitHub 账号", "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。", "github-username": "GitHub 用户名", + "Change File Encoding": "更改文件编码", + "Convert": "转换", + "Use {label} for this file?": "对此文件使用 {label} 编码?", + "Reload reads the file again. Convert keeps the current text and changes its encoding on save.": "重新加载会用所选编码重新读取文件。转换会保留当前文本,并在保存时使用所选编码。", "Managed version {version} in {location}": "版本 {version} 由 {location} 管理", "Managed in {location}": "由 {location} 管理", "{name} changed on disk": "{name} 已在磁盘上更改",