/** * Rules of the settings dialog's text control for string settings (H4): * which string settings are paths (they get a "Browse…" button), what the * field shows while empty, and the checks made before asking the engine. * * The rules work on any string setting `settings.list` reports, so a new * one (such as `git.executable`) gets the control without changes here. * The engine still validates every value; these checks only catch mistakes * early and say how to fix them. */ import { t } from "../../i18n"; import type { SettingDef } from "../../stores/settings"; /** Longest value in UTF-8 bytes; the engine's limit for string settings. */ export const MAX_STRING_BYTES = 4096; /** Endings of a key's last segment that mark a path setting. */ const PATH_ENDINGS = ["path", "executable"]; /** * Whether a text has control characters (U+0000–U+001F, U+007F), which no * single-line setting needs. * * @param text - the text. */ function hasControlChars(text: string): boolean { for (let i = 0; i < text.length; i += 1) { const code = text.charCodeAt(i); if (code < 0x20 || code === 0x7f) { return true; } } return false; } /** * Whether a setting holds a file path: a string setting whose key ends in * `path` or `executable` (`phpactor.path`, `php.executable`, * `git.executable`, `x.pharPath`). * * @param def - the setting. */ export function isPathSetting(def: SettingDef): boolean { if (def.type !== "string") { return false; } const last = (def.key.split(".").at(-1) ?? "").toLowerCase(); return PATH_ENDINGS.some((ending) => last.endsWith(ending)); } /** * What an empty text field shows: "Detected automatically" for a path * setting whose default is empty (the engine then looks for the tool * itself), nothing otherwise. * * @param def - the setting. */ export function placeholderOf(def: SettingDef): string { return isPathSetting(def) && def.default === "" ? t("settings.hint.pathAuto") : ""; } /** * Checks a typed value before it goes to `settings.set`. * * - Longer than {@link MAX_STRING_BYTES} UTF-8 bytes, or with control * characters: refused for every string setting. * - Paths: refused when wrapped in quotes (as copied from a shell or the * file manager) or with spaces at either end. * * @param def - the setting. * @param text - the typed value. * @returns the error text from the catalog, or null when the value may be sent. */ export function checkString(def: SettingDef, text: string): string | null { if (new TextEncoder().encode(text).length > MAX_STRING_BYTES) { return t("settings.error.stringTooLong", { max: MAX_STRING_BYTES }); } if (hasControlChars(text)) { return t("settings.error.stringControl"); } if (!isPathSetting(def)) { return null; } if (/^\s*(["']).*\1\s*$/.test(text) && text.trim().length >= 2) { return t("settings.error.pathQuoted"); } if (text !== text.trim()) { return t("settings.error.pathSpaces"); } return null; }