Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/options: fix some bugs
Adorian Doran869b81bf6cb9
diff --git a/apps/client/src/widgets/type_widgets/options/code_mime_types_list.spec.tsx b/apps/client/src/widgets/type_widgets/options/code_mime_types_list.spec.tsxindex 666c62a369..e15430e7bd 100644--- a/apps/client/src/widgets/type_widgets/options/code_mime_types_list.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/code_mime_types_list.spec.tsx@@ -54,19 +54,38 @@ function tooltipFor(container: HTMLElement, mime: string) {}describe("the code MIME type list", () => {- it("files each language under its initial, with plain text kept apart and out of reach", () => {- mocks.stored = [ "text/plain" ];+ it("files each language under its initial, with plain text kept apart", () => {const container = renderInto(<CodeMimeTypesList />);// The first group carries no heading: plain text is not filed under a letter.const headings = [ ...container.querySelectorAll("h5") ].map((heading) => heading.textContent);expect(headings).toEqual([ "C", "J" ]);+ });++ it("shows plain text as on and out of reach, whatever the stored set holds", () => {+ // `mime_types` applies it regardless, so a box reading empty would say the opposite of+ // what happens — and one that cannot be cleared has no business reading empty either.+ for (const stored of [ [], [ "text/plain" ] ]) {+ mocks.stored = stored;+ const plainText = [ ...renderInto(<CodeMimeTypesList />).querySelectorAll<HTMLInputElement>("input") ]+ .find((box) => box.value === "text/plain");++ expect(plainText?.checked).toBe(true);+ expect(plainText?.disabled).toBe(true);+ }+ });++ it("leaves the stored set alone when another language is ticked", () => {+ mocks.stored = [];+ mocks.saved = [];+ const container = renderInto(<CodeMimeTypesList />);++ const java = [ ...container.querySelectorAll<HTMLInputElement>("input") ].find((box) => box.value === "text/x-java");+ java?.dispatchEvent(new Event("change", { bubbles: true }));- const plainText = [ ...container.querySelectorAll<HTMLInputElement>("input") ]- .find((box) => box.value === "text/plain");- expect(plainText?.checked).toBe(true);- // It cannot be turned off: a code note has to be able to fall back to something.- expect(plainText?.disabled).toBe(true);+ // Plain text is on because the app applies it, not because it was chosen — so choosing+ // something else must not quietly write it into the user's option.+ expect(mocks.saved.at(-1)).toEqual([ "text/x-java" ]);});it("sorts the languages by name rather than leaving them in the order they arrived", () => {diff --git a/apps/client/src/widgets/type_widgets/options/code_mime_types_list.tsx b/apps/client/src/widgets/type_widgets/options/code_mime_types_list.tsxindex b1984cb596..f5ecabf32d 100644--- a/apps/client/src/widgets/type_widgets/options/code_mime_types_list.tsx+++ b/apps/client/src/widgets/type_widgets/options/code_mime_types_list.tsx@@ -11,7 +11,11 @@ import mime_types from "../../../services/mime_types";import { useStaticTooltip, useTriliumOptionJson } from "../../react/hooks";import CheckboxList from "./components/CheckboxList";-type MimeTypeWithDisabled = MimeType & { disabled?: boolean };+/**+ * Plain text is applied whatever the option holds (see `mime_types`, which ORs it in), so its entry+ * carries both halves of that: it cannot be cleared, and it reads as on regardless.+ */+type MimeTypeWithState = MimeType & { disabled?: boolean; alwaysOn?: boolean };/*** Lives in its own module (rather than in `code_notes.tsx`) because it is also rendered by the@@ -56,15 +60,15 @@ export function CodeMimeTypesList() {const groupedMimeTypes: Record<string, MimeType[]> = useMemo(() => {mime_types.loadMimeTypes();- const ungroupedMimeTypes = Array.from(mime_types.getMimeTypes()) as MimeTypeWithDisabled[];+ const ungroupedMimeTypes = Array.from(mime_types.getMimeTypes()) as MimeTypeWithState[];const plainTextMimeType = ungroupedMimeTypes.shift();const result: Record<string, MimeType[]> = {};ungroupedMimeTypes.sort((a, b) => a.title.localeCompare(b.title));if (plainTextMimeType) {result[""] = [ plainTextMimeType ];- plainTextMimeType.enabled = true;plainTextMimeType.disabled = true;+ plainTextMimeType.alwaysOn = true;}for (const mimeType of ungroupedMimeTypes) {@@ -85,8 +89,9 @@ export function CodeMimeTypesList() {<section>{ initial && <h5>{initial}</h5> }<CheckboxList- values={mimeTypes as MimeTypeWithDisabled[]}- keyProperty="mime" titleProperty="title" disabledProperty="disabled"+ values={mimeTypes as MimeTypeWithState[]}+ keyProperty="mime" titleProperty="title"+ disabledProperty="disabled" alwaysOnProperty="alwaysOn"currentValue={codeNotesMimeTypes} onChange={setCodeNotesMimeTypes}columnWidth="inherit"/>diff --git a/apps/client/src/widgets/type_widgets/options/components/CheckboxList.tsx b/apps/client/src/widgets/type_widgets/options/components/CheckboxList.tsxindex a2f48a04fd..582413ccfd 100644--- a/apps/client/src/widgets/type_widgets/options/components/CheckboxList.tsx+++ b/apps/client/src/widgets/type_widgets/options/components/CheckboxList.tsx@@ -3,12 +3,18 @@ interface CheckboxListProps<T> {keyProperty: keyof T;titleProperty?: keyof T;disabledProperty?: keyof T;+ /**+ * Marks an entry as ticked whatever the stored set holds, for one the app applies regardless of+ * what was chosen. Pair it with {@link CheckboxListProps.disabledProperty}: a box that cannot be+ * cleared but reads as empty says the opposite of what happens.+ */+ alwaysOnProperty?: keyof T;currentValue: string[];onChange: (newValues: string[]) => void;columnWidth?: string;}-export default function CheckboxList<T>({ values, keyProperty, titleProperty, disabledProperty, currentValue, onChange, columnWidth }: CheckboxListProps<T>) {+export default function CheckboxList<T>({ values, keyProperty, titleProperty, disabledProperty, alwaysOnProperty, currentValue, onChange, columnWidth }: CheckboxListProps<T>) {function toggleValue(value: string) {if (currentValue.includes(value)) {// Already there, needs removing.@@ -28,7 +34,8 @@ export default function CheckboxList<T>({ values, keyProperty, titleProperty, ditype="checkbox"className="form-check-input"value={String(value[keyProperty])}- checked={currentValue.includes(String(value[keyProperty]))}+ checked={currentValue.includes(String(value[keyProperty]))+ || !!(alwaysOnProperty && value[alwaysOnProperty])}disabled={!!(disabledProperty && value[disabledProperty])}onChange={e => toggleValue((e.target as HTMLInputElement).value)}/>diff --git a/apps/client/src/widgets/type_widgets/options/components/TimeSelector.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.spec.tsxindex 83458709bf..b4b9e1aa5b 100644--- a/apps/client/src/widgets/type_widgets/options/components/TimeSelector.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.spec.tsx@@ -96,6 +96,21 @@ describe("TimeSelector", () => {expect(mocks.saved).toEqual([]);});+ it("draws a row whose option has never been written, rather than taking the page down", () => {+ // An unset option answers with an empty string, which is no duration at all.+ const { box, scaleSelect } = selector("", "");++ expect(box?.value).toBe("0");+ // Seconds: the scale a bare figure is read at until one has been chosen.+ expect(scaleSelect?.value).toBe("1");+ expect(mocks.showError).not.toHaveBeenCalled();+ });++ it("falls back on a stored scale that could never divide anything", () => {+ expect(selector("120", "0").box?.value).toBe("120");+ expect(selector("120", "nonsense").box?.value).toBe("120");+ });+it("keeps the figure as it stands when only the scale changes, so the stored seconds move with it", () => {const { scaleSelect } = selector("3600", "3600");diff --git a/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsx b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsxindex 716073071c..edb45c276e 100644--- a/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsx+++ b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsx@@ -36,15 +36,22 @@ export default function TimeSelector({ id, name, includedTimeScales, optionValuereturn values;}, [ includedTimeScales ]);- const [ value, setValue ] = useTriliumOption(optionValueId);- const [ scale, setScale ] = useTriliumOption(optionTimeScaleId);+ const [ storedValue, setValue ] = useTriliumOption(optionValueId);+ const [ storedScale, setScale ] = useTriliumOption(optionTimeScaleId);const [ displayedTime, setDisplayedTime ] = useState("");+ // An option that has never been written answers with an empty string, which is no duration at+ // all — and `convertTime` rightly refuses one. Read as zero seconds instead, so a row whose+ // option is missing still draws and the first edit stores something real, rather than the whole+ // page going down over a setting nobody has touched yet.+ const seconds = toWholeNumber(storedValue, 0);+ const scale = String(toWholeNumber(storedScale, 1, 1));+// React to changes in scale and value.useEffect(() => {- const newTime = convertTime(parseInt(value, 10), scale).toDisplay();+ const newTime = convertTime(seconds, scale).toDisplay();setDisplayedTime(String(newTime));- }, [ value, scale ]);+ }, [ seconds, scale ]);return (<div class="d-flex gap-2">@@ -60,11 +67,13 @@ export default function TimeSelector({ id, name, includedTimeScales, optionValueconst time = parseInt(value, 10);const minimumSecondsOrDefault = (minimumSeconds ?? 0);- const newTime = convertTime(time, scale).toOption();+ // Converted only once there is a figure to convert: `convertTime` refuses+ // anything else, so a check made past it could never be reached.+ const newTime = Number.isNaN(time) ? null : convertTime(time, scale).toOption();// Held up to the floor rather than merely complained about: the figure is// stored in seconds, so that is what the floor is applied to.- if (Number.isNaN(time) || newTime < minimumSecondsOrDefault) {+ if (newTime === null || newTime < minimumSecondsOrDefault) {toast.showError(t("time_selector.minimum_input", { minimumSeconds: minimumSecondsOrDefault }));setValue(minimumSecondsOrDefault);return;@@ -84,6 +93,22 @@ export default function TimeSelector({ id, name, includedTimeScales, optionValue)}+/**+ * Reads a stored option as a whole number, falling back where it holds nothing usable — an option+ * never written, or one carrying something that is not a figure at all.+ *+ * @param minimum the least the value may be; anything under it takes the fallback too.+ */+function toWholeNumber(stored: string, fallback: number, minimum?: number) {+ const parsed = parseInt(stored, 10);++ if (!Number.isFinite(parsed) || (minimum !== undefined && parsed < minimum)) {+ return fallback;+ }++ return parsed;+}+function convertTime(value: number, timeScale: string | number) {if (Number.isNaN(value)) {throw new Error(`Time needs to be a valid integer, but received: ${value}`);diff --git a/apps/client/src/widgets/type_widgets/options/other.spec.tsx b/apps/client/src/widgets/type_widgets/options/other.spec.tsxindex 428eafccd3..a0ed73b631 100644--- a/apps/client/src/widgets/type_widgets/options/other.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/other.spec.tsx@@ -57,8 +57,7 @@ import OtherSettings from "./other";let host: HTMLElement;beforeEach(() => {- // Every duration row does arithmetic on a figure and a scale, so none of them may be the empty- // string an unset option would answer with.+ // What a real install holds: each duration row's figure and the scale it is read at.mocks.stored = {eraseEntitiesAfterTimeInSeconds: "86400", eraseEntitiesAfterTimeScale: "1",eraseUnusedAttachmentsAfterSeconds: "86400", eraseUnusedAttachmentsAfterTimeScale: "1",diff --git a/apps/client/src/widgets/type_widgets/options/password.spec.tsx b/apps/client/src/widgets/type_widgets/options/password.spec.tsxindex 1b856d154b..6e6926207c 100644--- a/apps/client/src/widgets/type_widgets/options/password.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/password.spec.tsx@@ -88,8 +88,7 @@ let host: HTMLElement;beforeEach(() => {mocks.state.electron = false;- // The protected-session row does arithmetic on both, so neither may be the empty string an- // unset option would answer with.+ // What a real install holds for the protected-session row: a figure and the scale it is read at.mocks.state.stored = { protectedSessionTimeout: "600", protectedSessionTimeoutTimeScale: "1" };mocks.state.oauth = {};mocks.state.totpSet = false;diff --git a/apps/client/src/widgets/type_widgets/options/sync.spec.tsx b/apps/client/src/widgets/type_widgets/options/sync.spec.tsxindex cb8591458d..2ad552d854 100644--- a/apps/client/src/widgets/type_widgets/options/sync.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/sync.spec.tsx@@ -41,8 +41,7 @@ import SyncOptions from "./sync";let host: HTMLElement;beforeEach(() => {- // The timeout row reads a figure and a scale and does arithmetic on both, so it needs real- // values rather than the empty string an unset option would answer with.+ // What a real install holds for the timeout row: a figure and the scale it is read at.mocks.stored = { syncServerTimeout: "120", syncServerTimeoutTimeScale: "1" };mocks.saved = [];host = document.body.appendChild(document.createElement("div"));