mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-01-29 00:35:38 +08:00
fix: monaco editor line count limit
This commit is contained in:
@@ -7,6 +7,7 @@
|
|||||||
- macOS 非预期 Tproxy 端口设置
|
- macOS 非预期 Tproxy 端口设置
|
||||||
- 流量图缩放异常
|
- 流量图缩放异常
|
||||||
- PAC 自动代理脚本内容无法动态调整
|
- PAC 自动代理脚本内容无法动态调整
|
||||||
|
- Monaco 编辑器的行数上限
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||||
|
|||||||
@@ -21,7 +21,11 @@ export const BaseLoadingOverlay: React.FC<BaseLoadingOverlayProps> = ({
|
|||||||
display: "flex",
|
display: "flex",
|
||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
backgroundColor: "rgba(255, 255, 255, 0.7)",
|
// Respect current theme; avoid bright flash in dark mode
|
||||||
|
backgroundColor: (theme) =>
|
||||||
|
theme.palette.mode === "dark"
|
||||||
|
? "rgba(0, 0, 0, 0.5)"
|
||||||
|
: "rgba(255, 255, 255, 0.7)",
|
||||||
zIndex: 1000,
|
zIndex: 1000,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -21,10 +21,11 @@ import metaSchema from "meta-json-schema/schemas/meta-json-schema.json";
|
|||||||
import * as monaco from "monaco-editor";
|
import * as monaco from "monaco-editor";
|
||||||
import { configureMonacoYaml } from "monaco-yaml";
|
import { configureMonacoYaml } from "monaco-yaml";
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
import { ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
import { ReactNode, useEffect, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import pac from "types-pac/pac.d.ts?raw";
|
import pac from "types-pac/pac.d.ts?raw";
|
||||||
|
|
||||||
|
import { BaseLoadingOverlay } from "@/components/base";
|
||||||
import { showNotice } from "@/services/noticeService";
|
import { showNotice } from "@/services/noticeService";
|
||||||
import { useThemeMode } from "@/services/states";
|
import { useThemeMode } from "@/services/states";
|
||||||
import debounce from "@/utils/debounce";
|
import debounce from "@/utils/debounce";
|
||||||
@@ -42,12 +43,16 @@ interface LanguageSchemaMap {
|
|||||||
interface Props<T extends Language> {
|
interface Props<T extends Language> {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
title?: string | ReactNode;
|
title?: string | ReactNode;
|
||||||
initialData: Promise<string>;
|
// Initial content loader: prefer passing a stable function. A plain Promise is supported,
|
||||||
|
// but it won't trigger background refreshes and should be paired with a stable `dataKey`.
|
||||||
|
initialData: Promise<string> | (() => Promise<string>);
|
||||||
|
// Logical document id; reloads when this or language/schema changes.
|
||||||
|
dataKey?: string | number;
|
||||||
readOnly?: boolean;
|
readOnly?: boolean;
|
||||||
language: T;
|
language: T;
|
||||||
schema?: Schema<T>;
|
schema?: Schema<T>;
|
||||||
onChange?: (prev?: string, curr?: string) => void;
|
onChange?: (prev?: string, curr?: string) => void;
|
||||||
onSave?: (prev?: string, curr?: string) => void;
|
onSave?: (prev?: string, curr?: string) => void | Promise<void>;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +60,7 @@ let initialized = false;
|
|||||||
const monacoInitialization = () => {
|
const monacoInitialization = () => {
|
||||||
if (initialized) return;
|
if (initialized) return;
|
||||||
|
|
||||||
// configure yaml worker
|
// YAML worker and schemas
|
||||||
configureMonacoYaml(monaco, {
|
configureMonacoYaml(monaco, {
|
||||||
validate: true,
|
validate: true,
|
||||||
enableSchemaRequest: true,
|
enableSchemaRequest: true,
|
||||||
@@ -74,7 +79,7 @@ const monacoInitialization = () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
// configure PAC definition
|
// PAC type definitions for JS suggestions
|
||||||
monaco.languages.typescript.javascriptDefaults.addExtraLib(pac, "pac.d.ts");
|
monaco.languages.typescript.javascriptDefaults.addExtraLib(pac, "pac.d.ts");
|
||||||
|
|
||||||
initialized = true;
|
initialized = true;
|
||||||
@@ -89,6 +94,7 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
open = false,
|
open = false,
|
||||||
title,
|
title,
|
||||||
initialData,
|
initialData,
|
||||||
|
dataKey,
|
||||||
readOnly = false,
|
readOnly = false,
|
||||||
language = "yaml",
|
language = "yaml",
|
||||||
schema,
|
schema,
|
||||||
@@ -98,39 +104,223 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
const resolvedTitle = title ?? t("profiles.components.menu.editFile");
|
const resolvedTitle = title ?? t("profiles.components.menu.editFile");
|
||||||
const resolvedInitialData = useMemo(
|
|
||||||
() => initialData ?? Promise.resolve(""),
|
|
||||||
[initialData],
|
|
||||||
);
|
|
||||||
|
|
||||||
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor>(undefined);
|
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor>(undefined);
|
||||||
const prevData = useRef<string | undefined>("");
|
const prevData = useRef<string | undefined>("");
|
||||||
const currData = useRef<string | undefined>("");
|
const currData = useRef<string | undefined>("");
|
||||||
|
// Hold the latest loader without making effects depend on its identity
|
||||||
|
const initialDataRef = useRef<Props<T>["initialData"]>(initialData);
|
||||||
|
// Track mount/open state to prevent setState after unmount/close
|
||||||
|
const isMountedRef = useRef(true);
|
||||||
|
const openRef = useRef(open);
|
||||||
|
useEffect(() => {
|
||||||
|
openRef.current = open;
|
||||||
|
}, [open]);
|
||||||
|
useEffect(() => {
|
||||||
|
isMountedRef.current = true;
|
||||||
|
return () => {
|
||||||
|
isMountedRef.current = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
const [initialText, setInitialText] = useState<string | null>(null);
|
||||||
|
const [modelPath, setModelPath] = useState<string>("");
|
||||||
|
const modelChangeDisposableRef = useRef<monaco.IDisposable | null>(null);
|
||||||
|
// Unique per-component instance id to avoid shared Monaco models across dialogs
|
||||||
|
const instanceIdRef = useRef<string>(nanoid());
|
||||||
|
// Disable actions while loading or before modelPath is ready
|
||||||
|
const isLoading = initialText === null || !modelPath;
|
||||||
|
// Track if background refresh failed; offer a retry action in UI
|
||||||
|
const [refreshFailed, setRefreshFailed] = useState<unknown | null>(null);
|
||||||
|
// Skip the first background refresh triggered by [open, modelPath, dataKey]
|
||||||
|
// to avoid double-invoking the loader right after the initial load.
|
||||||
|
const skipNextRefreshRef = useRef(false);
|
||||||
|
// Monotonic token to cancel stale background refreshes
|
||||||
|
const reloadTokenRef = useRef(0);
|
||||||
|
// Track whether the editor has a usable baseline (either loaded or fallback).
|
||||||
|
// This avoids saving before the model/path are ready, while still allowing recovery
|
||||||
|
// when the initial load fails but an empty buffer is presented.
|
||||||
|
const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
|
||||||
|
// Editor should only be read-only when explicitly requested by prop.
|
||||||
|
// A refresh/load failure must not lock the editor to allow manual recovery.
|
||||||
|
const effectiveReadOnly = readOnly;
|
||||||
|
// Keep ref in sync with prop without triggering loads
|
||||||
|
useEffect(() => {
|
||||||
|
initialDataRef.current = initialData;
|
||||||
|
}, [initialData]);
|
||||||
|
// Background refresh: when the dialog/model is ready and the underlying resource key changes,
|
||||||
|
// try to refresh content (only if user hasn't typed). Do NOT depend on `initialData` function
|
||||||
|
// identity because callers often pass inline lambdas that change every render.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
// Only attempt after initial model is ready to avoid racing the initial load
|
||||||
|
if (!modelPath) return;
|
||||||
|
// Avoid immediate double-load on open: the initial load has just completed.
|
||||||
|
if (skipNextRefreshRef.current) {
|
||||||
|
skipNextRefreshRef.current = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Only meaningful when a callable loader is provided (plain Promise cannot be "recalled")
|
||||||
|
if (typeof initialDataRef.current === "function") {
|
||||||
|
void reloadLatest();
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open, modelPath, dataKey]);
|
||||||
|
// Helper to (soft) reload latest source and apply only if the user hasn't typed yet
|
||||||
|
const reloadLatest = useLockFn(async () => {
|
||||||
|
// Snapshot the model/doc identity and bump a token so older calls can't win
|
||||||
|
const myToken = ++reloadTokenRef.current;
|
||||||
|
const expectedModelPath = modelPath;
|
||||||
|
const expectedKey = dataKey;
|
||||||
|
if (isMountedRef.current && openRef.current) {
|
||||||
|
// Clear previous error (UI hint) at the start of a new attempt
|
||||||
|
setRefreshFailed(null);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const src = initialDataRef.current;
|
||||||
|
const promise =
|
||||||
|
typeof src === "function"
|
||||||
|
? (src as () => Promise<string>)()
|
||||||
|
: (src ?? Promise.resolve(""));
|
||||||
|
const next = await promise;
|
||||||
|
// Abort if component/dialog state changed meanwhile:
|
||||||
|
// - unmounted or closed
|
||||||
|
// - document switched (modelPath/dataKey no longer match)
|
||||||
|
// - a newer reload was started
|
||||||
|
if (
|
||||||
|
!isMountedRef.current ||
|
||||||
|
!openRef.current ||
|
||||||
|
expectedModelPath !== modelPath ||
|
||||||
|
expectedKey !== dataKey ||
|
||||||
|
myToken !== reloadTokenRef.current
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Only update when untouched and value changed
|
||||||
|
const userUntouched = currData.current === prevData.current;
|
||||||
|
if (userUntouched && next !== prevData.current) {
|
||||||
|
prevData.current = next;
|
||||||
|
currData.current = next;
|
||||||
|
editorRef.current?.setValue(next);
|
||||||
|
}
|
||||||
|
// Ensure any previous error state is cleared after a successful refresh
|
||||||
|
if (isMountedRef.current && openRef.current) {
|
||||||
|
setRefreshFailed(null);
|
||||||
|
}
|
||||||
|
// If we previously failed to load, a successful refresh establishes a valid baseline
|
||||||
|
if (isMountedRef.current && openRef.current) {
|
||||||
|
setHasLoadedOnce(true);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Only report if still mounted/open and this call is the latest
|
||||||
|
if (
|
||||||
|
isMountedRef.current &&
|
||||||
|
openRef.current &&
|
||||||
|
myToken === reloadTokenRef.current
|
||||||
|
) {
|
||||||
|
setRefreshFailed(err ?? true);
|
||||||
|
showNotice.error(
|
||||||
|
"shared.feedback.notifications.common.refreshFailed",
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const beforeMount = () => {
|
const beforeMount = () => {
|
||||||
monacoInitialization(); // initialize monaco
|
monacoInitialization();
|
||||||
};
|
};
|
||||||
|
|
||||||
const onMount = async (editor: monaco.editor.IStandaloneCodeEditor) => {
|
// Prepare initial content and a stable model path for monaco-react
|
||||||
editorRef.current = editor;
|
/* eslint-disable @eslint-react/hooks-extra/no-direct-set-state-in-use-effect */
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
let cancelled = false;
|
||||||
|
// Clear state up-front to avoid showing stale content while loading
|
||||||
|
setInitialText(null);
|
||||||
|
setModelPath("");
|
||||||
|
// Clear any stale refresh error when starting a new load
|
||||||
|
setRefreshFailed(null);
|
||||||
|
// Reset initial-load success flag on open/start
|
||||||
|
setHasLoadedOnce(false);
|
||||||
|
// We will perform an explicit initial load below; skip the first background refresh.
|
||||||
|
skipNextRefreshRef.current = true;
|
||||||
|
prevData.current = undefined;
|
||||||
|
currData.current = undefined;
|
||||||
|
|
||||||
// retrieve initial data
|
(async () => {
|
||||||
await resolvedInitialData.then((data) => {
|
try {
|
||||||
|
const dataSource = initialDataRef.current;
|
||||||
|
const dataPromise =
|
||||||
|
typeof dataSource === "function"
|
||||||
|
? (dataSource as () => Promise<string>)()
|
||||||
|
: (dataSource ?? Promise.resolve(""));
|
||||||
|
const data = await dataPromise;
|
||||||
|
if (cancelled) return;
|
||||||
prevData.current = data;
|
prevData.current = data;
|
||||||
currData.current = data;
|
currData.current = data;
|
||||||
|
|
||||||
// create and set model
|
setInitialText(data);
|
||||||
const uri = monaco.Uri.parse(`${nanoid()}.${schema}.${language}`);
|
// Build a path that matches YAML schemas when applicable, and avoids "undefined" in name
|
||||||
const model = monaco.editor.createModel(data, language, uri);
|
const pathParts = [String(dataKey ?? nanoid()), instanceIdRef.current];
|
||||||
editorRef.current?.setModel(model);
|
if (schema) pathParts.push(String(schema));
|
||||||
|
pathParts.push(language);
|
||||||
|
|
||||||
|
setModelPath(pathParts.join("."));
|
||||||
|
// Successful initial load should clear any previous refresh error flag
|
||||||
|
setRefreshFailed(null);
|
||||||
|
// Mark that we have a valid baseline content
|
||||||
|
setHasLoadedOnce(true);
|
||||||
|
} catch (err) {
|
||||||
|
if (cancelled) return;
|
||||||
|
// Notify the error and still show an empty editor so the user isn't stuck
|
||||||
|
showNotice.error(err);
|
||||||
|
|
||||||
|
// Align refs with fallback text after a load failure
|
||||||
|
prevData.current = "";
|
||||||
|
currData.current = "";
|
||||||
|
|
||||||
|
setInitialText("");
|
||||||
|
const pathParts = [String(dataKey ?? nanoid()), instanceIdRef.current];
|
||||||
|
if (schema) pathParts.push(String(schema));
|
||||||
|
pathParts.push(language);
|
||||||
|
|
||||||
|
setModelPath(pathParts.join("."));
|
||||||
|
// Mark refresh failure so users can retry
|
||||||
|
setRefreshFailed(err ?? true);
|
||||||
|
// Initial load failed; keep `hasLoadedOnce` false to prevent accidental save
|
||||||
|
// of an empty buffer. It will be enabled on successful refresh or first edit.
|
||||||
|
setHasLoadedOnce(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [open, dataKey, language, schema]);
|
||||||
|
/* eslint-enable @eslint-react/hooks-extra/no-direct-set-state-in-use-effect */
|
||||||
|
|
||||||
|
const onMount = async (editor: monaco.editor.IStandaloneCodeEditor) => {
|
||||||
|
editorRef.current = editor;
|
||||||
|
// Dispose previous model when switching (monaco-react creates a fresh model when `path` changes)
|
||||||
|
modelChangeDisposableRef.current?.dispose();
|
||||||
|
modelChangeDisposableRef.current = editor.onDidChangeModel((e) => {
|
||||||
|
if (e.oldModelUrl) {
|
||||||
|
const oldModel = monaco.editor.getModel(e.oldModelUrl);
|
||||||
|
oldModel?.dispose();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
// No refresh on mount; doing so would double-load.
|
||||||
|
// Background refreshes are handled by the [open, modelPath, dataKey] effect.
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleChange = useLockFn(async (_value?: string) => {
|
const handleChange = useLockFn(async (value?: string) => {
|
||||||
try {
|
try {
|
||||||
const value = editorRef.current?.getValue();
|
currData.current = value ?? editorRef.current?.getValue();
|
||||||
currData.current = value;
|
|
||||||
onChange?.(prevData.current, currData.current);
|
onChange?.(prevData.current, currData.current);
|
||||||
|
// If the initial load failed, allow saving after the user makes an edit.
|
||||||
|
if (!hasLoadedOnce) {
|
||||||
|
setHasLoadedOnce(true);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showNotice.error(err);
|
showNotice.error(err);
|
||||||
}
|
}
|
||||||
@@ -138,9 +328,18 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
|
|
||||||
const handleSave = useLockFn(async () => {
|
const handleSave = useLockFn(async () => {
|
||||||
try {
|
try {
|
||||||
if (!readOnly) {
|
// Disallow saving if initial content never loaded successfully to avoid accidental overwrite
|
||||||
currData.current = editorRef.current?.getValue();
|
if (!readOnly && hasLoadedOnce) {
|
||||||
onSave?.(prevData.current, currData.current);
|
// Guard: if the editor/model hasn't mounted, bail out
|
||||||
|
if (!editorRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
currData.current = editorRef.current.getValue();
|
||||||
|
if (onSave) {
|
||||||
|
await onSave(prevData.current, currData.current);
|
||||||
|
// If save succeeds, align prev with current
|
||||||
|
prevData.current = currData.current;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
onClose();
|
onClose();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -156,30 +355,30 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const editorResize = useMemo(
|
|
||||||
() =>
|
|
||||||
debounce(() => {
|
|
||||||
editorRef.current?.layout();
|
|
||||||
setTimeout(() => editorRef.current?.layout(), 500);
|
|
||||||
}, 100),
|
|
||||||
[],
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onResized = debounce(() => {
|
const onResized = debounce(() => {
|
||||||
editorResize();
|
appWindow
|
||||||
appWindow.isMaximized().then((maximized) => {
|
.isMaximized()
|
||||||
setIsMaximized(() => maximized);
|
.then((maximized) => setIsMaximized(() => maximized));
|
||||||
});
|
// Ensure Monaco recalculates layout after window resize/maximize/restore.
|
||||||
|
// automaticLayout is not always sufficient when the parent dialog resizes.
|
||||||
|
try {
|
||||||
|
editorRef.current?.layout();
|
||||||
|
} catch {}
|
||||||
}, 100);
|
}, 100);
|
||||||
const unlistenResized = appWindow.onResized(onResized);
|
const unlistenResized = appWindow.onResized(onResized);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
unlistenResized.then((fn) => fn());
|
unlistenResized.then((fn) => fn());
|
||||||
|
// Clean up editor and model to avoid leaks
|
||||||
|
const model = editorRef.current?.getModel();
|
||||||
editorRef.current?.dispose();
|
editorRef.current?.dispose();
|
||||||
|
model?.dispose();
|
||||||
|
modelChangeDisposableRef.current?.dispose();
|
||||||
|
modelChangeDisposableRef.current = null;
|
||||||
editorRef.current = undefined;
|
editorRef.current = undefined;
|
||||||
};
|
};
|
||||||
}, [editorResize]);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onClose={onClose} maxWidth="xl" fullWidth>
|
<Dialog open={open} onClose={onClose} maxWidth="xl" fullWidth>
|
||||||
@@ -188,42 +387,94 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
<DialogContent
|
<DialogContent
|
||||||
sx={{
|
sx={{
|
||||||
width: "auto",
|
width: "auto",
|
||||||
|
// Give the editor a scrollable height (even in nested dialogs)
|
||||||
height: "calc(100vh - 185px)",
|
height: "calc(100vh - 185px)",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
overflow: "hidden",
|
overflow: "hidden",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<div style={{ position: "relative", flex: "1 1 auto", minHeight: 0 }}>
|
||||||
|
{/* Show overlay while loading or until modelPath is ready */}
|
||||||
|
<BaseLoadingOverlay isLoading={isLoading} />
|
||||||
|
{/* Background refresh failure helper */}
|
||||||
|
{!!refreshFailed && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 8,
|
||||||
|
right: 10,
|
||||||
|
zIndex: 2,
|
||||||
|
display: "flex",
|
||||||
|
gap: 8,
|
||||||
|
alignItems: "center",
|
||||||
|
pointerEvents: "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
color: "var(--mui-palette-warning-main, #ed6c02)",
|
||||||
|
background: "rgba(237,108,2,0.1)",
|
||||||
|
border: "1px solid rgba(237,108,2,0.35)",
|
||||||
|
borderRadius: 6,
|
||||||
|
padding: "2px 8px",
|
||||||
|
fontSize: 12,
|
||||||
|
lineHeight: "20px",
|
||||||
|
userSelect: "text",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("shared.feedback.notifications.common.refreshFailed")}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => reloadLatest()}
|
||||||
|
>
|
||||||
|
{t("shared.actions.retry")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{initialText !== null && modelPath && (
|
||||||
<MonacoEditor
|
<MonacoEditor
|
||||||
|
height="100%"
|
||||||
|
path={modelPath}
|
||||||
language={language}
|
language={language}
|
||||||
|
defaultValue={initialText}
|
||||||
theme={themeMode === "light" ? "light" : "vs-dark"}
|
theme={themeMode === "light" ? "light" : "vs-dark"}
|
||||||
options={{
|
options={{
|
||||||
tabSize: ["yaml", "javascript", "css"].includes(language) ? 2 : 4, // 根据语言类型设置缩进大小
|
automaticLayout: true,
|
||||||
|
tabSize: ["yaml", "javascript", "css"].includes(language)
|
||||||
|
? 2
|
||||||
|
: 4,
|
||||||
minimap: {
|
minimap: {
|
||||||
enabled: document.documentElement.clientWidth >= 1500, // 超过一定宽度显示minimap滚动条
|
enabled: document.documentElement.clientWidth >= 1500,
|
||||||
},
|
},
|
||||||
mouseWheelZoom: true, // 按住Ctrl滚轮调节缩放比例
|
mouseWheelZoom: true,
|
||||||
readOnly: readOnly, // 只读模式
|
readOnly: effectiveReadOnly,
|
||||||
readOnlyMessage: {
|
readOnlyMessage: {
|
||||||
value: t("profiles.modals.editor.messages.readOnly"),
|
value: t("profiles.modals.editor.messages.readOnly"),
|
||||||
}, // 只读模式尝试编辑时的提示信息
|
},
|
||||||
renderValidationDecorations: "on", // 只读模式下显示校验信息
|
renderValidationDecorations: "on",
|
||||||
quickSuggestions: {
|
quickSuggestions: {
|
||||||
strings: true, // 字符串类型的建议
|
strings: true,
|
||||||
comments: true, // 注释类型的建议
|
comments: true,
|
||||||
other: true, // 其他类型的建议
|
other: true,
|
||||||
},
|
},
|
||||||
padding: {
|
padding: {
|
||||||
top: 33, // 顶部padding防止遮挡snippets
|
top: 33, // Top padding to prevent snippet overlap
|
||||||
},
|
},
|
||||||
fontFamily: `Fira Code, JetBrains Mono, Roboto Mono, "Source Code Pro", Consolas, Menlo, Monaco, monospace, "Courier New", "Apple Color Emoji"${
|
fontFamily: `Fira Code, JetBrains Mono, Roboto Mono, "Source Code Pro", Consolas, Menlo, Monaco, monospace, "Courier New", "Apple Color Emoji"${
|
||||||
getSystem() === "windows" ? ", twemoji mozilla" : ""
|
getSystem() === "windows" ? ", twemoji mozilla" : ""
|
||||||
}`,
|
}`,
|
||||||
fontLigatures: false, // 连字符
|
fontLigatures: false,
|
||||||
smoothScrolling: true, // 平滑滚动
|
smoothScrolling: true,
|
||||||
}}
|
}}
|
||||||
beforeMount={beforeMount}
|
beforeMount={beforeMount}
|
||||||
onMount={onMount}
|
onMount={onMount}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<ButtonGroup
|
<ButtonGroup
|
||||||
variant="contained"
|
variant="contained"
|
||||||
@@ -234,6 +485,7 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
color="inherit"
|
color="inherit"
|
||||||
sx={{ display: readOnly ? "none" : "" }}
|
sx={{ display: readOnly ? "none" : "" }}
|
||||||
title={t("profiles.modals.editor.actions.format")}
|
title={t("profiles.modals.editor.actions.format")}
|
||||||
|
disabled={isLoading}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
editorRef.current
|
editorRef.current
|
||||||
?.getAction("editor.action.formatDocument")
|
?.getAction("editor.action.formatDocument")
|
||||||
@@ -248,7 +500,21 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
title={t(
|
title={t(
|
||||||
isMaximized ? "shared.window.minimize" : "shared.window.maximize",
|
isMaximized ? "shared.window.minimize" : "shared.window.maximize",
|
||||||
)}
|
)}
|
||||||
onClick={() => appWindow.toggleMaximize().then(editorResize)}
|
onClick={() =>
|
||||||
|
appWindow
|
||||||
|
.toggleMaximize()
|
||||||
|
.then(() =>
|
||||||
|
appWindow
|
||||||
|
.isMaximized()
|
||||||
|
.then((maximized) => setIsMaximized(maximized)),
|
||||||
|
)
|
||||||
|
.finally(() => {
|
||||||
|
// Nudge a layout in case the resize event batching lags behind
|
||||||
|
try {
|
||||||
|
editorRef.current?.layout();
|
||||||
|
} catch {}
|
||||||
|
})
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{isMaximized ? <CloseFullscreenRounded /> : <OpenInFullRounded />}
|
{isMaximized ? <CloseFullscreenRounded /> : <OpenInFullRounded />}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
@@ -260,7 +526,11 @@ export const EditorViewer = <T extends Language>(props: Props<T>) => {
|
|||||||
{t(readOnly ? "shared.actions.close" : "shared.actions.cancel")}
|
{t(readOnly ? "shared.actions.close" : "shared.actions.cancel")}
|
||||||
</Button>
|
</Button>
|
||||||
{!readOnly && (
|
{!readOnly && (
|
||||||
<Button onClick={handleSave} variant="contained">
|
<Button
|
||||||
|
onClick={handleSave}
|
||||||
|
variant="contained"
|
||||||
|
disabled={isLoading || !hasLoadedOnce}
|
||||||
|
>
|
||||||
{t("shared.actions.save")}
|
{t("shared.actions.save")}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -830,7 +830,8 @@ export const ProfileItem = (props: Props) => {
|
|||||||
{fileOpen && (
|
{fileOpen && (
|
||||||
<EditorViewer
|
<EditorViewer
|
||||||
open={true}
|
open={true}
|
||||||
initialData={readProfileFile(uid)}
|
initialData={() => readProfileFile(uid)}
|
||||||
|
dataKey={uid}
|
||||||
language="yaml"
|
language="yaml"
|
||||||
schema="clash"
|
schema="clash"
|
||||||
onSave={async (prev, curr) => {
|
onSave={async (prev, curr) => {
|
||||||
@@ -876,9 +877,10 @@ export const ProfileItem = (props: Props) => {
|
|||||||
{mergeOpen && (
|
{mergeOpen && (
|
||||||
<EditorViewer
|
<EditorViewer
|
||||||
open={true}
|
open={true}
|
||||||
initialData={readProfileFile(option?.merge ?? "")}
|
initialData={() => readProfileFile(option?.merge ?? "")}
|
||||||
|
dataKey={`merge:${option?.merge ?? ""}`}
|
||||||
language="yaml"
|
language="yaml"
|
||||||
schema="clash"
|
schema="merge"
|
||||||
onSave={async (prev, curr) => {
|
onSave={async (prev, curr) => {
|
||||||
await saveProfileFile(option?.merge ?? "", curr ?? "");
|
await saveProfileFile(option?.merge ?? "", curr ?? "");
|
||||||
onSave?.(prev, curr);
|
onSave?.(prev, curr);
|
||||||
@@ -889,7 +891,8 @@ export const ProfileItem = (props: Props) => {
|
|||||||
{scriptOpen && (
|
{scriptOpen && (
|
||||||
<EditorViewer
|
<EditorViewer
|
||||||
open={true}
|
open={true}
|
||||||
initialData={readProfileFile(option?.script ?? "")}
|
initialData={() => readProfileFile(option?.script ?? "")}
|
||||||
|
dataKey={`script:${option?.script ?? ""}`}
|
||||||
language="javascript"
|
language="javascript"
|
||||||
onSave={async (prev, curr) => {
|
onSave={async (prev, curr) => {
|
||||||
await saveProfileFile(option?.script ?? "", curr ?? "");
|
await saveProfileFile(option?.script ?? "", curr ?? "");
|
||||||
|
|||||||
@@ -181,9 +181,10 @@ export const ProfileMore = (props: Props) => {
|
|||||||
<EditorViewer
|
<EditorViewer
|
||||||
open={true}
|
open={true}
|
||||||
title={t(globalTitles[id])}
|
title={t(globalTitles[id])}
|
||||||
initialData={readProfileFile(id)}
|
initialData={() => readProfileFile(id)}
|
||||||
|
dataKey={id}
|
||||||
language={id === "Merge" ? "yaml" : "javascript"}
|
language={id === "Merge" ? "yaml" : "javascript"}
|
||||||
schema={id === "Merge" ? "clash" : undefined}
|
schema={id === "Merge" ? "merge" : undefined}
|
||||||
onSave={async (prev, curr) => {
|
onSave={async (prev, curr) => {
|
||||||
await saveProfileFile(id, curr ?? "");
|
await saveProfileFile(id, curr ?? "");
|
||||||
onSave?.(prev, curr);
|
onSave?.(prev, curr);
|
||||||
|
|||||||
@@ -31,7 +31,8 @@ export const ConfigViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
<Chip label={t("shared.labels.readOnly")} size="small" />
|
<Chip label={t("shared.labels.readOnly")} size="small" />
|
||||||
</Box>
|
</Box>
|
||||||
}
|
}
|
||||||
initialData={Promise.resolve(runtimeConfig)}
|
initialData={() => Promise.resolve(runtimeConfig)}
|
||||||
|
dataKey="runtime-config"
|
||||||
readOnly
|
readOnly
|
||||||
language="yaml"
|
language="yaml"
|
||||||
schema="clash"
|
schema="clash"
|
||||||
|
|||||||
@@ -617,7 +617,8 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
<EditorViewer
|
<EditorViewer
|
||||||
open={true}
|
open={true}
|
||||||
title={t("settings.modals.sysproxy.actions.editPac")}
|
title={t("settings.modals.sysproxy.actions.editPac")}
|
||||||
initialData={Promise.resolve(value.pac_content ?? "")}
|
initialData={() => Promise.resolve(value.pac_content ?? "")}
|
||||||
|
dataKey="sysproxy-pac"
|
||||||
language="javascript"
|
language="javascript"
|
||||||
onSave={(_prev, curr) => {
|
onSave={(_prev, curr) => {
|
||||||
let pac = DEFAULT_PAC;
|
let pac = DEFAULT_PAC;
|
||||||
|
|||||||
@@ -9,7 +9,14 @@ import {
|
|||||||
useTheme,
|
useTheme,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { useLockFn } from "ahooks";
|
import { useLockFn } from "ahooks";
|
||||||
import { useImperativeHandle, useMemo, useState } from "react";
|
import {
|
||||||
|
useEffect,
|
||||||
|
useImperativeHandle,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
useCallback,
|
||||||
|
} from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { BaseDialog, DialogRef } from "@/components/base";
|
import { BaseDialog, DialogRef } from "@/components/base";
|
||||||
@@ -27,6 +34,11 @@ export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
|||||||
const { verge, patchVerge } = useVerge();
|
const { verge, patchVerge } = useVerge();
|
||||||
const { theme_setting } = verge ?? {};
|
const { theme_setting } = verge ?? {};
|
||||||
const [theme, setTheme] = useState(theme_setting || {});
|
const [theme, setTheme] = useState(theme_setting || {});
|
||||||
|
// Latest theme ref to avoid stale closures when saving CSS
|
||||||
|
const themeRef = useRef(theme);
|
||||||
|
useEffect(() => {
|
||||||
|
themeRef.current = theme;
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
useImperativeHandle(ref, () => ({
|
||||||
open: () => {
|
open: () => {
|
||||||
@@ -55,7 +67,6 @@ export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// default theme
|
|
||||||
const { palette } = useTheme();
|
const { palette } = useTheme();
|
||||||
|
|
||||||
const dt = palette.mode === "light" ? defaultTheme : defaultDarkTheme;
|
const dt = palette.mode === "light" ? defaultTheme : defaultDarkTheme;
|
||||||
@@ -100,6 +111,13 @@ export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
|||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Stable loader that returns a fresh Promise each call so EditorViewer
|
||||||
|
// can retry/refresh and always read the latest staged CSS from state.
|
||||||
|
const loadCss = useCallback(
|
||||||
|
() => Promise.resolve(themeRef.current?.css_injection ?? ""),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
const renderItem = (labelKey: string, key: ThemeKey) => {
|
const renderItem = (labelKey: string, key: ThemeKey) => {
|
||||||
const label = t(labelKey);
|
const label = t(labelKey);
|
||||||
return (
|
return (
|
||||||
@@ -159,11 +177,15 @@ export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
|||||||
<EditorViewer
|
<EditorViewer
|
||||||
open={true}
|
open={true}
|
||||||
title={t("settings.components.verge.theme.dialogs.editCssTitle")}
|
title={t("settings.components.verge.theme.dialogs.editCssTitle")}
|
||||||
initialData={Promise.resolve(theme.css_injection ?? "")}
|
initialData={loadCss}
|
||||||
|
dataKey="theme-css"
|
||||||
language="css"
|
language="css"
|
||||||
onSave={(_prev, curr) => {
|
onSave={async (_prev, curr) => {
|
||||||
theme.css_injection = curr;
|
// Only stage the CSS change locally. Persistence happens
|
||||||
handleChange("css_injection");
|
// when the outer Theme dialog's Save button is pressed.
|
||||||
|
const prevTheme = themeRef.current || {};
|
||||||
|
const nextCss = curr ?? "";
|
||||||
|
setTheme({ ...prevTheme, css_injection: nextCss });
|
||||||
}}
|
}}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setEditorOpen(false);
|
setEditorOpen(false);
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "تم النسخ بنجاح",
|
"copySuccess": "تم النسخ بنجاح",
|
||||||
"saveSuccess": "Configuration saved successfully",
|
"saveSuccess": "Configuration saved successfully",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "فشل التحديث"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "Kopieren erfolgreich",
|
"copySuccess": "Kopieren erfolgreich",
|
||||||
"saveSuccess": "Zufalls-Konfiguration erfolgreich gespeichert",
|
"saveSuccess": "Zufalls-Konfiguration erfolgreich gespeichert",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "Aktualisierung fehlgeschlagen"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "Copy Success",
|
"copySuccess": "Copy Success",
|
||||||
"saveSuccess": "Configuration saved successfully",
|
"saveSuccess": "Configuration saved successfully",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "Refresh failed; showing last loaded value"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "Copia exitosa",
|
"copySuccess": "Copia exitosa",
|
||||||
"saveSuccess": "Configuración aleatoria guardada correctamente",
|
"saveSuccess": "Configuración aleatoria guardada correctamente",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "Error al actualizar"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "کپی با موفقیت انجام شد",
|
"copySuccess": "کپی با موفقیت انجام شد",
|
||||||
"saveSuccess": "Configuration saved successfully",
|
"saveSuccess": "Configuration saved successfully",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "بهروزرسانی ناموفق بود"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "Salin Berhasil",
|
"copySuccess": "Salin Berhasil",
|
||||||
"saveSuccess": "Configuration saved successfully",
|
"saveSuccess": "Configuration saved successfully",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "Penyegaran gagal"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "コピー成功",
|
"copySuccess": "コピー成功",
|
||||||
"saveSuccess": "ランダム設定を保存完了",
|
"saveSuccess": "ランダム設定を保存完了",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "更新に失敗しました"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "복사 성공",
|
"copySuccess": "복사 성공",
|
||||||
"saveSuccess": "설정이 저장되었습니다",
|
"saveSuccess": "설정이 저장되었습니다",
|
||||||
"saveFailed": "설정 저장 실패"
|
"saveFailed": "설정 저장 실패",
|
||||||
|
"refreshFailed": "새로고침 실패"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "Скопировано",
|
"copySuccess": "Скопировано",
|
||||||
"saveSuccess": "Configuration saved successfully",
|
"saveSuccess": "Configuration saved successfully",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "Не удалось обновить"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "Kopyalama Başarılı",
|
"copySuccess": "Kopyalama Başarılı",
|
||||||
"saveSuccess": "Configuration saved successfully",
|
"saveSuccess": "Configuration saved successfully",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "Yenileme başarısız"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "Күчерелде",
|
"copySuccess": "Күчерелде",
|
||||||
"saveSuccess": "Configuration saved successfully",
|
"saveSuccess": "Configuration saved successfully",
|
||||||
"saveFailed": "Failed to save configuration"
|
"saveFailed": "Failed to save configuration",
|
||||||
|
"refreshFailed": "Refresh failed"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "复制成功",
|
"copySuccess": "复制成功",
|
||||||
"saveSuccess": "配置保存成功",
|
"saveSuccess": "配置保存成功",
|
||||||
"saveFailed": "配置保存失败"
|
"saveFailed": "配置保存失败",
|
||||||
|
"refreshFailed": "刷新失败"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -89,7 +89,8 @@
|
|||||||
"common": {
|
"common": {
|
||||||
"copySuccess": "複製成功",
|
"copySuccess": "複製成功",
|
||||||
"saveSuccess": "設定儲存完成",
|
"saveSuccess": "設定儲存完成",
|
||||||
"saveFailed": "設定儲存失敗"
|
"saveFailed": "設定儲存失敗",
|
||||||
|
"refreshFailed": "重整失敗"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
|
|||||||
@@ -706,6 +706,7 @@ export const translationKeys = [
|
|||||||
"shared.feedback.notifications.common.copySuccess",
|
"shared.feedback.notifications.common.copySuccess",
|
||||||
"shared.feedback.notifications.common.saveSuccess",
|
"shared.feedback.notifications.common.saveSuccess",
|
||||||
"shared.feedback.notifications.common.saveFailed",
|
"shared.feedback.notifications.common.saveFailed",
|
||||||
|
"shared.feedback.notifications.common.refreshFailed",
|
||||||
"shared.feedback.validation.config.failed",
|
"shared.feedback.validation.config.failed",
|
||||||
"shared.feedback.validation.config.bootFailed",
|
"shared.feedback.validation.config.bootFailed",
|
||||||
"shared.feedback.validation.config.coreChangeFailed",
|
"shared.feedback.validation.config.coreChangeFailed",
|
||||||
|
|||||||
@@ -1200,6 +1200,7 @@ export interface TranslationResources {
|
|||||||
notifications: {
|
notifications: {
|
||||||
common: {
|
common: {
|
||||||
copySuccess: string;
|
copySuccess: string;
|
||||||
|
refreshFailed: string;
|
||||||
saveFailed: string;
|
saveFailed: string;
|
||||||
saveSuccess: string;
|
saveSuccess: string;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user