H4: string and path settings controls, live completion and tooltip settings
- Settings dialog: every string setting gets a text field with in-place
hints (quotes or spaces around a path, control characters, length);
keys ending in path/executable also get "Browse…" through the dialog
plugin's native picker (new desktop IPC pick_file). git.executable
from M4.1 gets the control without UI changes.
- settings.open {section?, query?} for agents and live checks.
- New keys editor.completion.autoPopup, editor.completion.delayMs and
editor.hover.delayMs; the assist module reads them live through
CodeMirror compartments.
- Tests: engine settings test, control/engine key lists, Vitest for the
controls and the live wiring. Docs: architecture, ui-parity, parity
Settings row, gaps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b0f8550aeb
commit
197d5b7d27
19 changed files with 1149 additions and 41 deletions
|
|
@ -10,7 +10,7 @@ import { renderMarkdown } from "./markdown";
|
|||
import { engineAssistTransport, queryAt } from "./request";
|
||||
import { toHover, type AssistBuffer, type AssistTransport } from "./types";
|
||||
|
||||
/** Milliseconds the pointer rests before the hover is asked for. */
|
||||
/** Default milliseconds the pointer rests before the hover is asked for (`editor.hover.delayMs`). */
|
||||
export const HOVER_DELAY = 350;
|
||||
|
||||
/**
|
||||
|
|
@ -60,10 +60,15 @@ export async function hoverAt(
|
|||
*
|
||||
* @param buffer - the buffer the editor state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
* @param delay - milliseconds the pointer rests before the hover is asked for.
|
||||
*/
|
||||
export function lspHover(buffer: AssistBuffer, transport: AssistTransport = engineAssistTransport): Extension {
|
||||
export function lspHover(
|
||||
buffer: AssistBuffer,
|
||||
transport: AssistTransport = engineAssistTransport,
|
||||
delay: number = HOVER_DELAY,
|
||||
): Extension {
|
||||
return hoverTooltip((view, pos) => hoverAt(view, pos, buffer, transport), {
|
||||
hoverTime: HOVER_DELAY,
|
||||
hoverTime: delay,
|
||||
hideOnChange: true,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,8 +5,10 @@
|
|||
* queries, see `request.ts`).
|
||||
*
|
||||
* {@link assistExtensions} is the hook the editor uses: PHP files of a
|
||||
* buffer get the extensions, everything else none. Colours come from
|
||||
* `--lt-*` tokens only; strings from the catalog.
|
||||
* buffer get the extensions, everything else none. Completion and hover
|
||||
* follow the assist settings live (`settings.ts`: auto popup, completion
|
||||
* delay, hover delay). Colours come from `--lt-*` tokens only; strings
|
||||
* from the catalog.
|
||||
*/
|
||||
import { autocompletion } from "@codemirror/autocomplete";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
|
|
@ -17,6 +19,7 @@ import { itemOf, lspCompletionSource } from "./completion";
|
|||
import { lspHover } from "./hover";
|
||||
import { kindIcon } from "./icons";
|
||||
import { engineAssistTransport } from "./request";
|
||||
import { liveAssistSettings, storeAssistSettings, type AssistSettings, type AssistSettingsSource } from "./settings";
|
||||
import { lspSignatureHelp } from "./signature";
|
||||
import type { AssistBuffer, AssistTransport } from "./types";
|
||||
|
||||
|
|
@ -122,30 +125,48 @@ const assistTheme: Extension = EditorView.theme({
|
|||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The completion extension for given settings: typing opens the list only
|
||||
* with auto popup on, after the completion delay.
|
||||
*
|
||||
* @param buffer - the buffer the editor state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
* @param settings - the assist settings.
|
||||
*/
|
||||
function completionExtension(buffer: AssistBuffer, transport: AssistTransport, settings: AssistSettings): Extension {
|
||||
return autocompletion({
|
||||
override: [lspCompletionSource(buffer, transport)],
|
||||
activateOnTyping: settings.autoPopup,
|
||||
activateOnTypingDelay: settings.completionDelay,
|
||||
icons: false,
|
||||
addToOptions: [{ render: (completion) => kindIcon(completion.type ?? "text"), position: 20 }],
|
||||
optionClass: (completion) => (itemOf.get(completion)?.deprecated === true ? "lt-assist-deprecated" : ""),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The assist extensions of an editor state.
|
||||
*
|
||||
* @param path - project-relative path of the file.
|
||||
* @param buffer - the buffer it shows; none for states without one.
|
||||
* @param transport - how to reach the engine.
|
||||
* @param settings - where the assist settings come from; the settings store by default.
|
||||
* @returns the extensions; empty unless a PHP file of a buffer.
|
||||
*/
|
||||
export function assistExtensions(
|
||||
path: string,
|
||||
buffer: AssistBuffer | undefined,
|
||||
transport: AssistTransport = engineAssistTransport,
|
||||
settings: AssistSettingsSource = storeAssistSettings,
|
||||
): Extension {
|
||||
if (!buffer || languageOf(path) !== "php") {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
autocompletion({
|
||||
override: [lspCompletionSource(buffer, transport)],
|
||||
icons: false,
|
||||
addToOptions: [{ render: (completion) => kindIcon(completion.type ?? "text"), position: 20 }],
|
||||
optionClass: (completion) => (itemOf.get(completion)?.deprecated === true ? "lt-assist-deprecated" : ""),
|
||||
}),
|
||||
lspHover(buffer, transport),
|
||||
liveAssistSettings(settings, [
|
||||
(values) => completionExtension(buffer, transport, values),
|
||||
(values) => lspHover(buffer, transport, values.hoverDelay),
|
||||
]),
|
||||
lspSignatureHelp(buffer, transport),
|
||||
assistTracker(buffer, transport),
|
||||
assistTheme,
|
||||
|
|
|
|||
195
ui/src/components/editor/assist/settings.ts
Normal file
195
ui/src/components/editor/assist/settings.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
/**
|
||||
* The settings of code assistance (H4), read live from the settings store:
|
||||
*
|
||||
* - `editor.completion.autoPopup` (bool, default true): whether typing
|
||||
* opens the completion list; the completion shortcut always does.
|
||||
* - `editor.completion.delayMs` (0–2000, default 0): how long typing has
|
||||
* to pause before completion is asked for.
|
||||
* - `editor.hover.delayMs` (100–3000, default 350): how long the pointer
|
||||
* rests before the hover documentation is asked for.
|
||||
*
|
||||
* {@link liveAssistSettings} keeps an editor state's completion and hover
|
||||
* extensions in step with these values: a change from the dialog, the
|
||||
* control channel or an agent reconfigures every open editor at once.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { Compartment, StateEffect, StateField } from "@codemirror/state";
|
||||
import { ViewPlugin, type EditorView } from "@codemirror/view";
|
||||
import { getActivePinia } from "pinia";
|
||||
import { watch } from "vue";
|
||||
import { useSettingsStore } from "../../../stores/settings";
|
||||
|
||||
/** The assist settings with values the editor can use. */
|
||||
export interface AssistSettings {
|
||||
/** Whether typing opens the completion list. */
|
||||
autoPopup: boolean;
|
||||
/** Milliseconds typing pauses before completion is asked for. */
|
||||
completionDelay: number;
|
||||
/** Milliseconds the pointer rests before the hover is asked for. */
|
||||
hoverDelay: number;
|
||||
}
|
||||
|
||||
/** Setting keys of the assist settings. */
|
||||
export const ASSIST_SETTING_KEYS = {
|
||||
autoPopup: "editor.completion.autoPopup",
|
||||
completionDelay: "editor.completion.delayMs",
|
||||
hoverDelay: "editor.hover.delayMs",
|
||||
} as const;
|
||||
|
||||
/** The engine's defaults, used while a value is missing or unusable. */
|
||||
export const ASSIST_DEFAULTS: Readonly<AssistSettings> = {
|
||||
autoPopup: true,
|
||||
completionDelay: 0,
|
||||
hoverDelay: 350,
|
||||
};
|
||||
|
||||
/** Where the assist settings come from, and how changes are followed. */
|
||||
export interface AssistSettingsSource {
|
||||
/** The current values. */
|
||||
current(): AssistSettings;
|
||||
/**
|
||||
* Calls `listener` after the values change.
|
||||
*
|
||||
* @returns a function that stops following.
|
||||
*/
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A whole number from untrusted data, clamped to a range.
|
||||
*
|
||||
* @param value - the data.
|
||||
* @param min - smallest value.
|
||||
* @param max - largest value.
|
||||
* @param fallback - used when the data is no finite number.
|
||||
*/
|
||||
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
return fallback;
|
||||
}
|
||||
return Math.min(max, Math.max(min, Math.round(value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the assist settings from setting values (unchecked), with the
|
||||
* defaults for missing or malformed values and numbers clamped to the
|
||||
* engine's ranges.
|
||||
*
|
||||
* @param values - setting values by key.
|
||||
*/
|
||||
export function toAssistSettings(values: Readonly<Record<string, unknown>>): AssistSettings {
|
||||
const autoPopup = values[ASSIST_SETTING_KEYS.autoPopup];
|
||||
return {
|
||||
autoPopup: typeof autoPopup === "boolean" ? autoPopup : ASSIST_DEFAULTS.autoPopup,
|
||||
completionDelay: clampInt(values[ASSIST_SETTING_KEYS.completionDelay], 0, 2000, ASSIST_DEFAULTS.completionDelay),
|
||||
hoverDelay: clampInt(values[ASSIST_SETTING_KEYS.hoverDelay], 100, 3000, ASSIST_DEFAULTS.hoverDelay),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two sets of assist settings are equal.
|
||||
*
|
||||
* @param a - one set.
|
||||
* @param b - the other.
|
||||
*/
|
||||
export function sameAssistSettings(a: AssistSettings, b: AssistSettings): boolean {
|
||||
return a.autoPopup === b.autoPopup && a.completionDelay === b.completionDelay && a.hoverDelay === b.hoverDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings store of the active Pinia as a source. Without an active
|
||||
* Pinia (an editor used outside the app) it gives the defaults and never
|
||||
* changes.
|
||||
*/
|
||||
export const storeAssistSettings: AssistSettingsSource = {
|
||||
current() {
|
||||
const pinia = getActivePinia();
|
||||
return pinia ? toAssistSettings(useSettingsStore(pinia).values) : { ...ASSIST_DEFAULTS };
|
||||
},
|
||||
subscribe(listener) {
|
||||
const pinia = getActivePinia();
|
||||
if (!pinia) {
|
||||
return () => undefined;
|
||||
}
|
||||
const store = useSettingsStore(pinia);
|
||||
return watch(
|
||||
() => toAssistSettings(store.values),
|
||||
(next, previous) => {
|
||||
if (!sameAssistSettings(next, previous)) {
|
||||
listener();
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/** Records which settings an editor state's assist extensions were built with. */
|
||||
const applied = StateEffect.define<AssistSettings>();
|
||||
|
||||
/** The settings the state's assist extensions use. */
|
||||
const appliedField = StateField.define<AssistSettings>({
|
||||
create: () => ({ ...ASSIST_DEFAULTS }),
|
||||
update: (value, tr) => {
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(applied)) {
|
||||
return effect.value;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
},
|
||||
});
|
||||
|
||||
/** Builds an extension for the given settings. */
|
||||
export type SettingsBuilder = (settings: AssistSettings) => Extension;
|
||||
|
||||
/**
|
||||
* Extensions that depend on the assist settings and follow them live.
|
||||
* Each builder sits in its own compartment; when the source reports a
|
||||
* change (or a view gets a state built with older values), the
|
||||
* compartments are reconfigured with the new values. The reconfiguration
|
||||
* is dispatched outside any editor update.
|
||||
*
|
||||
* @param source - where the settings come from.
|
||||
* @param builders - one builder per settings-dependent extension.
|
||||
* @returns the extensions, built with the current values.
|
||||
*/
|
||||
export function liveAssistSettings(source: AssistSettingsSource, builders: readonly SettingsBuilder[]): Extension {
|
||||
const initial = source.current();
|
||||
const slots = builders.map((build) => ({ build, compartment: new Compartment() }));
|
||||
const sync = (view: EditorView): void => {
|
||||
const next = source.current();
|
||||
if (sameAssistSettings(next, view.state.field(appliedField))) {
|
||||
return;
|
||||
}
|
||||
view.dispatch({
|
||||
effects: [
|
||||
...slots.map((slot) => slot.compartment.reconfigure(slot.build(next))),
|
||||
applied.of(next),
|
||||
],
|
||||
});
|
||||
};
|
||||
const follower = ViewPlugin.define((view) => {
|
||||
let live = true;
|
||||
const stop = source.subscribe(() => {
|
||||
if (live) {
|
||||
sync(view);
|
||||
}
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
if (live) {
|
||||
sync(view);
|
||||
}
|
||||
});
|
||||
return {
|
||||
destroy() {
|
||||
live = false;
|
||||
stop();
|
||||
},
|
||||
};
|
||||
});
|
||||
return [
|
||||
appliedField.init(() => initial),
|
||||
...slots.map((slot) => slot.compartment.of(slot.build(initial))),
|
||||
follower,
|
||||
];
|
||||
}
|
||||
|
|
@ -3,27 +3,33 @@
|
|||
* The settings dialog (`settings.open`, `Mod+,`), built from the engine's
|
||||
* `settings.list`: sections on the left, the settings of the chosen
|
||||
* section on the right, each with its control by type (enum → select,
|
||||
* int → number field with min/max, bool → switch), label and description
|
||||
* from the catalog, and "Reset to default" when it differs from the
|
||||
* default.
|
||||
* int → number field with min/max, bool → switch, string → text field,
|
||||
* plus "Browse…" for a path, see `stringSetting.ts`), label and
|
||||
* description from the catalog, and "Reset to default" when it differs
|
||||
* from the default.
|
||||
*
|
||||
* - **Search:** the field filters by label, description, key and section
|
||||
* name; while it has text, every match shows, grouped by section.
|
||||
* - **Changes** apply at once through `settings.set` (a number when the
|
||||
* field is committed: Enter, the spinner or leaving it). A refused value
|
||||
* shows its error under the control and keeps the typed text.
|
||||
* - **Changes** apply at once through `settings.set` (a number or a text
|
||||
* when the field is committed: Enter, the spinner or leaving it; a path
|
||||
* when the file picker returns one). A refused value shows its error
|
||||
* under the control and keeps the typed text.
|
||||
* - **Live:** values follow `settingsChanged` through the settings store,
|
||||
* so a change over the control channel shows while the dialog is open.
|
||||
* - **Keyboard:** Escape closes, Tab and Shift+Tab stay inside the dialog,
|
||||
* and the focus returns to where it was.
|
||||
* - **One modal:** opening the dialog closes the palette or the close
|
||||
* question (see `commands/modals.ts`).
|
||||
* - **Agents:** `settings.open {section?, query?}` opens on a section or
|
||||
* with a search, so the dialog can be shown over the control channel
|
||||
* without clicks.
|
||||
*/
|
||||
import { X } from "@lucide/vue";
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
import { useModalsStore } from "../../commands/modals";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { pickFile, type JsonValue } from "../../ipc";
|
||||
import {
|
||||
descriptionOf,
|
||||
groupSections,
|
||||
|
|
@ -34,6 +40,7 @@ import {
|
|||
type SettingDef,
|
||||
type SettingSection,
|
||||
} from "../../stores/settings";
|
||||
import { checkString, isPathSetting, placeholderOf } from "./stringSetting";
|
||||
|
||||
const commands = useCommandsStore();
|
||||
const settings = useSettingsStore();
|
||||
|
|
@ -45,7 +52,7 @@ const open = ref(false);
|
|||
const query = ref("");
|
||||
/** Id of the chosen section. */
|
||||
const current = ref<string | null>(null);
|
||||
/** Text typed into number fields, by key; shown while their value is refused. */
|
||||
/** Text typed into number and text fields, by key; shown while their value is refused. */
|
||||
const drafts = reactive<Record<string, string>>({});
|
||||
/** The dialog element. */
|
||||
const dialog = ref<HTMLElement | null>(null);
|
||||
|
|
@ -105,6 +112,21 @@ function numberText(def: SettingDef): string {
|
|||
return typeof value === "number" ? String(value) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of a text field: the refused draft while there is an error,
|
||||
* else the value.
|
||||
*
|
||||
* @param def - the setting.
|
||||
*/
|
||||
function stringText(def: SettingDef): string {
|
||||
const draft = drafts[def.key];
|
||||
if (draft !== undefined && settings.errors[def.key] !== undefined) {
|
||||
return draft;
|
||||
}
|
||||
const value = settings.values[def.key];
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The value of a select.
|
||||
*
|
||||
|
|
@ -172,6 +194,56 @@ async function onNumber(def: SettingDef, event: Event): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a text to `settings.set` after the checks of
|
||||
* {@link checkString}; a refused text stays in the field with its error.
|
||||
*
|
||||
* @param def - the setting.
|
||||
* @param text - the new value.
|
||||
*/
|
||||
async function applyString(def: SettingDef, text: string): Promise<void> {
|
||||
drafts[def.key] = text;
|
||||
const error = checkString(def, text);
|
||||
if (error !== null) {
|
||||
settings.setError(def.key, error);
|
||||
return;
|
||||
}
|
||||
if (await settings.set(def.key, text)) {
|
||||
Reflect.deleteProperty(drafts, def.key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a committed text field.
|
||||
*
|
||||
* @param def - the setting.
|
||||
* @param event - the change event.
|
||||
*/
|
||||
async function onString(def: SettingDef, event: Event): Promise<void> {
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLInputElement) {
|
||||
await applyString(def, target.value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Browse…" of a path setting: shows the native file picker and applies
|
||||
* the chosen file. Cancelling changes nothing; a picker that cannot open
|
||||
* shows its error under the control.
|
||||
*
|
||||
* @param def - the setting.
|
||||
*/
|
||||
async function onBrowse(def: SettingDef): Promise<void> {
|
||||
const picked = await pickFile(t("settings.dialog.browseTitle", { name: labelOf(def) }));
|
||||
if (!picked.ok) {
|
||||
settings.setError(def.key, t("settings.error.browseFailed", { message: picked.error.message }));
|
||||
return;
|
||||
}
|
||||
if (picked.value !== null) {
|
||||
await applyString(def, picked.value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flips a switch.
|
||||
*
|
||||
|
|
@ -202,8 +274,13 @@ function choose(id: string): void {
|
|||
query.value = "";
|
||||
}
|
||||
|
||||
/** Opens the dialog (or focuses its search field) and reloads the settings. */
|
||||
async function show(): Promise<void> {
|
||||
/**
|
||||
* Opens the dialog (or focuses its search field) and reloads the settings.
|
||||
*
|
||||
* @param params - optional `{section?, query?}` from `settings.open`:
|
||||
* the section id to show, the search text; anything else is ignored.
|
||||
*/
|
||||
async function show(params?: JsonValue): Promise<void> {
|
||||
modals.opened("settings", close);
|
||||
if (!open.value) {
|
||||
const active = document.activeElement;
|
||||
|
|
@ -211,6 +288,14 @@ async function show(): Promise<void> {
|
|||
query.value = "";
|
||||
open.value = true;
|
||||
}
|
||||
if (typeof params === "object" && params !== null && !Array.isArray(params)) {
|
||||
if (typeof params.section === "string") {
|
||||
choose(params.section);
|
||||
}
|
||||
if (typeof params.query === "string") {
|
||||
query.value = params.query.slice(0, 200);
|
||||
}
|
||||
}
|
||||
await nextTick();
|
||||
search.value?.focus();
|
||||
await settings.load();
|
||||
|
|
@ -295,7 +380,7 @@ function onFocusIn(event: FocusEvent): void {
|
|||
}
|
||||
|
||||
onMounted(() => {
|
||||
withdraw = commands.provide("settings.open", { run: show });
|
||||
withdraw = commands.provide("settings.open", { run: (params) => show(params) });
|
||||
document.addEventListener("focusin", onFocusIn);
|
||||
});
|
||||
|
||||
|
|
@ -419,6 +504,7 @@ defineExpose({ show, close });
|
|||
v-for="def in section.settings"
|
||||
:key="def.key"
|
||||
class="settings__row"
|
||||
:class="{ 'settings__row--wide': def.type === 'string' }"
|
||||
:data-key="def.key"
|
||||
data-test="settings-row"
|
||||
>
|
||||
|
|
@ -478,6 +564,32 @@ defineExpose({ show, close });
|
|||
data-test="settings-control"
|
||||
@change="onNumber(def, $event)"
|
||||
>
|
||||
<template v-else-if="def.type === 'string'">
|
||||
<input
|
||||
:id="controlId(def)"
|
||||
class="settings__input settings__input--text"
|
||||
type="text"
|
||||
:value="stringText(def)"
|
||||
:placeholder="placeholderOf(def) || undefined"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
:aria-describedby="`${controlId(def)}-description`"
|
||||
:aria-invalid="settings.errors[def.key] ? 'true' : undefined"
|
||||
:aria-errormessage="settings.errors[def.key] ? `${controlId(def)}-error` : undefined"
|
||||
data-test="settings-control"
|
||||
@change="onString(def, $event)"
|
||||
>
|
||||
<button
|
||||
v-if="isPathSetting(def)"
|
||||
type="button"
|
||||
class="settings__browse"
|
||||
:aria-label="t('settings.dialog.browseLabel', { name: labelOf(def) })"
|
||||
data-test="settings-browse"
|
||||
@click="onBrowse(def)"
|
||||
>
|
||||
{{ t("settings.dialog.browse") }}
|
||||
</button>
|
||||
</template>
|
||||
<button
|
||||
v-else
|
||||
:id="controlId(def)"
|
||||
|
|
@ -634,6 +746,16 @@ defineExpose({ show, close });
|
|||
min-width: 0;
|
||||
}
|
||||
|
||||
.settings__row--wide {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.settings__row--wide .settings__control {
|
||||
flex-shrink: 1;
|
||||
}
|
||||
|
||||
.settings__label {
|
||||
display: block;
|
||||
}
|
||||
|
|
@ -674,6 +796,11 @@ defineExpose({ show, close });
|
|||
width: 6em;
|
||||
}
|
||||
|
||||
.settings__input--text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.settings__input[aria-invalid="true"] {
|
||||
border-color: var(--lt-error);
|
||||
}
|
||||
|
|
@ -719,6 +846,17 @@ defineExpose({ show, close });
|
|||
cursor: pointer;
|
||||
}
|
||||
|
||||
.settings__browse {
|
||||
padding: 3px 8px;
|
||||
font: inherit;
|
||||
font-size: var(--lt-font-size-small);
|
||||
color: var(--lt-fg);
|
||||
background: none;
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.settings__reset:disabled {
|
||||
color: var(--lt-fg-muted);
|
||||
cursor: default;
|
||||
|
|
@ -729,6 +867,7 @@ defineExpose({ show, close });
|
|||
.settings__search:focus-visible,
|
||||
.settings__input:focus-visible,
|
||||
.settings__switch:focus-visible,
|
||||
.settings__browse:focus-visible,
|
||||
.settings__reset:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
outline-offset: 1px;
|
||||
|
|
|
|||
91
ui/src/components/settings/stringSetting.ts
Normal file
91
ui/src/components/settings/stringSetting.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
/**
|
||||
* 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;
|
||||
}
|
||||
|
|
@ -179,6 +179,9 @@
|
|||
"settings.appearance.theme.value.lutraDark": "Lutra Dark",
|
||||
"settings.appearance.theme.value.lutraLight": "Lutra Light",
|
||||
"settings.appearance.theme.value.system": "Same as system",
|
||||
"settings.dialog.browse": "Browse…",
|
||||
"settings.dialog.browseLabel": "Choose a file for {name}",
|
||||
"settings.dialog.browseTitle": "Choose {name}",
|
||||
"settings.dialog.loadFailed": "Settings could not be loaded: {message}",
|
||||
"settings.dialog.noMatches": "No settings match your search",
|
||||
"settings.dialog.reset": "Reset to default",
|
||||
|
|
@ -192,10 +195,22 @@
|
|||
"settings.editor.autosave.onBlur.label": "Autosave when leaving the window",
|
||||
"settings.editor.autosave.onTabSwitch.description": "Save changed files when you switch to another editor tab.",
|
||||
"settings.editor.autosave.onTabSwitch.label": "Autosave on tab switch",
|
||||
"settings.editor.completion.autoPopup.description": "Open the completion list by itself as you type a name, $, ->, :: or \\. When off, the list opens only with the completion shortcut.",
|
||||
"settings.editor.completion.autoPopup.label": "Show completions while typing",
|
||||
"settings.editor.completion.delayMs.description": "How long Lutra waits after you stop typing before it asks for completions. 0 asks at once.",
|
||||
"settings.editor.completion.delayMs.label": "Completion popup delay (ms)",
|
||||
"settings.editor.fontSize.description": "Size of the text in the editor, in pixels.",
|
||||
"settings.editor.fontSize.label": "Editor font size",
|
||||
"settings.editor.hover.delayMs.description": "How long the pointer has to rest on a name before its documentation shows.",
|
||||
"settings.editor.hover.delayMs.label": "Documentation tooltip delay (ms)",
|
||||
"settings.error.browseFailed": "The file picker could not open: {message}",
|
||||
"settings.error.int": "Enter a whole number",
|
||||
"settings.error.intRange": "Enter a whole number from {min} to {max}",
|
||||
"settings.error.pathQuoted": "Remove the quotes around the path",
|
||||
"settings.error.pathSpaces": "Remove the spaces at the start or end of the path",
|
||||
"settings.error.stringControl": "Remove tabs, line breaks and other control characters",
|
||||
"settings.error.stringTooLong": "Enter at most {max} bytes",
|
||||
"settings.hint.pathAuto": "Detected automatically",
|
||||
"settings.php.executable.description": "Path to the PHP executable (8.2 or newer) that runs Phpactor. Leave empty to use php from PATH.",
|
||||
"settings.php.executable.label": "PHP executable",
|
||||
"settings.phpactor.autoDownload.description": "When a PHP project opens and Phpactor is missing, download the pinned Phpactor release from GitHub and check its SHA-256. This is the only network access Lutra makes.",
|
||||
|
|
|
|||
|
|
@ -318,3 +318,20 @@ export async function listCommands(): Promise<RunResult<CommandInfo[]>> {
|
|||
return { ok: false, error: toEngineError(reason) };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the native file picker of the desktop shell (the "Browse…" button
|
||||
* of a path setting).
|
||||
*
|
||||
* @param title - the picker's title, from the catalog.
|
||||
* @returns the chosen file's absolute path, null when the user cancelled,
|
||||
* or the error the call failed with (for example outside the shell).
|
||||
*/
|
||||
export async function pickFile(title: string): Promise<RunResult<string | null>> {
|
||||
try {
|
||||
const value = await invoke<string | null>("pick_file", { title });
|
||||
return { ok: true, value: typeof value === "string" ? value : null };
|
||||
} catch (reason: unknown) {
|
||||
return { ok: false, error: toEngineError(reason) };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ import { setTokenOverride } from "../theme";
|
|||
export type SettingValue = string | number | boolean | null;
|
||||
|
||||
/** Types of settings the dialog has a control for. */
|
||||
export type SettingType = "enum" | "int" | "bool";
|
||||
export type SettingType = "enum" | "int" | "bool" | "string";
|
||||
|
||||
/** A setting as `settings.list` describes it. */
|
||||
export interface SettingDef {
|
||||
|
|
@ -98,7 +98,7 @@ function toSettingDef(raw: unknown): SettingDef | null {
|
|||
typeof labelKey !== "string" ||
|
||||
typeof descriptionKey !== "string" ||
|
||||
typeof section !== "string" ||
|
||||
(type !== "enum" && type !== "int" && type !== "bool")
|
||||
(type !== "enum" && type !== "int" && type !== "bool" && type !== "string")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
|
@ -377,7 +377,7 @@ export const useSettingsStore = defineStore("settings", () => {
|
|||
|
||||
/**
|
||||
* Records an error found before asking the engine (a number field with
|
||||
* text that is no whole number).
|
||||
* text that is no whole number, a string field with a refused text).
|
||||
*
|
||||
* @param key - the setting.
|
||||
* @param message - the error text.
|
||||
|
|
|
|||
195
ui/tests/editor/assist/settings.test.ts
Normal file
195
ui/tests/editor/assist/settings.test.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
/**
|
||||
* Tests of the live assist settings (H4, `assist/settings.ts`): reading
|
||||
* and clamping the values, following the settings store, reconfiguring
|
||||
* open editors when a value changes, and the effect on completion (auto
|
||||
* popup on/off, popup delay) through `assistExtensions`.
|
||||
*/
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { nextTick } from "vue";
|
||||
import { assistExtensions } from "../../../src/components/editor/assist";
|
||||
import {
|
||||
ASSIST_DEFAULTS,
|
||||
liveAssistSettings,
|
||||
storeAssistSettings,
|
||||
toAssistSettings,
|
||||
type AssistSettings,
|
||||
type AssistSettingsSource,
|
||||
} from "../../../src/components/editor/assist/settings";
|
||||
import { useSettingsStore } from "../../../src/stores/settings";
|
||||
import { fakeBuffer, fakeTransport } from "./fakes";
|
||||
|
||||
/** Views created by a test, destroyed after it. */
|
||||
let views: EditorView[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
for (const view of views) {
|
||||
view.destroy();
|
||||
}
|
||||
views = [];
|
||||
});
|
||||
|
||||
/** A mounted view with `doc` and `extensions`. */
|
||||
function mount(doc: string, extensions: Extension): EditorView {
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const view = new EditorView({ state: EditorState.create({ doc, extensions }), parent });
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** A settings source the test changes by hand. */
|
||||
function fakeSource(initial: Partial<AssistSettings> = {}): AssistSettingsSource & {
|
||||
change(next: Partial<AssistSettings>): void;
|
||||
listeners: Set<() => void>;
|
||||
} {
|
||||
let value: AssistSettings = { ...ASSIST_DEFAULTS, ...initial };
|
||||
const listeners = new Set<() => void>();
|
||||
return {
|
||||
listeners,
|
||||
current: () => ({ ...value }),
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
change(next) {
|
||||
value = { ...value, ...next };
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets `ms` milliseconds pass on the fake clock, running the timers and
|
||||
* promises due meanwhile.
|
||||
*/
|
||||
async function wait(ms: number): Promise<void> {
|
||||
await vi.advanceTimersByTimeAsync(ms);
|
||||
}
|
||||
|
||||
/** Types `text` at the end of the view's document as the user would. */
|
||||
function type(view: EditorView, text: string): void {
|
||||
const end = view.state.doc.length;
|
||||
view.dispatch({
|
||||
changes: { from: end, insert: text },
|
||||
selection: { anchor: end + text.length },
|
||||
userEvent: "input.type",
|
||||
});
|
||||
}
|
||||
|
||||
/** The completion queries a transport received. */
|
||||
function completions(transport: ReturnType<typeof fakeTransport>): number {
|
||||
return transport.calls.filter((c) => c.command === "lsp.completion").length;
|
||||
}
|
||||
|
||||
describe("assist settings values", () => {
|
||||
it("uses the defaults for missing or malformed values and clamps numbers", () => {
|
||||
expect(toAssistSettings({})).toEqual({ autoPopup: true, completionDelay: 0, hoverDelay: 350 });
|
||||
expect(
|
||||
toAssistSettings({
|
||||
"editor.completion.autoPopup": "no",
|
||||
"editor.completion.delayMs": Number.NaN,
|
||||
"editor.hover.delayMs": null,
|
||||
}),
|
||||
).toEqual(ASSIST_DEFAULTS);
|
||||
expect(
|
||||
toAssistSettings({
|
||||
"editor.completion.autoPopup": false,
|
||||
"editor.completion.delayMs": 9999,
|
||||
"editor.hover.delayMs": 10.4,
|
||||
}),
|
||||
).toEqual({ autoPopup: false, completionDelay: 2000, hoverDelay: 100 });
|
||||
});
|
||||
|
||||
it("reads and follows the settings store", async () => {
|
||||
setActivePinia(createPinia());
|
||||
const store = useSettingsStore();
|
||||
expect(storeAssistSettings.current()).toEqual(ASSIST_DEFAULTS);
|
||||
let changes = 0;
|
||||
const stop = storeAssistSettings.subscribe(() => {
|
||||
changes += 1;
|
||||
});
|
||||
store.values["editor.hover.delayMs"] = 800;
|
||||
await nextTick();
|
||||
expect(changes).toBe(1);
|
||||
expect(storeAssistSettings.current().hoverDelay).toBe(800);
|
||||
store.values["editor.fontSize"] = 20;
|
||||
await nextTick();
|
||||
expect(changes).toBe(1);
|
||||
stop();
|
||||
store.values["editor.completion.autoPopup"] = false;
|
||||
await nextTick();
|
||||
expect(changes).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("live reconfiguration", () => {
|
||||
it("rebuilds the dependent extensions with new values and stops on destroy", async () => {
|
||||
const source = fakeSource({ hoverDelay: 500 });
|
||||
const built: number[] = [];
|
||||
const view = mount("<?php\n", liveAssistSettings(source, [(s) => (built.push(s.hoverDelay), [])]));
|
||||
await Promise.resolve();
|
||||
expect(built).toEqual([500]);
|
||||
source.change({ hoverDelay: 1200 });
|
||||
expect(built).toEqual([500, 1200]);
|
||||
source.change({ hoverDelay: 1200 });
|
||||
expect(built).toEqual([500, 1200]);
|
||||
view.destroy();
|
||||
views = [];
|
||||
expect(source.listeners.size).toBe(0);
|
||||
});
|
||||
|
||||
it("catches up when a view gets a state built with older values", async () => {
|
||||
const source = fakeSource();
|
||||
const built: boolean[] = [];
|
||||
const state = EditorState.create({
|
||||
doc: "<?php\n",
|
||||
extensions: liveAssistSettings(source, [(s) => (built.push(s.autoPopup), [])]),
|
||||
});
|
||||
source.change({ autoPopup: false });
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
views.push(new EditorView({ state, parent }));
|
||||
await Promise.resolve();
|
||||
expect(built).toEqual([true, false]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("completion follows the settings", () => {
|
||||
it("opens while typing only with auto popup on", async () => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
const source = fakeSource({ autoPopup: false });
|
||||
const transport = fakeTransport({ isIncomplete: false, items: [{ label: "Foo", kind: "class" }] });
|
||||
const view = mount("<?php\n", assistExtensions("a.php", fakeBuffer(1), transport, source));
|
||||
type(view, "Fo");
|
||||
await wait(30);
|
||||
expect(completions(transport)).toBe(0);
|
||||
|
||||
source.change({ autoPopup: true });
|
||||
type(view, "o");
|
||||
await wait(30);
|
||||
expect(completions(transport)).toBe(1);
|
||||
});
|
||||
|
||||
it("waits for the popup delay after typing", async () => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
const source = fakeSource({ completionDelay: 200 });
|
||||
const transport = fakeTransport({ isIncomplete: true, items: [{ label: "Foo", kind: "class" }] });
|
||||
const view = mount("<?php\n", assistExtensions("a.php", fakeBuffer(1), transport, source));
|
||||
type(view, "F");
|
||||
await wait(190);
|
||||
expect(completions(transport)).toBe(0);
|
||||
await wait(20);
|
||||
expect(completions(transport)).toBe(1);
|
||||
|
||||
source.change({ completionDelay: 0 });
|
||||
type(view, "o");
|
||||
await wait(30);
|
||||
expect(completions(transport)).toBe(2);
|
||||
});
|
||||
});
|
||||
|
|
@ -77,8 +77,14 @@ const RUNTIME_KEYS = new Set([
|
|||
"settings.editor.autosave.onBlur.label",
|
||||
"settings.editor.autosave.onTabSwitch.description",
|
||||
"settings.editor.autosave.onTabSwitch.label",
|
||||
"settings.editor.completion.autoPopup.description",
|
||||
"settings.editor.completion.autoPopup.label",
|
||||
"settings.editor.completion.delayMs.description",
|
||||
"settings.editor.completion.delayMs.label",
|
||||
"settings.editor.fontSize.description",
|
||||
"settings.editor.fontSize.label",
|
||||
"settings.editor.hover.delayMs.description",
|
||||
"settings.editor.hover.delayMs.label",
|
||||
"settings.php.executable.description",
|
||||
"settings.php.executable.label",
|
||||
"settings.phpactor.autoDownload.description",
|
||||
|
|
|
|||
333
ui/tests/settings/StringSettings.test.ts
Normal file
333
ui/tests/settings/StringSettings.test.ts
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
/**
|
||||
* Tests of the string and path controls of the settings dialog (H4,
|
||||
* `components/settings/stringSetting.ts`): which settings are paths, the
|
||||
* checks before `settings.set` and their messages, the text field and its
|
||||
* placeholder, "Browse…" through the shell's `pick_file`, engine errors,
|
||||
* live updates, `settings.open {section, query}`, and a string setting the dialog has never seen
|
||||
* (`git.executable`) getting the control without changes. The engine is a
|
||||
* fake behind the mocked Tauri `invoke` and `listen`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const invoke = vi.hoisted(() => vi.fn());
|
||||
const listen = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
vi.mock("@tauri-apps/api/event", () => ({ listen }));
|
||||
|
||||
import { useCommandsStore } from "../../src/commands/store";
|
||||
import SettingsDialog from "../../src/components/settings/SettingsDialog.vue";
|
||||
import {
|
||||
checkString,
|
||||
isPathSetting,
|
||||
MAX_STRING_BYTES,
|
||||
placeholderOf,
|
||||
} from "../../src/components/settings/stringSetting";
|
||||
import { toSettingDefs, useSettingsStore, type SettingDef } from "../../src/stores/settings";
|
||||
|
||||
/**
|
||||
* A string setting as `settings.list` reports it.
|
||||
*
|
||||
* @param key - the key.
|
||||
* @param section - the section id.
|
||||
*/
|
||||
function stringEntry(key: string, section: string): Record<string, unknown> {
|
||||
return {
|
||||
key,
|
||||
type: "string",
|
||||
default: "",
|
||||
labelKey: `settings.${key}.label`,
|
||||
descriptionKey: `settings.${key}.description`,
|
||||
section,
|
||||
};
|
||||
}
|
||||
|
||||
/** The fake engine's base `settings.list`. */
|
||||
const BASE = [
|
||||
stringEntry("php.executable", "php"),
|
||||
stringEntry("phpactor.path", "php"),
|
||||
{ ...stringEntry("editor.name", "php"), default: "Lutra" },
|
||||
];
|
||||
|
||||
/** What `settings.list` returns in the current test. */
|
||||
let list: Record<string, unknown>[];
|
||||
/** The fake engine's values. */
|
||||
let values: Record<string, unknown>;
|
||||
/** Every `engine_execute` call, in order. */
|
||||
let calls: { command: string; params: Record<string, unknown> }[];
|
||||
/** What `pick_file` answers: a path, null (cancelled) or an error. */
|
||||
let picked: string | null | Error;
|
||||
/** The titles `pick_file` was called with. */
|
||||
let pickTitles: string[];
|
||||
/** The engine event callbacks. */
|
||||
let listeners: ((payload: unknown) => void)[];
|
||||
/** Pinia of the current test. */
|
||||
let pinia: Pinia;
|
||||
/** Mounted components. */
|
||||
let mounted: VueWrapper[];
|
||||
|
||||
/**
|
||||
* The setting definitions of the base list.
|
||||
*
|
||||
* @param key - the key.
|
||||
*/
|
||||
function defOf(key: string): SettingDef {
|
||||
const def = toSettingDefs([...BASE, stringEntry("git.executable", "git"), { ...BASE[0], key: "x.pharPath" }])?.find(
|
||||
(d) => d.key === key,
|
||||
);
|
||||
if (!def) {
|
||||
throw new Error(key);
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
/** Mounts and opens the dialog on the first section. */
|
||||
async function openDialog(): Promise<VueWrapper> {
|
||||
const wrapper = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(wrapper);
|
||||
await useCommandsStore(pinia).start();
|
||||
await useSettingsStore(pinia).start();
|
||||
await (wrapper.vm as unknown as { show(): Promise<void> }).show();
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* A setting's row.
|
||||
*
|
||||
* @param wrapper - the dialog.
|
||||
* @param key - the setting.
|
||||
*/
|
||||
function row(wrapper: VueWrapper, key: string) {
|
||||
return wrapper.find(`[data-test=settings-row][data-key="${key}"]`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Types into a setting's text field and commits it (as leaving the field does).
|
||||
*
|
||||
* @param wrapper - the dialog.
|
||||
* @param key - the setting.
|
||||
* @param text - the text.
|
||||
*/
|
||||
async function commit(wrapper: VueWrapper, key: string, text: string): Promise<void> {
|
||||
const input = row(wrapper, key).find("input");
|
||||
(input.element as HTMLInputElement).value = text;
|
||||
await input.trigger("change");
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/** The `settings.set` calls. */
|
||||
function sets(): Record<string, unknown>[] {
|
||||
return calls.filter((c) => c.command === "settings.set").map((c) => c.params);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
list = [...BASE];
|
||||
values = { "php.executable": "", "phpactor.path": "/opt/phpactor.phar", "editor.name": "Lutra" };
|
||||
calls = [];
|
||||
picked = null;
|
||||
pickTitles = [];
|
||||
listeners = [];
|
||||
mounted = [];
|
||||
listen.mockReset();
|
||||
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
|
||||
listeners.push((payload) => {
|
||||
callback({ payload });
|
||||
});
|
||||
return Promise.resolve(() => undefined);
|
||||
});
|
||||
invoke.mockReset();
|
||||
invoke.mockImplementation((cmd: string, args?: Record<string, unknown>) => {
|
||||
if (cmd === "pick_file") {
|
||||
pickTitles.push(String(args?.title));
|
||||
return picked instanceof Error ? Promise.reject(picked) : Promise.resolve(picked);
|
||||
}
|
||||
if (cmd !== "engine_execute" || !args) {
|
||||
return Promise.resolve(cmd === "engine_list_commands" ? [] : null);
|
||||
}
|
||||
const command = args.command as string;
|
||||
const params = args.params as Record<string, unknown>;
|
||||
calls.push({ command, params });
|
||||
switch (command) {
|
||||
case "settings.list":
|
||||
return Promise.resolve(list);
|
||||
case "settings.get": {
|
||||
const keys = Array.isArray(params.keys) ? (params.keys as string[]) : Object.keys(values);
|
||||
return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) });
|
||||
}
|
||||
case "settings.set":
|
||||
if (params.value === "/does/not/exist") {
|
||||
return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" }));
|
||||
}
|
||||
values[params.key as string] = params.value;
|
||||
return Promise.resolve({ value: params.value });
|
||||
case "settings.reset":
|
||||
values[params.key as string] = "";
|
||||
return Promise.resolve({ value: "" });
|
||||
default:
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useCommandsStore(pinia).stop();
|
||||
useSettingsStore(pinia).stop();
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
describe("string setting rules", () => {
|
||||
it("treats keys ending in path or executable as paths", () => {
|
||||
expect(isPathSetting(defOf("php.executable"))).toBe(true);
|
||||
expect(isPathSetting(defOf("phpactor.path"))).toBe(true);
|
||||
expect(isPathSetting(defOf("git.executable"))).toBe(true);
|
||||
expect(isPathSetting(defOf("x.pharPath"))).toBe(true);
|
||||
expect(isPathSetting(defOf("editor.name"))).toBe(false);
|
||||
expect(isPathSetting({ ...defOf("php.executable"), type: "int" })).toBe(false);
|
||||
});
|
||||
|
||||
it("shows 'Detected automatically' only for paths with an empty default", () => {
|
||||
expect(placeholderOf(defOf("php.executable"))).toBe("Detected automatically");
|
||||
expect(placeholderOf({ ...defOf("php.executable"), default: "/usr/bin/php" })).toBe("");
|
||||
expect(placeholderOf(defOf("editor.name"))).toBe("");
|
||||
});
|
||||
|
||||
it("refuses long texts, control characters, quoted and padded paths", () => {
|
||||
const php = defOf("php.executable");
|
||||
const name = defOf("editor.name");
|
||||
expect(checkString(php, "C:\\php\\php.exe")).toBeNull();
|
||||
expect(checkString(php, "")).toBeNull();
|
||||
expect(checkString(php, "/opt/my php/php")).toBeNull();
|
||||
expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBe("Remove the quotes around the path");
|
||||
expect(checkString(php, "'/opt/php'")).toBe("Remove the quotes around the path");
|
||||
expect(checkString(php, " /opt/php")).toBe("Remove the spaces at the start or end of the path");
|
||||
expect(checkString(php, "/opt/php\t")).toBe("Remove tabs, line breaks and other control characters");
|
||||
expect(checkString(name, " padded is fine ")).toBeNull();
|
||||
expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2))).toBeNull();
|
||||
expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2 + 1))).toBe(`Enter at most ${String(MAX_STRING_BYTES)} bytes`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("string and path controls", () => {
|
||||
it("shows a text field with the value, a placeholder and Browse for paths", async () => {
|
||||
const wrapper = await openDialog();
|
||||
const php = row(wrapper, "php.executable");
|
||||
const field = php.find("input");
|
||||
expect(field.attributes()).toMatchObject({ type: "text", placeholder: "Detected automatically" });
|
||||
expect((field.element as HTMLInputElement).value).toBe("");
|
||||
expect(php.find("label").text()).toBe("PHP executable");
|
||||
expect(php.find("[data-test=settings-browse]").text()).toBe("Browse…");
|
||||
expect(php.find("[data-test=settings-browse]").attributes("aria-label")).toBe("Choose a file for PHP executable");
|
||||
expect((row(wrapper, "phpactor.path").find("input").element as HTMLInputElement).value).toBe("/opt/phpactor.phar");
|
||||
expect(row(wrapper, "phpactor.path").find("[data-test=settings-reset]").attributes("disabled")).toBeUndefined();
|
||||
const name = row(wrapper, "editor.name");
|
||||
expect(name.find("input").attributes("placeholder")).toBeUndefined();
|
||||
expect(name.find("[data-test=settings-browse]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("applies a committed text through settings.set", async () => {
|
||||
const wrapper = await openDialog();
|
||||
await commit(wrapper, "php.executable", "C:\\php\\php.exe");
|
||||
expect(sets()).toEqual([{ key: "php.executable", value: "C:\\php\\php.exe" }]);
|
||||
expect(useSettingsStore(pinia).values["php.executable"]).toBe("C:\\php\\php.exe");
|
||||
expect(row(wrapper, "php.executable").find("[data-test=settings-error]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses a quoted path in place and keeps the typed text", async () => {
|
||||
const wrapper = await openDialog();
|
||||
await commit(wrapper, "php.executable", '"C:\\php\\php.exe"');
|
||||
expect(sets()).toEqual([]);
|
||||
const php = row(wrapper, "php.executable");
|
||||
expect(php.find("[data-test=settings-error]").text()).toBe("Remove the quotes around the path");
|
||||
expect(php.find("input").attributes("aria-invalid")).toBe("true");
|
||||
expect((php.find("input").element as HTMLInputElement).value).toBe('"C:\\php\\php.exe"');
|
||||
await commit(wrapper, "php.executable", "C:\\php\\php.exe");
|
||||
expect(sets()).toEqual([{ key: "php.executable", value: "C:\\php\\php.exe" }]);
|
||||
expect(php.find("[data-test=settings-error]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("shows the engine's error for a value it refuses", async () => {
|
||||
const wrapper = await openDialog();
|
||||
await commit(wrapper, "phpactor.path", "/does/not/exist");
|
||||
const path = row(wrapper, "phpactor.path");
|
||||
expect(path.find("[data-test=settings-error]").text()).toBe("no such file");
|
||||
expect((path.find("input").element as HTMLInputElement).value).toBe("/does/not/exist");
|
||||
});
|
||||
|
||||
it("browses for a file and applies it; cancelling changes nothing", async () => {
|
||||
const wrapper = await openDialog();
|
||||
picked = null;
|
||||
await row(wrapper, "php.executable").find("[data-test=settings-browse]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(pickTitles).toEqual(["Choose PHP executable"]);
|
||||
expect(sets()).toEqual([]);
|
||||
picked = "C:\\tools\\php\\php.exe";
|
||||
await row(wrapper, "php.executable").find("[data-test=settings-browse]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(sets()).toEqual([{ key: "php.executable", value: "C:\\tools\\php\\php.exe" }]);
|
||||
expect((row(wrapper, "php.executable").find("input").element as HTMLInputElement).value).toBe(
|
||||
"C:\\tools\\php\\php.exe",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows why the file picker could not open", async () => {
|
||||
const wrapper = await openDialog();
|
||||
picked = new Error("no shell");
|
||||
await row(wrapper, "phpactor.path").find("[data-test=settings-browse]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(row(wrapper, "phpactor.path").find("[data-test=settings-error]").text()).toBe(
|
||||
"The file picker could not open: no shell",
|
||||
);
|
||||
expect(sets()).toEqual([]);
|
||||
});
|
||||
|
||||
it("follows settingsChanged and resets to the default", async () => {
|
||||
const wrapper = await openDialog();
|
||||
values["php.executable"] = "/usr/bin/php8.4";
|
||||
for (const listener of listeners) {
|
||||
listener({ kind: "settingsChanged", keys: ["php.executable"] });
|
||||
}
|
||||
await flushPromises();
|
||||
expect((row(wrapper, "php.executable").find("input").element as HTMLInputElement).value).toBe("/usr/bin/php8.4");
|
||||
await row(wrapper, "php.executable").find("[data-test=settings-reset]").trigger("click");
|
||||
await flushPromises();
|
||||
expect((row(wrapper, "php.executable").find("input").element as HTMLInputElement).value).toBe("");
|
||||
});
|
||||
|
||||
it("opens on a section or with a search from settings.open params (agents)", async () => {
|
||||
list = [...BASE, { ...stringEntry("git.executable", "git") }];
|
||||
values["git.executable"] = "";
|
||||
const wrapper = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(wrapper);
|
||||
await useCommandsStore(pinia).start();
|
||||
await useSettingsStore(pinia).start();
|
||||
for (const listener of listeners) {
|
||||
listener({ kind: "uiCommand", id: "settings.open", params: { section: "git" } });
|
||||
}
|
||||
await flushPromises();
|
||||
expect(wrapper.findAll("[data-test=settings-row]").map((r) => r.attributes("data-key"))).toEqual(["git.executable"]);
|
||||
for (const listener of listeners) {
|
||||
listener({ kind: "uiCommand", id: "settings.open", params: { query: "phar" } });
|
||||
}
|
||||
await flushPromises();
|
||||
expect((wrapper.find("[data-test=settings-search]").element as HTMLInputElement).value).toBe("phar");
|
||||
expect(wrapper.findAll("[data-test=settings-row]").map((r) => r.attributes("data-key"))).toEqual(["phpactor.path"]);
|
||||
});
|
||||
|
||||
it("gives a string setting it has never seen the control (git.executable)", async () => {
|
||||
list = [...BASE, stringEntry("git.executable", "git")];
|
||||
values["git.executable"] = "";
|
||||
const wrapper = await openDialog();
|
||||
await wrapper.find("[data-section=git]").trigger("click");
|
||||
const git = row(wrapper, "git.executable");
|
||||
expect(git.find("input").attributes()).toMatchObject({ type: "text", placeholder: "Detected automatically" });
|
||||
expect(git.find("[data-test=settings-browse]").exists()).toBe(true);
|
||||
await commit(wrapper, "git.executable", "/usr/bin/git");
|
||||
expect(sets()).toEqual([{ key: "git.executable", value: "/usr/bin/git" }]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue