Skip to content

Build your personal knowledge base with Trilium Notes

style/options: CSS cleanup

Adorian Doran2698c4522142
diff --git a/apps/client/src/stylesheets/theme-next/pages.css b/apps/client/src/stylesheets/theme-next/pages.css
index bdf0f51316..faac56387a 100644
--- a/apps/client/src/stylesheets/theme-next/pages.css
+++ b/apps/client/src/stylesheets/theme-next/pages.css
@@ -268,15 +268,6 @@ body.desktop .options-section:not(.tn-no-card) {
.note-detail-content-widget-content:has(.shortcuts-options-section) {
/* Allow the cards to extend on the full width of the parent */
--options-card-max-width: 100%;
-
- /* Remove the top margin of the first item */
- --options-first-item-top-margin: 0;
-}
-
-/* ETAPI */
-
-.etapi-options-section div {
- height: auto !important;
}
/* BACKUP */
diff --git a/apps/client/src/widgets/react/Card.css b/apps/client/src/widgets/react/Card.css
index afdd210f6d..c71f5605b5 100644
--- a/apps/client/src/widgets/react/Card.css
+++ b/apps/client/src/widgets/react/Card.css
@@ -108,6 +108,37 @@
font-size: 1.3em;
}
+/*
+ * Bootstrap sizes a form control to whatever holds it, and a card option's controls do not shrink —
+ * so left alone, a select or a figure takes the whole row and leaves the label a word to the line.
+ * Each is sized to what it actually holds instead.
+ *
+ * Only a control the option holds directly: a select nested inside one (the scale beside a duration)
+ * is sized by whatever built it.
+ */
+.tn-card-option {
+ > select {
+ width: auto;
+ min-width: 150px;
+ /* A choice too long to show is cut short rather than carried off the card. The arrow is a
+ background image with padding reserved for it (forms.css), so it keeps its place. */
+ max-width: min(260px, 100%);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ /* A figure is a few characters wherever it appears — a duration, a count, a percentage — and
+ where a unit sits beside it, the pair belongs to the figure rather than to the row. */
+ input[type="number"] {
+ width: 7em;
+ }
+
+ > .tn-number-unit-pair {
+ width: auto;
+ }
+}
+
.tn-card-option-stacked {
flex-direction: column;
align-items: stretch;
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.css b/apps/client/src/widgets/type_widgets/options/appearance.css
index 6862e34f52..83883deb47 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.css
+++ b/apps/client/src/widgets/type_widgets/options/appearance.css
@@ -10,16 +10,6 @@
}
}
-/* A figure and the unit it is read in, sized to the figure: Bootstrap gives an input group the whole
- width of what holds it, which in a card row is the row. */
-.appearance-number .tn-number-unit-pair {
- width: auto;
-
- input[type="number"] {
- width: 7em;
- }
-}
-
/* Font Option Row */
.font-option {
cursor: pointer;
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsx
index 3d306ff97d..43fe080659 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx
@@ -1,785 +1,783 @@
-import "./appearance.css";
-
-import { FontFamily, OptionNames, SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK } from "@triliumnext/commons";
-import clsx from "clsx";
-import { Fragment } from "preact";
-import { createPortal } from "preact/compat";
-import { useEffect, useMemo, useState } from "preact/hooks";
-
-import zoomService from "../../../components/zoom";
-import { ColorScheme, resolveColorScheme, THEME_FAMILY_SCHEMES } from "../../../services/color_scheme";
-import { t } from "../../../services/i18n";
-import server from "../../../services/server";
-import { isElectron, isMobile, reloadFrontendApp } from "../../../services/utils";
-import { VerticalLayoutIcon } from "../../buttons/global_menu";
-import { Card, CardOption, CardSection } from "../../react/Card";
-import Dropdown from "../../react/Dropdown";
-import FormList, { FormListHeader, FormListItem } from "../../react/FormList";
-import { FormTextBoxWithUnit } from "../../react/FormTextBox";
-import FormToggle from "../../react/FormToggle";
-import HelpButton from "../../react/HelpButton";
-import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
-import Icon from "../../react/Icon";
-import Modal from "../../react/Modal";
-import SegmentedChoice, { SegmentedChoiceOption } from "../../react/SegmentedChoice";
-import Slider from "../../react/Slider";
-import OptionsPageHeader from "./components/OptionsPageHeader";
-import PlatformIndicator from "./components/PlatformIndicator";
-import RadioWithIllustration from "./components/RadioWithIllustration";
-import RelatedSettings from "./components/RelatedSettings";
-import RestartAction from "./components/RestartAction";
-
-const MIN_CONTENT_WIDTH = 640;
-
-interface CustomTheme {
- val: string;
- title: string;
- icon?: string;
- noteId?: string;
-}
-
-interface ThemeFamily {
- key: string;
- title: string;
- icon: string;
- schemes: Record<ColorScheme, string>;
-}
-
-const THEME_FAMILIES: ThemeFamily[] = [
- {
- key: "modern",
- title: t("theme.modern_themes"),
- icon: "bx bx-star",
- schemes: THEME_FAMILY_SCHEMES.modern
- },
- {
- key: "legacy",
- title: t("theme.legacy_themes"),
- icon: "bx bx-history",
- schemes: THEME_FAMILY_SCHEMES.legacy
- }
-];
-
-const COLOR_SCHEMES: SegmentedChoiceOption<ColorScheme>[] = [
- { value: "system", label: t("theme.color_scheme_system"), icon: "bx-brightness-half" },
- { value: "light", label: t("theme.color_scheme_light"), icon: "bx-sun" },
- { value: "dark", label: t("theme.color_scheme_dark"), icon: "bx-moon" }
-];
-
-function resolveTheme(themeVal: string | null): { family: ThemeFamily | null; scheme: ColorScheme; isCustom: boolean } {
- const { family: familyKey, scheme, isCustom } = resolveColorScheme(themeVal);
- const family = THEME_FAMILIES.find(f => f.key === familyKey) ?? null;
- return { family, scheme, isCustom };
-}
-
-interface FontFamilyEntry {
- value: FontFamily;
- label?: string;
-}
-
-interface FontGroup {
- title: string;
- items: FontFamilyEntry[];
-}
-
-const FONT_FAMILIES: FontGroup[] = [
- {
- title: t("fonts.generic-fonts"),
- items: [
- { value: "theme", label: t("fonts.theme_defined") },
- { value: "system", label: t("fonts.system-default") },
- { value: "serif", label: t("fonts.serif") },
- { value: "sans-serif", label: t("fonts.sans-serif") },
- { value: "monospace", label: t("fonts.monospace") }
- ]
- },
- {
- title: t("fonts.sans-serif-system-fonts"),
- items: [{ value: "Arial" }, { value: "Verdana" }, { value: "Helvetica" }, { value: "Tahoma" }, { value: "Trebuchet MS" }, { value: "Microsoft YaHei" }]
- },
- {
- title: t("fonts.serif-system-fonts"),
- items: [{ value: "Times New Roman" }, { value: "Georgia" }, { value: "Garamond" }]
- },
- {
- title: t("fonts.monospace-system-fonts"),
- items: [
- { value: "Courier New" },
- { value: "Brush Script MT" },
- { value: "Impact" },
- { value: "American Typewriter" },
- { value: "Andalé Mono" },
- { value: "Lucida Console" },
- { value: "Monaco" }
- ]
- },
- {
- title: t("fonts.handwriting-system-fonts"),
- items: [{ value: "Bradley Hand" }, { value: "Luminari" }, { value: "Comic Sans MS" }]
- }
-];
-
-export default function AppearanceSettings() {
- return (
- <>
- <OptionsPageHeader />
- <UserInterface />
- {!isMobile() && <LayoutChoices />}
- <Fonts />
- {isElectron() && <ElectronIntegration /> }
- <Performance />
- <MaxContentWidth />
- <RelatedSettings items={[
- {
- title: t("settings_appearance.related_code_blocks"),
- targetPage: "_optionsTextNotes"
- },
- {
- title: t("settings_appearance.related_code_notes"),
- targetPage: "_optionsCodeNotes"
- }
- ]} />
- </>
- );
-}
-
-function UserInterface() {
- const [ theme, setTheme ] = useTriliumOption("theme");
- const [ customThemes, setCustomThemes ] = useState<CustomTheme[]>([]);
- const [ newLayout ] = useTriliumOptionBool("newLayout");
- const [ editedNotesOpenInRibbon, setEditedNotesOpenInRibbon ] = useTriliumOptionBool("editedNotesOpenInRibbon");
-
- useEffect(() => {
- server.get<CustomTheme[]>("options/user-themes").then((userThemes) => {
- setCustomThemes(userThemes);
- });
- }, []);
-
- const resolved = useMemo(() => resolveTheme(theme ?? null), [theme]);
- const isCustom = resolved.isCustom;
-
- // Derive display info for the theme family dropdown
- const currentFamilyLabel = resolved.family?.title
- ?? customThemes.find(ct => ct.val === theme)?.title
- ?? theme ?? "";
- const currentFamilyIcon = resolved.family?.icon
- ?? customThemes.find(ct => ct.val === theme)?.icon
- ?? "bx bx-palette";
-
- const setFamily = (family: ThemeFamily) => {
- // Keep current color scheme when switching families
- setTheme(family.schemes[resolved.scheme]);
- };
-
- const setColorScheme = (scheme: ColorScheme) => {
- if (resolved.family) {
- setTheme(resolved.family.schemes[scheme]);
- }
- };
-
- return (
- <div className="options-section">
- <Card heading={t("theme.title")}>
- <CardOption name="theme" label={t("theme.theme_label")}>
- <Dropdown
- text={<>
- <span className={currentFamilyIcon} style={{ marginRight: "8px" }} />
- {currentFamilyLabel}
- </>}
- mobileBottomSheet
- >
- {THEME_FAMILIES.map(family => (
- <FormListItem
- key={family.key}
- icon={family.icon}
- selected={resolved.family?.key === family.key}
- onClick={() => setFamily(family)}
- badges={family.key === "modern" ? [{ text: t("theme.recommended") }] : undefined}
- >
- {family.title}
- </FormListItem>
- ))}
- {customThemes.length > 0 && (
- <>
- <FormListHeader text={t("theme.custom_themes")} />
- {customThemes.map(ct => (
- <FormListItem
- key={ct.val}
- icon={ct.icon}
- selected={theme === ct.val}
- onClick={() => setTheme(ct.val)}
- >
- {ct.title}
- </FormListItem>
- ))}
- </>
- )}
- </Dropdown>
- </CardOption>
-
- <CardOption
- name="color-scheme"
- label={t("theme.color_scheme")}
- description={isCustom ? t("theme.color_scheme_custom_disabled") : undefined}
- >
- <SegmentedChoice
- options={COLOR_SCHEMES}
- // A custom theme brings its own colours, so the group highlights nothing rather
- // than naming a scheme it is not following.
- currentValue={isCustom ? "" : resolved.scheme}
- onChange={setColorScheme}
- disabled={isCustom}
- collapseOnMobile
- />
- </CardOption>
-
- {!isMobile() && !newLayout && (
- <CardOption
- name="edited-notes-open-in-ribbon"
- label={t("ribbon.edited_notes_message")}
- >
- <FormToggle
- currentValue={editedNotesOpenInRibbon}
- onChange={setEditedNotesOpenInRibbon}
- />
- </CardOption>
- )}
- </Card>
- </div>
- );
-}
-
-/**
- * The two choices that decide the shape of the window, each shown as a picture rather than named in
- * words. Neither fits a settings row — an illustration is too large to stand as a value beside a
- * label — so each takes a card of its own, with what the choice is called as the card's heading.
- *
- * Side by side, being read against one another rather than one after the other; a pane too narrow to
- * hold both puts them on lines of their own instead (see the CSS).
- */
-function LayoutChoices() {
- return (
- <div className="options-section appearance-layout-choices">
- <LayoutOrientation />
- <LayoutStyle />
- </div>
- );
-}
-
-function LayoutStyle() {
- const [ newLayout, setNewLayout ] = useTriliumOptionBool("newLayout");
-
- return (
- <Card className="thumbnail-selector-option-card" heading={t("settings_appearance.ui_layout_style")}>
- <CardSection>
- <RadioWithIllustration
- currentValue={newLayout ? "new-layout" : "old-layout"}
- onChange={async newValue => {
- await setNewLayout(newValue === "new-layout");
- reloadFrontendApp();
- }}
- values={[
- { key: "old-layout", text: t("settings_appearance.ui_old_layout"), illustration: <LayoutIllustration /> },
- { key: "new-layout", text: t("settings_appearance.ui_new_layout"), illustration: <LayoutIllustration isNewLayout /> }
- ]}
- />
- </CardSection>
- </Card>
- );
-}
-
-function LayoutOrientation() {
- const [ layoutOrientation, setLayoutOrientation ] = useTriliumOption("layoutOrientation", true);
-
- return (
- <Card className="thumbnail-selector-option-card" heading={t("settings_appearance.ui_layout_orientation")}>
- <CardSection>
- <RadioWithIllustration
- currentValue={layoutOrientation ?? "vertical"}
- onChange={setLayoutOrientation}
- values={[
- { key: "vertical", text: t("theme.layout-vertical-title"), illustration: <OrientationIllustration orientation="vertical" /> },
- { key: "horizontal", text: t("theme.layout-horizontal-title"), illustration: <OrientationIllustration orientation="horizontal" /> }
- ]}
- />
- </CardSection>
- </Card>
- );
-}
-
-function LayoutIllustration({ isNewLayout }: { isNewLayout?: boolean }) {
- return (
- <div className="old-layout-illustration">
- <div className="launcher-pane">
- <VerticalLayoutIcon />
- <Icon icon="bx bx-send" />
- <Icon icon="bx bx-file-blank" />
- <Icon icon="bx bx-search" />
- </div>
-
- <div className="tree">
- <ul>
- <li>Options</li>
- <ul>
- <li>Appearance</li>
- <li>Shortcuts</li>
- <li>Text Notes</li>
- <li>Code Notes</li>
- <li>Images</li>
- </ul>
- </ul>
- </div>
-
- <div className="main">
- <div className="tab-bar" />
-
- <div className="content">
-
- {(isNewLayout) ? (
- <div className="note-header">
- <div className="note-toolbar">
- <Icon icon="bx bx-dock-right" />
- </div>
- <div className="note-inline-title">
- <Icon className="note-icon" icon="bx bx-leaf" />
- <div className="note-title-row">
- <div className="title">Title</div>
- <div className="subtitle">Just a sample note</div>
- </div>
- </div>
- </div>
- ) : (
- <div>
- <div className="title-bar">
- <Icon icon="bx bx-leaf" />
- <span className="title">Title</span>
- <Icon icon="bx bx-dock-right" />
- </div>
- </div>
- )}
-
- {!isNewLayout && <div className="ribbon">
- <div className="ribbon-header">
- <Icon icon="bx bx-slider" />
- <Icon icon="bx bx-list-check" />
- <Icon icon="bx bx-list-plus" />
- <Icon icon="bx bx-collection" />
- </div>
-
- <div className="ribbon-body">
- <div className="ribbon-body-content" />
- </div>
- </div>}
-
- {isNewLayout && <div className="note-title-actions">
- <Icon icon="bx bx-chevron-down" />{" "}Promoted attributes
- </div>}
-
- <div className="content-inner">
- This is a "demo" document packaged with Trilium to showcase some of its features and also give you some ideas on how you might structure your notes. You can play with it, and modify the note content and tree structure as you wish.
- </div>
-
- {isNewLayout && <div className="status-bar">
- <div className="status-bar-breadcrumb">
- <Icon icon="bx bx-home" />
- <Icon icon="bx bx-chevron-right" />
- Note
- <Icon icon="bx bx-chevron-right" />
- Note
- </div>
-
- <div className="status-bar-actions">
- <Icon icon="bx bx-list-check" />
- <Icon icon="bx bx-info-circle" />
- </div>
- </div>}
- </div>
- </div>
- </div>
- );
-}
-
-function OrientationIllustration({ orientation }: { orientation: "vertical" | "horizontal" }) {
- const isHorizontal = orientation === "horizontal";
-
- return (
- <div className={`orientation-illustration ${orientation}`}>
- {isHorizontal && (
- <div className="tab-bar full-width">
- <div className="tab active" />
- <div className="tab" />
- <div className="tab" />
- </div>
- )}
- {isHorizontal && (
- <div className="launcher-bar horizontal">
- <Icon icon="bx bx-menu" />
- <Icon icon="bx bx-send" />
- <Icon icon="bx bx-file-blank" />
- <Icon icon="bx bx-search" />
- </div>
- )}
- <div className="main-area">
- {!isHorizontal && (
- <div className="launcher-bar vertical">
- <Icon icon="bx bx-menu" />
- <Icon icon="bx bx-send" />
- <Icon icon="bx bx-file-blank" />
- <Icon icon="bx bx-search" />
- </div>
- )}
- <div className="tree-pane">
- <div className="tree-content" />
- </div>
- <div className="content-pane">
- {!isHorizontal && (
- <div className="tab-bar">
- <div className="tab active" />
- <div className="tab" />
- <div className="tab" />
- </div>
- )}
- <div className="note-content" />
- </div>
- </div>
- </div>
- );
-}
-
-function Fonts() {
- const [ overrideThemeFonts, setOverrideThemeFonts ] = useTriliumOptionBool("overrideThemeFonts");
- const [ ligaturesEnabled, setLigaturesEnabled ] = useTriliumOptionBool("monospaceLigaturesEnabled");
- const isEnabled = overrideThemeFonts === true;
-
- return (
- <div className="options-section appearance-fonts">
- <Card heading={t("fonts.fonts")}>
- <CardOption
- name="override-theme-fonts"
- label={t("fonts.custom_fonts")}
- description={t("fonts.not_all_fonts_available")}
- // The four fonts stay on show with the switch off, greyed rather than gone: what
- // is there to be set is the whole reason for turning it on, and a switch with
- // nothing under it says nothing about what it would bring.
- subSectionsVisible
- subSections={[
- <Font key="main" label={t("fonts.main_font")} fontFamilyOption="mainFontFamily" fontSizeOption="mainFontSize" disabled={!isEnabled} />,
- <Font key="tree" label={t("fonts.note_tree_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="treeFontFamily" fontSizeOption="treeFontSize" disabled={!isEnabled} />,
- <Font key="detail" label={t("fonts.note_detail_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="detailFontFamily" fontSizeOption="detailFontSize" disabled={!isEnabled} />,
- <Font key="monospace" label={t("fonts.monospace_font")} description={t("fonts.monospace_font_description")} fontFamilyOption="monospaceFontFamily" fontSizeOption="monospaceFontSize" disabled={!isEnabled} isMonospace />
- ]}
- >
- <FormToggle currentValue={overrideThemeFonts} onChange={setOverrideThemeFonts} />
- </CardOption>
-
- {/*
- * Deliberately not nested under `overrideThemeFonts` like the fonts above: the
- * ligatures come from the *theme's* monospace font, so the setting is needed exactly
- * when custom fonts are off. Gating it would put it out of reach of everyone affected.
- */}
- <CardOption
- name="monospace-ligatures-enabled"
- label={t("fonts.monospace_ligatures")}
- description={t("fonts.monospace_ligatures_description")}
- >
- <FormToggle currentValue={ligaturesEnabled} onChange={setLigaturesEnabled} />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-interface FontProps {
- label: string;
- description?: string;
- sizeDescription?: string;
- fontFamilyOption: OptionNames;
- fontSizeOption: OptionNames;
- disabled?: boolean;
- isMonospace?: boolean;
-}
-
-function Font({ label, description, sizeDescription, fontFamilyOption, fontSizeOption, disabled, isMonospace }: FontProps) {
- const [ fontFamily, setFontFamily ] = useTriliumOption(fontFamilyOption);
- const [ fontSize, setFontSize ] = useTriliumOption(fontSizeOption);
- const [ showModal, setShowModal ] = useState(false);
-
- // Find the current font entry to display
- const currentFont = FONT_FAMILIES
- .flatMap(group => group.items)
- .find(item => item.value === fontFamily);
- const displayLabel = currentFont?.label ?? currentFont?.value ?? fontFamily ?? "";
-
- // Map option name to CSS variable
- const themeCssVariable = {
- mainFontFamily: "var(--main-font-family)",
- treeFontFamily: "var(--tree-font-family)",
- detailFontFamily: "var(--detail-font-family)",
- monospaceFontFamily: "var(--monospace-font-family)"
- }[fontFamilyOption] ?? "inherit";
-
- // Get the CSS font-family value for preview
- const getFontFamily = (value: string) => {
- if (value === "theme") {
- // Use the theme's CSS variable for this font option
- return themeCssVariable;
- }
- if (value === "system") {
- // Use the appropriate system font stack
- return isMonospace ? SYSTEM_MONOSPACE_FONT_STACK : SYSTEM_SANS_SERIF_FONT_STACK;
- }
- return value;
- };
-
- return (
- <>
- <CardOption
- className={clsx("font-option", disabled && "disabled")}
- label={label}
- description={description}
- onAction={disabled ? undefined : () => setShowModal(true)}
- >
- <span className="font-option-preview">
- <span className="font-option-specimen" style={{ fontFamily: getFontFamily(fontFamily ?? ""), fontSize: `${fontSize}%` }}>{displayLabel}</span>
- <span className="bx bx-chevron-right" />
- </span>
- </CardOption>
-
- <FontPickerModal
- show={showModal}
- onHidden={() => setShowModal(false)}
- title={label}
- fontFamily={fontFamily ?? ""}
- fontSize={parseInt(fontSize ?? "100", 10)}
- onFontFamilyChange={setFontFamily}
- onFontSizeChange={(size) => setFontSize(String(size))}
- getFontFamily={getFontFamily}
- sizeDescription={sizeDescription}
- />
- </>
- );
-}
-
-const PREVIEW_TEXT = "The quick brown fox jumps over the lazy dog. 0123456789";
-
-interface FontPickerModalProps {
- show: boolean;
- onHidden: () => void;
- title: string;
- fontFamily: string;
- fontSize: number;
- onFontFamilyChange: (value: string) => void;
- onFontSizeChange: (value: number) => void;
- getFontFamily: (value: string) => string | undefined;
- sizeDescription?: string;
-}
-
-function FontPickerModal({ show, onHidden, title, fontFamily, fontSize, onFontFamilyChange, onFontSizeChange, getFontFamily, sizeDescription }: FontPickerModalProps) {
- return createPortal(
- <Modal
- className="font-picker-modal"
- title={title}
- size="lg"
- show={show}
- onHidden={onHidden}
- stackable
- sidebar={
- <FormList fullHeight wrapperClassName="font-picker-list">
- {FONT_FAMILIES.map(group => (
- <Fragment key={group.title}>
- <FormListHeader text={group.title} />
- {group.items.map(item => (
- <FormListItem
- key={item.value}
- onClick={() => onFontFamilyChange(item.value)}
- checked={fontFamily === item.value}
- selected={fontFamily === item.value}
- >
- <span style={{ fontFamily: getFontFamily(item.value) }}>
- {item.label ?? item.value}
- </span>
- </FormListItem>
- ))}
- </Fragment>
- ))}
- </FormList>
- }
- >
- <div className="font-picker-settings">
- <div className="font-size-control">
- <label>{t("fonts.size")}</label>
- <div className="font-size-slider">
- <Slider
- value={fontSize}
- onChange={onFontSizeChange}
- min={50}
- max={200}
- step={5}
- />
- <span className="font-size-value">{fontSize}%</span>
- </div>
- {sizeDescription && <small className="font-size-description">{sizeDescription}</small>}
- </div>
-
- <div className="font-preview">
- <label>{t("fonts.preview")}</label>
- <div
- className="font-preview-text"
- style={{
- fontFamily: getFontFamily(fontFamily),
- fontSize: `${fontSize}%`
- }}
- >
- {PREVIEW_TEXT}
- </div>
- </div>
- </div>
- </Modal>,
- document.body
- );
-}
-
-function ElectronIntegration() {
- const [ zoomFactor ] = useTriliumOption("zoomFactor");
- const [ nativeTitleBarVisible, setNativeTitleBarVisible ] = useTriliumOptionBool("nativeTitleBarVisible");
- const [ backgroundEffects, setBackgroundEffects ] = useTriliumOptionBool("backgroundEffects");
-
- const zoomPercentage = Math.round(parseFloat(zoomFactor || "1") * 100);
- // Background effects are only supported on Windows 11 and macOS; on Linux they have no
- // visual effect and would only cost the native window shadow.
- const backgroundEffectsSupported = window.glob.platform === "win32" || window.glob.platform === "darwin";
-
- return (
- <>
- <div className="options-section appearance-electron">
- <Card heading={t("electron_integration.desktop-application")}>
- <CardOption
- className="appearance-number"
- name="zoom-factor"
- label={t("electron_integration.zoom-factor")}
- description={t("zoom_factor.description")}
- >
- <FormTextBoxWithUnit
- type="number"
- min={50} max={200} step={10}
- currentValue={String(zoomPercentage)}
- onChange={(v) => zoomService.setZoomFactorAndSave(parseInt(v, 10) / 100)}
- unit={t("units.percentage")}
- />
- </CardOption>
-
- <CardOption
- name="native-title-bar"
- label={t("electron_integration.native-title-bar")}
- description={t("electron_integration.native-title-bar-description")}
- >
- <FormToggle currentValue={nativeTitleBarVisible} onChange={setNativeTitleBarVisible} />
- </CardOption>
-
- <CardOption
- name="background-effects"
- label={<>{t("electron_integration.background-effects")} <PlatformIndicator windows="11" mac /></>}
- description={t("electron_integration.background-effects-description")}
- >
- <FormToggle
- currentValue={backgroundEffects}
- onChange={setBackgroundEffects}
- disabled={nativeTitleBarVisible || !backgroundEffectsSupported}
- />
- </CardOption>
- </Card>
- </div>
-
- <RestartAction text={t("electron_integration.restart-app-button")} icon="bx-refresh" />
- </>
- );
-}
-
-function Performance() {
- const [ motionEnabled, setMotionEnabled ] = useTriliumOptionBool("motionEnabled");
- const [ shadowsEnabled, setShadowsEnabled ] = useTriliumOptionBool("shadowsEnabled");
- const [ backdropEffectsEnabled, setBackdropEffectsEnabled ] = useTriliumOptionBool("backdropEffectsEnabled");
-
- return (
- <div className="options-section">
- <Card heading={t("ui-performance.title")}>
- <CardOption name="motion-enabled" label={t("ui-performance.enable-motion")}>
- <FormToggle currentValue={motionEnabled} onChange={setMotionEnabled} />
- </CardOption>
-
- <CardOption name="shadows-enabled" label={t("ui-performance.enable-shadows")}>
- <FormToggle currentValue={shadowsEnabled} onChange={setShadowsEnabled} />
- </CardOption>
-
- {!isMobile() && (
- <CardOption name="backdrop-effects-enabled" label={t("ui-performance.enable-backdrop-effects")}>
- <FormToggle currentValue={backdropEffectsEnabled} onChange={setBackdropEffectsEnabled} />
- </CardOption>
- )}
-
- {isElectron() && <SmoothScrollEnabledOption />}
-
- {isElectron() && <HardwareAccelerationOption />}
- </Card>
- </div>
- );
-}
-
-function SmoothScrollEnabledOption() {
- const [ smoothScrollEnabled, setSmoothScrollEnabled ] = useTriliumOptionBool("smoothScrollEnabled");
-
- return (
- <CardOption
- name="smooth-scroll-enabled"
- label={t("ui-performance.enable-smooth-scroll")}
- description={t("ui-performance.app-restart-required")}
- >
- <FormToggle currentValue={smoothScrollEnabled} onChange={setSmoothScrollEnabled} />
- </CardOption>
- );
-}
-
-function HardwareAccelerationOption() {
- const [ hardwareAccelerationEnabled, setHardwareAccelerationEnabled ] = useTriliumOptionBool("hardwareAccelerationEnabled");
-
- return (
- <CardOption
- name="hardware-acceleration-enabled"
- label={t("ui-performance.enable-hardware-acceleration")}
- description={t("ui-performance.enable-hardware-acceleration-description")}
- >
- <FormToggle currentValue={hardwareAccelerationEnabled} onChange={setHardwareAccelerationEnabled} />
- </CardOption>
- );
-}
-
-function MaxContentWidth() {
- const [maxContentWidth, setMaxContentWidth] = useTriliumOption("maxContentWidth");
- const [centerContent, setCenterContent] = useTriliumOptionBool("centerContent");
-
- return (
- <div className="options-section">
- <Card
- heading={t("max_content_width.title")}
- description={t("max_content_width.default_description")}
- actions={<HelpButton helpPage="t596jLvPrqkS" />}
- >
- <CardOption
- className="appearance-number"
- name="max-content-width"
- label={t("max_content_width.max_width_label")}
- >
- <FormTextBoxWithUnit
- type="number" min={MIN_CONTENT_WIDTH} step="10"
- currentValue={maxContentWidth} onBlur={setMaxContentWidth}
- unit={t("max_content_width.max_width_unit")}
- />
- </CardOption>
-
- <CardOption name="center-content" label={t("max_content_width.centerContent")}>
- <FormToggle currentValue={centerContent} onChange={setCenterContent} />
- </CardOption>
- </Card>
- </div>
- );
-}
+import "./appearance.css";
+
+import { FontFamily, OptionNames, SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK } from "@triliumnext/commons";
+import clsx from "clsx";
+import { Fragment } from "preact";
+import { createPortal } from "preact/compat";
+import { useEffect, useMemo, useState } from "preact/hooks";
+
+import zoomService from "../../../components/zoom";
+import { ColorScheme, resolveColorScheme, THEME_FAMILY_SCHEMES } from "../../../services/color_scheme";
+import { t } from "../../../services/i18n";
+import server from "../../../services/server";
+import { isElectron, isMobile, reloadFrontendApp } from "../../../services/utils";
+import { VerticalLayoutIcon } from "../../buttons/global_menu";
+import { Card, CardOption, CardSection } from "../../react/Card";
+import Dropdown from "../../react/Dropdown";
+import FormList, { FormListHeader, FormListItem } from "../../react/FormList";
+import { FormTextBoxWithUnit } from "../../react/FormTextBox";
+import FormToggle from "../../react/FormToggle";
+import HelpButton from "../../react/HelpButton";
+import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import Icon from "../../react/Icon";
+import Modal from "../../react/Modal";
+import SegmentedChoice, { SegmentedChoiceOption } from "../../react/SegmentedChoice";
+import Slider from "../../react/Slider";
+import OptionsPageHeader from "./components/OptionsPageHeader";
+import PlatformIndicator from "./components/PlatformIndicator";
+import RadioWithIllustration from "./components/RadioWithIllustration";
+import RelatedSettings from "./components/RelatedSettings";
+import RestartAction from "./components/RestartAction";
+
+const MIN_CONTENT_WIDTH = 640;
+
+interface CustomTheme {
+ val: string;
+ title: string;
+ icon?: string;
+ noteId?: string;
+}
+
+interface ThemeFamily {
+ key: string;
+ title: string;
+ icon: string;
+ schemes: Record<ColorScheme, string>;
+}
+
+const THEME_FAMILIES: ThemeFamily[] = [
+ {
+ key: "modern",
+ title: t("theme.modern_themes"),
+ icon: "bx bx-star",
+ schemes: THEME_FAMILY_SCHEMES.modern
+ },
+ {
+ key: "legacy",
+ title: t("theme.legacy_themes"),
+ icon: "bx bx-history",
+ schemes: THEME_FAMILY_SCHEMES.legacy
+ }
+];
+
+const COLOR_SCHEMES: SegmentedChoiceOption<ColorScheme>[] = [
+ { value: "system", label: t("theme.color_scheme_system"), icon: "bx-brightness-half" },
+ { value: "light", label: t("theme.color_scheme_light"), icon: "bx-sun" },
+ { value: "dark", label: t("theme.color_scheme_dark"), icon: "bx-moon" }
+];
+
+function resolveTheme(themeVal: string | null): { family: ThemeFamily | null; scheme: ColorScheme; isCustom: boolean } {
+ const { family: familyKey, scheme, isCustom } = resolveColorScheme(themeVal);
+ const family = THEME_FAMILIES.find(f => f.key === familyKey) ?? null;
+ return { family, scheme, isCustom };
+}
+
+interface FontFamilyEntry {
+ value: FontFamily;
+ label?: string;
+}
+
+interface FontGroup {
+ title: string;
+ items: FontFamilyEntry[];
+}
+
+const FONT_FAMILIES: FontGroup[] = [
+ {
+ title: t("fonts.generic-fonts"),
+ items: [
+ { value: "theme", label: t("fonts.theme_defined") },
+ { value: "system", label: t("fonts.system-default") },
+ { value: "serif", label: t("fonts.serif") },
+ { value: "sans-serif", label: t("fonts.sans-serif") },
+ { value: "monospace", label: t("fonts.monospace") }
+ ]
+ },
+ {
+ title: t("fonts.sans-serif-system-fonts"),
+ items: [{ value: "Arial" }, { value: "Verdana" }, { value: "Helvetica" }, { value: "Tahoma" }, { value: "Trebuchet MS" }, { value: "Microsoft YaHei" }]
+ },
+ {
+ title: t("fonts.serif-system-fonts"),
+ items: [{ value: "Times New Roman" }, { value: "Georgia" }, { value: "Garamond" }]
+ },
+ {
+ title: t("fonts.monospace-system-fonts"),
+ items: [
+ { value: "Courier New" },
+ { value: "Brush Script MT" },
+ { value: "Impact" },
+ { value: "American Typewriter" },
+ { value: "Andalé Mono" },
+ { value: "Lucida Console" },
+ { value: "Monaco" }
+ ]
+ },
+ {
+ title: t("fonts.handwriting-system-fonts"),
+ items: [{ value: "Bradley Hand" }, { value: "Luminari" }, { value: "Comic Sans MS" }]
+ }
+];
+
+export default function AppearanceSettings() {
+ return (
+ <>
+ <OptionsPageHeader />
+ <UserInterface />
+ {!isMobile() && <LayoutChoices />}
+ <Fonts />
+ {isElectron() && <ElectronIntegration /> }
+ <Performance />
+ <MaxContentWidth />
+ <RelatedSettings items={[
+ {
+ title: t("settings_appearance.related_code_blocks"),
+ targetPage: "_optionsTextNotes"
+ },
+ {
+ title: t("settings_appearance.related_code_notes"),
+ targetPage: "_optionsCodeNotes"
+ }
+ ]} />
+ </>
+ );
+}
+
+function UserInterface() {
+ const [ theme, setTheme ] = useTriliumOption("theme");
+ const [ customThemes, setCustomThemes ] = useState<CustomTheme[]>([]);
+ const [ newLayout ] = useTriliumOptionBool("newLayout");
+ const [ editedNotesOpenInRibbon, setEditedNotesOpenInRibbon ] = useTriliumOptionBool("editedNotesOpenInRibbon");
+
+ useEffect(() => {
+ server.get<CustomTheme[]>("options/user-themes").then((userThemes) => {
+ setCustomThemes(userThemes);
+ });
+ }, []);
+
+ const resolved = useMemo(() => resolveTheme(theme ?? null), [theme]);
+ const isCustom = resolved.isCustom;
+
+ // Derive display info for the theme family dropdown
+ const currentFamilyLabel = resolved.family?.title
+ ?? customThemes.find(ct => ct.val === theme)?.title
+ ?? theme ?? "";
+ const currentFamilyIcon = resolved.family?.icon
+ ?? customThemes.find(ct => ct.val === theme)?.icon
+ ?? "bx bx-palette";
+
+ const setFamily = (family: ThemeFamily) => {
+ // Keep current color scheme when switching families
+ setTheme(family.schemes[resolved.scheme]);
+ };
+
+ const setColorScheme = (scheme: ColorScheme) => {
+ if (resolved.family) {
+ setTheme(resolved.family.schemes[scheme]);
+ }
+ };
+
+ return (
+ <div className="options-section">
+ <Card heading={t("theme.title")}>
+ <CardOption name="theme" label={t("theme.theme_label")}>
+ <Dropdown
+ text={<>
+ <span className={currentFamilyIcon} style={{ marginRight: "8px" }} />
+ {currentFamilyLabel}
+ </>}
+ mobileBottomSheet
+ >
+ {THEME_FAMILIES.map(family => (
+ <FormListItem
+ key={family.key}
+ icon={family.icon}
+ selected={resolved.family?.key === family.key}
+ onClick={() => setFamily(family)}
+ badges={family.key === "modern" ? [{ text: t("theme.recommended") }] : undefined}
+ >
+ {family.title}
+ </FormListItem>
+ ))}
+ {customThemes.length > 0 && (
+ <>
+ <FormListHeader text={t("theme.custom_themes")} />
+ {customThemes.map(ct => (
+ <FormListItem
+ key={ct.val}
+ icon={ct.icon}
+ selected={theme === ct.val}
+ onClick={() => setTheme(ct.val)}
+ >
+ {ct.title}
+ </FormListItem>
+ ))}
+ </>
+ )}
+ </Dropdown>
+ </CardOption>
+
+ <CardOption
+ name="color-scheme"
+ label={t("theme.color_scheme")}
+ description={isCustom ? t("theme.color_scheme_custom_disabled") : undefined}
+ >
+ <SegmentedChoice
+ options={COLOR_SCHEMES}
+ // A custom theme brings its own colours, so the group highlights nothing rather
+ // than naming a scheme it is not following.
+ currentValue={isCustom ? "" : resolved.scheme}
+ onChange={setColorScheme}
+ disabled={isCustom}
+ collapseOnMobile
+ />
+ </CardOption>
+
+ {!isMobile() && !newLayout && (
+ <CardOption
+ name="edited-notes-open-in-ribbon"
+ label={t("ribbon.edited_notes_message")}
+ >
+ <FormToggle
+ currentValue={editedNotesOpenInRibbon}
+ onChange={setEditedNotesOpenInRibbon}
+ />
+ </CardOption>
+ )}
+ </Card>
+ </div>
+ );
+}
+
+/**
+ * The two choices that decide the shape of the window, each shown as a picture rather than named in
+ * words. Neither fits a settings row — an illustration is too large to stand as a value beside a
+ * label — so each takes a card of its own, with what the choice is called as the card's heading.
+ *
+ * Side by side, being read against one another rather than one after the other; a pane too narrow to
+ * hold both puts them on lines of their own instead (see the CSS).
+ */
+function LayoutChoices() {
+ return (
+ <div className="options-section appearance-layout-choices">
+ <LayoutOrientation />
+ <LayoutStyle />
+ </div>
+ );
+}
+
+function LayoutStyle() {
+ const [ newLayout, setNewLayout ] = useTriliumOptionBool("newLayout");
+
+ return (
+ <Card className="thumbnail-selector-option-card" heading={t("settings_appearance.ui_layout_style")}>
+ <CardSection>
+ <RadioWithIllustration
+ currentValue={newLayout ? "new-layout" : "old-layout"}
+ onChange={async newValue => {
+ await setNewLayout(newValue === "new-layout");
+ reloadFrontendApp();
+ }}
+ values={[
+ { key: "old-layout", text: t("settings_appearance.ui_old_layout"), illustration: <LayoutIllustration /> },
+ { key: "new-layout", text: t("settings_appearance.ui_new_layout"), illustration: <LayoutIllustration isNewLayout /> }
+ ]}
+ />
+ </CardSection>
+ </Card>
+ );
+}
+
+function LayoutOrientation() {
+ const [ layoutOrientation, setLayoutOrientation ] = useTriliumOption("layoutOrientation", true);
+
+ return (
+ <Card className="thumbnail-selector-option-card" heading={t("settings_appearance.ui_layout_orientation")}>
+ <CardSection>
+ <RadioWithIllustration
+ currentValue={layoutOrientation ?? "vertical"}
+ onChange={setLayoutOrientation}
+ values={[
+ { key: "vertical", text: t("theme.layout-vertical-title"), illustration: <OrientationIllustration orientation="vertical" /> },
+ { key: "horizontal", text: t("theme.layout-horizontal-title"), illustration: <OrientationIllustration orientation="horizontal" /> }
+ ]}
+ />
+ </CardSection>
+ </Card>
+ );
+}
+
+function LayoutIllustration({ isNewLayout }: { isNewLayout?: boolean }) {
+ return (
+ <div className="old-layout-illustration">
+ <div className="launcher-pane">
+ <VerticalLayoutIcon />
+ <Icon icon="bx bx-send" />
+ <Icon icon="bx bx-file-blank" />
+ <Icon icon="bx bx-search" />
+ </div>
+
+ <div className="tree">
+ <ul>
+ <li>Options</li>
+ <ul>
+ <li>Appearance</li>
+ <li>Shortcuts</li>
+ <li>Text Notes</li>
+ <li>Code Notes</li>
+ <li>Images</li>
+ </ul>
+ </ul>
+ </div>
+
+ <div className="main">
+ <div className="tab-bar" />
+
+ <div className="content">
+
+ {(isNewLayout) ? (
+ <div className="note-header">
+ <div className="note-toolbar">
+ <Icon icon="bx bx-dock-right" />
+ </div>
+ <div className="note-inline-title">
+ <Icon className="note-icon" icon="bx bx-leaf" />
+ <div className="note-title-row">
+ <div className="title">Title</div>
+ <div className="subtitle">Just a sample note</div>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div>
+ <div className="title-bar">
+ <Icon icon="bx bx-leaf" />
+ <span className="title">Title</span>
+ <Icon icon="bx bx-dock-right" />
+ </div>
+ </div>
+ )}
+
+ {!isNewLayout && <div className="ribbon">
+ <div className="ribbon-header">
+ <Icon icon="bx bx-slider" />
+ <Icon icon="bx bx-list-check" />
+ <Icon icon="bx bx-list-plus" />
+ <Icon icon="bx bx-collection" />
+ </div>
+
+ <div className="ribbon-body">
+ <div className="ribbon-body-content" />
+ </div>
+ </div>}
+
+ {isNewLayout && <div className="note-title-actions">
+ <Icon icon="bx bx-chevron-down" />{" "}Promoted attributes
+ </div>}
+
+ <div className="content-inner">
+ This is a "demo" document packaged with Trilium to showcase some of its features and also give you some ideas on how you might structure your notes. You can play with it, and modify the note content and tree structure as you wish.
+ </div>
+
+ {isNewLayout && <div className="status-bar">
+ <div className="status-bar-breadcrumb">
+ <Icon icon="bx bx-home" />
+ <Icon icon="bx bx-chevron-right" />
+ Note
+ <Icon icon="bx bx-chevron-right" />
+ Note
+ </div>
+
+ <div className="status-bar-actions">
+ <Icon icon="bx bx-list-check" />
+ <Icon icon="bx bx-info-circle" />
+ </div>
+ </div>}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function OrientationIllustration({ orientation }: { orientation: "vertical" | "horizontal" }) {
+ const isHorizontal = orientation === "horizontal";
+
+ return (
+ <div className={`orientation-illustration ${orientation}`}>
+ {isHorizontal && (
+ <div className="tab-bar full-width">
+ <div className="tab active" />
+ <div className="tab" />
+ <div className="tab" />
+ </div>
+ )}
+ {isHorizontal && (
+ <div className="launcher-bar horizontal">
+ <Icon icon="bx bx-menu" />
+ <Icon icon="bx bx-send" />
+ <Icon icon="bx bx-file-blank" />
+ <Icon icon="bx bx-search" />
+ </div>
+ )}
+ <div className="main-area">
+ {!isHorizontal && (
+ <div className="launcher-bar vertical">
+ <Icon icon="bx bx-menu" />
+ <Icon icon="bx bx-send" />
+ <Icon icon="bx bx-file-blank" />
+ <Icon icon="bx bx-search" />
+ </div>
+ )}
+ <div className="tree-pane">
+ <div className="tree-content" />
+ </div>
+ <div className="content-pane">
+ {!isHorizontal && (
+ <div className="tab-bar">
+ <div className="tab active" />
+ <div className="tab" />
+ <div className="tab" />
+ </div>
+ )}
+ <div className="note-content" />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Fonts() {
+ const [ overrideThemeFonts, setOverrideThemeFonts ] = useTriliumOptionBool("overrideThemeFonts");
+ const [ ligaturesEnabled, setLigaturesEnabled ] = useTriliumOptionBool("monospaceLigaturesEnabled");
+ const isEnabled = overrideThemeFonts === true;
+
+ return (
+ <div className="options-section appearance-fonts">
+ <Card heading={t("fonts.fonts")}>
+ <CardOption
+ name="override-theme-fonts"
+ label={t("fonts.custom_fonts")}
+ description={t("fonts.not_all_fonts_available")}
+ // The four fonts stay on show with the switch off, greyed rather than gone: what
+ // is there to be set is the whole reason for turning it on, and a switch with
+ // nothing under it says nothing about what it would bring.
+ subSectionsVisible
+ subSections={[
+ <Font key="main" label={t("fonts.main_font")} fontFamilyOption="mainFontFamily" fontSizeOption="mainFontSize" disabled={!isEnabled} />,
+ <Font key="tree" label={t("fonts.note_tree_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="treeFontFamily" fontSizeOption="treeFontSize" disabled={!isEnabled} />,
+ <Font key="detail" label={t("fonts.note_detail_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="detailFontFamily" fontSizeOption="detailFontSize" disabled={!isEnabled} />,
+ <Font key="monospace" label={t("fonts.monospace_font")} description={t("fonts.monospace_font_description")} fontFamilyOption="monospaceFontFamily" fontSizeOption="monospaceFontSize" disabled={!isEnabled} isMonospace />
+ ]}
+ >
+ <FormToggle currentValue={overrideThemeFonts} onChange={setOverrideThemeFonts} />
+ </CardOption>
+
+ {/*
+ * Deliberately not nested under `overrideThemeFonts` like the fonts above: the
+ * ligatures come from the *theme's* monospace font, so the setting is needed exactly
+ * when custom fonts are off. Gating it would put it out of reach of everyone affected.
+ */}
+ <CardOption
+ name="monospace-ligatures-enabled"
+ label={t("fonts.monospace_ligatures")}
+ description={t("fonts.monospace_ligatures_description")}
+ >
+ <FormToggle currentValue={ligaturesEnabled} onChange={setLigaturesEnabled} />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+interface FontProps {
+ label: string;
+ description?: string;
+ sizeDescription?: string;
+ fontFamilyOption: OptionNames;
+ fontSizeOption: OptionNames;
+ disabled?: boolean;
+ isMonospace?: boolean;
+}
+
+function Font({ label, description, sizeDescription, fontFamilyOption, fontSizeOption, disabled, isMonospace }: FontProps) {
+ const [ fontFamily, setFontFamily ] = useTriliumOption(fontFamilyOption);
+ const [ fontSize, setFontSize ] = useTriliumOption(fontSizeOption);
+ const [ showModal, setShowModal ] = useState(false);
+
+ // Find the current font entry to display
+ const currentFont = FONT_FAMILIES
+ .flatMap(group => group.items)
+ .find(item => item.value === fontFamily);
+ const displayLabel = currentFont?.label ?? currentFont?.value ?? fontFamily ?? "";
+
+ // Map option name to CSS variable
+ const themeCssVariable = {
+ mainFontFamily: "var(--main-font-family)",
+ treeFontFamily: "var(--tree-font-family)",
+ detailFontFamily: "var(--detail-font-family)",
+ monospaceFontFamily: "var(--monospace-font-family)"
+ }[fontFamilyOption] ?? "inherit";
+
+ // Get the CSS font-family value for preview
+ const getFontFamily = (value: string) => {
+ if (value === "theme") {
+ // Use the theme's CSS variable for this font option
+ return themeCssVariable;
+ }
+ if (value === "system") {
+ // Use the appropriate system font stack
+ return isMonospace ? SYSTEM_MONOSPACE_FONT_STACK : SYSTEM_SANS_SERIF_FONT_STACK;
+ }
+ return value;
+ };
+
+ return (
+ <>
+ <CardOption
+ className={clsx("font-option", disabled && "disabled")}
+ label={label}
+ description={description}
+ onAction={disabled ? undefined : () => setShowModal(true)}
+ >
+ <span className="font-option-preview">
+ <span className="font-option-specimen" style={{ fontFamily: getFontFamily(fontFamily ?? ""), fontSize: `${fontSize}%` }}>{displayLabel}</span>
+ <span className="bx bx-chevron-right" />
+ </span>
+ </CardOption>
+
+ <FontPickerModal
+ show={showModal}
+ onHidden={() => setShowModal(false)}
+ title={label}
+ fontFamily={fontFamily ?? ""}
+ fontSize={parseInt(fontSize ?? "100", 10)}
+ onFontFamilyChange={setFontFamily}
+ onFontSizeChange={(size) => setFontSize(String(size))}
+ getFontFamily={getFontFamily}
+ sizeDescription={sizeDescription}
+ />
+ </>
+ );
+}
+
+const PREVIEW_TEXT = "The quick brown fox jumps over the lazy dog. 0123456789";
+
+interface FontPickerModalProps {
+ show: boolean;
+ onHidden: () => void;
+ title: string;
+ fontFamily: string;
+ fontSize: number;
+ onFontFamilyChange: (value: string) => void;
+ onFontSizeChange: (value: number) => void;
+ getFontFamily: (value: string) => string | undefined;
+ sizeDescription?: string;
+}
+
+function FontPickerModal({ show, onHidden, title, fontFamily, fontSize, onFontFamilyChange, onFontSizeChange, getFontFamily, sizeDescription }: FontPickerModalProps) {
+ return createPortal(
+ <Modal
+ className="font-picker-modal"
+ title={title}
+ size="lg"
+ show={show}
+ onHidden={onHidden}
+ stackable
+ sidebar={
+ <FormList fullHeight wrapperClassName="font-picker-list">
+ {FONT_FAMILIES.map(group => (
+ <Fragment key={group.title}>
+ <FormListHeader text={group.title} />
+ {group.items.map(item => (
+ <FormListItem
+ key={item.value}
+ onClick={() => onFontFamilyChange(item.value)}
+ checked={fontFamily === item.value}
+ selected={fontFamily === item.value}
+ >
+ <span style={{ fontFamily: getFontFamily(item.value) }}>
+ {item.label ?? item.value}
+ </span>
+ </FormListItem>
+ ))}
+ </Fragment>
+ ))}
+ </FormList>
+ }
+ >
+ <div className="font-picker-settings">
+ <div className="font-size-control">
+ <label>{t("fonts.size")}</label>
+ <div className="font-size-slider">
+ <Slider
+ value={fontSize}
+ onChange={onFontSizeChange}
+ min={50}
+ max={200}
+ step={5}
+ />
+ <span className="font-size-value">{fontSize}%</span>
+ </div>
+ {sizeDescription && <small className="font-size-description">{sizeDescription}</small>}
+ </div>
+
+ <div className="font-preview">
+ <label>{t("fonts.preview")}</label>
+ <div
+ className="font-preview-text"
+ style={{
+ fontFamily: getFontFamily(fontFamily),
+ fontSize: `${fontSize}%`
+ }}
+ >
+ {PREVIEW_TEXT}
+ </div>
+ </div>
+ </div>
+ </Modal>,
+ document.body
+ );
+}
+
+function ElectronIntegration() {
+ const [ zoomFactor ] = useTriliumOption("zoomFactor");
+ const [ nativeTitleBarVisible, setNativeTitleBarVisible ] = useTriliumOptionBool("nativeTitleBarVisible");
+ const [ backgroundEffects, setBackgroundEffects ] = useTriliumOptionBool("backgroundEffects");
+
+ const zoomPercentage = Math.round(parseFloat(zoomFactor || "1") * 100);
+ // Background effects are only supported on Windows 11 and macOS; on Linux they have no
+ // visual effect and would only cost the native window shadow.
+ const backgroundEffectsSupported = window.glob.platform === "win32" || window.glob.platform === "darwin";
+
+ return (
+ <>
+ <div className="options-section appearance-electron">
+ <Card heading={t("electron_integration.desktop-application")}>
+ <CardOption
+ name="zoom-factor"
+ label={t("electron_integration.zoom-factor")}
+ description={t("zoom_factor.description")}
+ >
+ <FormTextBoxWithUnit
+ type="number"
+ min={50} max={200} step={10}
+ currentValue={String(zoomPercentage)}
+ onChange={(v) => zoomService.setZoomFactorAndSave(parseInt(v, 10) / 100)}
+ unit={t("units.percentage")}
+ />
+ </CardOption>
+
+ <CardOption
+ name="native-title-bar"
+ label={t("electron_integration.native-title-bar")}
+ description={t("electron_integration.native-title-bar-description")}
+ >
+ <FormToggle currentValue={nativeTitleBarVisible} onChange={setNativeTitleBarVisible} />
+ </CardOption>
+
+ <CardOption
+ name="background-effects"
+ label={<>{t("electron_integration.background-effects")} <PlatformIndicator windows="11" mac /></>}
+ description={t("electron_integration.background-effects-description")}
+ >
+ <FormToggle
+ currentValue={backgroundEffects}
+ onChange={setBackgroundEffects}
+ disabled={nativeTitleBarVisible || !backgroundEffectsSupported}
+ />
+ </CardOption>
+ </Card>
+ </div>
+
+ <RestartAction text={t("electron_integration.restart-app-button")} icon="bx-refresh" />
+ </>
+ );
+}
+
+function Performance() {
+ const [ motionEnabled, setMotionEnabled ] = useTriliumOptionBool("motionEnabled");
+ const [ shadowsEnabled, setShadowsEnabled ] = useTriliumOptionBool("shadowsEnabled");
+ const [ backdropEffectsEnabled, setBackdropEffectsEnabled ] = useTriliumOptionBool("backdropEffectsEnabled");
+
+ return (
+ <div className="options-section">
+ <Card heading={t("ui-performance.title")}>
+ <CardOption name="motion-enabled" label={t("ui-performance.enable-motion")}>
+ <FormToggle currentValue={motionEnabled} onChange={setMotionEnabled} />
+ </CardOption>
+
+ <CardOption name="shadows-enabled" label={t("ui-performance.enable-shadows")}>
+ <FormToggle currentValue={shadowsEnabled} onChange={setShadowsEnabled} />
+ </CardOption>
+
+ {!isMobile() && (
+ <CardOption name="backdrop-effects-enabled" label={t("ui-performance.enable-backdrop-effects")}>
+ <FormToggle currentValue={backdropEffectsEnabled} onChange={setBackdropEffectsEnabled} />
+ </CardOption>
+ )}
+
+ {isElectron() && <SmoothScrollEnabledOption />}
+
+ {isElectron() && <HardwareAccelerationOption />}
+ </Card>
+ </div>
+ );
+}
+
+function SmoothScrollEnabledOption() {
+ const [ smoothScrollEnabled, setSmoothScrollEnabled ] = useTriliumOptionBool("smoothScrollEnabled");
+
+ return (
+ <CardOption
+ name="smooth-scroll-enabled"
+ label={t("ui-performance.enable-smooth-scroll")}
+ description={t("ui-performance.app-restart-required")}
+ >
+ <FormToggle currentValue={smoothScrollEnabled} onChange={setSmoothScrollEnabled} />
+ </CardOption>
+ );
+}
+
+function HardwareAccelerationOption() {
+ const [ hardwareAccelerationEnabled, setHardwareAccelerationEnabled ] = useTriliumOptionBool("hardwareAccelerationEnabled");
+
+ return (
+ <CardOption
+ name="hardware-acceleration-enabled"
+ label={t("ui-performance.enable-hardware-acceleration")}
+ description={t("ui-performance.enable-hardware-acceleration-description")}
+ >
+ <FormToggle currentValue={hardwareAccelerationEnabled} onChange={setHardwareAccelerationEnabled} />
+ </CardOption>
+ );
+}
+
+function MaxContentWidth() {
+ const [maxContentWidth, setMaxContentWidth] = useTriliumOption("maxContentWidth");
+ const [centerContent, setCenterContent] = useTriliumOptionBool("centerContent");
+
+ return (
+ <div className="options-section">
+ <Card
+ heading={t("max_content_width.title")}
+ description={t("max_content_width.default_description")}
+ actions={<HelpButton helpPage="t596jLvPrqkS" />}
+ >
+ <CardOption
+ name="max-content-width"
+ label={t("max_content_width.max_width_label")}
+ >
+ <FormTextBoxWithUnit
+ type="number" min={MIN_CONTENT_WIDTH} step="10"
+ currentValue={maxContentWidth} onBlur={setMaxContentWidth}
+ unit={t("max_content_width.max_width_unit")}
+ />
+ </CardOption>
+
+ <CardOption name="center-content" label={t("max_content_width.centerContent")}>
+ <FormToggle currentValue={centerContent} onChange={setCenterContent} />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/options/code_notes.css b/apps/client/src/widgets/type_widgets/options/code_notes.css
index 11aaa7127a..6866eaa38e 100644
--- a/apps/client/src/widgets/type_widgets/options/code_notes.css
+++ b/apps/client/src/widgets/type_widgets/options/code_notes.css
@@ -1,25 +1,3 @@
-/* Bootstrap gives a select the whole width of what holds it, which in a card row leaves the label
- beside it a word to the line. Sized to what it offers instead, and cut short rather than carried
- across the row. */
-.code-notes-appearance select {
- width: auto;
- min-width: 150px;
- max-width: 260px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* A figure and the unit it is read in, sized to the figure: Bootstrap gives an input group the whole
- width of what holds it, which in a card row is the row. */
-.code-notes-number .tn-number-unit-pair {
- width: auto;
-
- input[type="number"] {
- width: 7em;
- }
-}
-
/* Clipped to the corners the last segment rounds, which the editor inside would otherwise paint over. */
.code-note-preview {
overflow: hidden;
diff --git a/apps/client/src/widgets/type_widgets/options/code_notes.tsx b/apps/client/src/widgets/type_widgets/options/code_notes.tsx
index 5de85184e5..615c68ca87 100644
--- a/apps/client/src/widgets/type_widgets/options/code_notes.tsx
+++ b/apps/client/src/widgets/type_widgets/options/code_notes.tsx
@@ -1,236 +1,234 @@
-import "./code_notes.css";
-
-import CodeMirror, { ColorThemes, getThemeById, type ThemeVariant } from "@triliumnext/codemirror";
-import { useEffect, useMemo, useRef } from "preact/hooks";
-
-import { t } from "../../../services/i18n";
-import { Card, CardOption, CardSection } from "../../react/Card";
-import FormSelect from "../../react/FormSelect";
-import { FormTextBoxWithUnit } from "../../react/FormTextBox";
-import FormToggle from "../../react/FormToggle";
-import { useColorScheme, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
-import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";
-import { CodeMimeTypesList } from "./code_mime_types_list";
-import OptionsPageHeader from "./components/OptionsPageHeader";
-import ThemeModeSelector from "./components/ThemeModeSelector";
-import codeNoteSample from "./samples/code_note.txt?raw";
-
-const SAMPLE_MIME = "application/typescript";
-
-export default function CodeNoteSettings() {
- const [codeLineWrapEnabled, setCodeLineWrapEnabled] = useTriliumOptionBool("codeLineWrapEnabled");
- const [codeNoteTabWidth] = useTriliumOption("codeNoteTabWidth");
-
- return (
- <>
- <OptionsPageHeader />
- <Editor wordWrapping={codeLineWrapEnabled} setWordWrapping={setCodeLineWrapEnabled} />
- <Appearance wordWrapping={codeLineWrapEnabled} indentSize={parseInt(codeNoteTabWidth) || 4} />
- <CodeMimeTypes />
- </>
- );
-}
-
-interface EditorProps {
- wordWrapping: boolean;
- setWordWrapping: (newValue: boolean) => void;
-}
-
-function Editor({ wordWrapping, setWordWrapping }: EditorProps) {
- const [vimKeymapEnabled, setVimKeymapEnabled] = useTriliumOptionBool("vimKeymapEnabled");
- const [autoReadonlySize, setAutoReadonlySize] = useTriliumOption("autoReadonlySizeCode");
- const [codeNoteTabWidth, setCodeNoteTabWidth] = useTriliumOption("codeNoteTabWidth");
-
- return (
- <div className="options-section">
- <Card heading={t("code-editor-options.title")}>
- <CardOption name="word-wrap" label={t("code_theme.word_wrapping")}>
- <FormToggle currentValue={wordWrapping} onChange={setWordWrapping} />
- </CardOption>
-
- {/* Avoid using "code" in the name of numeric inputs to prevent KeepassXC from triggering. */}
- <CardOption
- className="code-notes-number"
- name="editor-tab-width"
- label={t("code-editor-options.tab_width")}
- >
- <FormTextBoxWithUnit
- type="number" min={1} max={16} step={1}
- unit={t("code-editor-options.tab_width_unit")}
- currentValue={codeNoteTabWidth}
- onChange={setCodeNoteTabWidth}
- onBlur={setCodeNoteTabWidth}
- />
- </CardOption>
-
- <CardOption
- className="code-notes-number"
- name="source-readonly-threshold"
- label={t("code_auto_read_only_size.label")}
- description={t("text_auto_read_only_size.description")}
- >
- <FormTextBoxWithUnit
- type="number" min={0}
- unit={t("text_auto_read_only_size.unit")}
- currentValue={autoReadonlySize}
- onBlur={setAutoReadonlySize}
- />
- </CardOption>
-
- <CardOption
- name="vim-keymap-enabled"
- label={t("vim_key_bindings.use_vim_keybindings_in_code_notes")}
- description={t("vim_key_bindings.enable_vim_keybindings")}
- >
- <FormToggle currentValue={vimKeymapEnabled} onChange={setVimKeymapEnabled} />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-interface AppearanceProps {
- wordWrapping: boolean;
- indentSize: number;
-}
-
-function useFilteredThemes(variant?: ThemeVariant) {
- return useMemo(() => {
- return ColorThemes
- .filter((theme) => !variant || theme.variant === variant)
- .map(({ id, name }) => ({
- id: `default:${id}`,
- name
- }));
- }, [variant]);
-}
-
-function Appearance({ wordWrapping, indentSize }: AppearanceProps) {
- const [codeNoteTheme, setCodeNoteTheme] = useTriliumOption("codeNoteTheme");
- const [matchesApp, setMatchesApp] = useTriliumOptionBool("codeNoteThemeMatchesApp");
- const [lightTheme, setLightTheme] = useTriliumOption("codeNoteThemeLight");
- const [darkTheme, setDarkTheme] = useTriliumOption("codeNoteThemeDark");
-
- const colorScheme = useColorScheme();
- const allThemes = useFilteredThemes();
- const lightThemes = useFilteredThemes("light");
- const darkThemes = useFilteredThemes("dark");
-
- const effectiveTheme = matchesApp
- ? (colorScheme === "dark" ? darkTheme : lightTheme)
- : codeNoteTheme;
-
- return (
- <div className="options-section code-notes-appearance">
- <Card heading={t("code_theme.title")}>
- <ThemeModeSelector matchesApp={matchesApp} onMatchesAppChange={setMatchesApp} />
-
- {matchesApp ? (
- <>
- <CardOption name="light-theme" label={t("code_theme.light_theme")}>
- <FormSelect
- values={lightThemes}
- keyProperty="id" titleProperty="name"
- currentValue={lightTheme} onChange={setLightTheme}
- />
- </CardOption>
- <CardOption name="dark-theme" label={t("code_theme.dark_theme")}>
- <FormSelect
- values={darkThemes}
- keyProperty="id" titleProperty="name"
- currentValue={darkTheme} onChange={setDarkTheme}
- />
- </CardOption>
- </>
- ) : (
- <CardOption name="color-scheme" label={t("code_theme.color-scheme")}>
- <FormSelect
- values={allThemes}
- keyProperty="id" titleProperty="name"
- currentValue={codeNoteTheme} onChange={setCodeNoteTheme}
- />
- </CardOption>
- )}
-
- {/* The whole segment, edge to edge: a specimen of the editor rather than a control
- standing beside a label. */}
- <CardSection className="code-note-preview" noPadding>
- <CodeNotePreview wordWrapping={wordWrapping} themeName={effectiveTheme} indentSize={indentSize} />
- </CardSection>
- </Card>
- </div>
- );
-}
-
-function CodeNotePreview({ themeName, wordWrapping, indentSize }: { themeName: string, wordWrapping: boolean, indentSize: number }) {
- const editorRef = useRef<CodeMirror>(null);
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- // Clean up previous instance.
- editorRef.current?.destroy();
- containerRef.current.innerHTML = "";
-
- // Set up a new instance.
- const editor = new CodeMirror({
- parent: containerRef.current
- });
- editor.setText(codeNoteSample);
- editor.setMimeType(SAMPLE_MIME);
- editorRef.current = editor;
- }, []);
-
- useEffect(() => {
- editorRef.current?.setLineWrapping(wordWrapping);
- }, [ wordWrapping ]);
-
- useEffect(() => {
- const editor = editorRef.current;
- if (!editor) return;
- editor.setIndentSize(indentSize);
- editor.setText(reindentSample(codeNoteSample, indentSize));
- }, [ indentSize ]);
-
- useEffect(() => {
- if (themeName?.startsWith(DEFAULT_PREFIX)) {
- const theme = getThemeById(themeName.substring(DEFAULT_PREFIX.length));
- if (theme) {
- editorRef.current?.setTheme(theme);
- }
- }
- }, [ themeName ]);
-
- return (
- <div
- ref={containerRef}
- class="note-detail-readonly-code-content"
- style={{ margin: 0, height: "200px" }}
- />
- );
-}
-
-const SAMPLE_BASE_INDENT = 4;
-
-function reindentSample(sample: string, indentSize: number): string {
- return sample.replace(/^( +)/gm, (match) => {
- const level = match.length / SAMPLE_BASE_INDENT;
- return " ".repeat(Math.round(level) * indentSize);
- });
-}
-
-function CodeMimeTypes() {
- return (
- <div className="options-section">
- <Card heading={t("code_mime_types.title")}>
- <CardSection>
- <CodeMimeTypesList />
- </CardSection>
- </Card>
- </div>
- );
-}
-
+import "./code_notes.css";
+
+import CodeMirror, { ColorThemes, getThemeById, type ThemeVariant } from "@triliumnext/codemirror";
+import { useEffect, useMemo, useRef } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import { Card, CardOption, CardSection } from "../../react/Card";
+import FormSelect from "../../react/FormSelect";
+import { FormTextBoxWithUnit } from "../../react/FormTextBox";
+import FormToggle from "../../react/FormToggle";
+import { useColorScheme, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";
+import { CodeMimeTypesList } from "./code_mime_types_list";
+import OptionsPageHeader from "./components/OptionsPageHeader";
+import ThemeModeSelector from "./components/ThemeModeSelector";
+import codeNoteSample from "./samples/code_note.txt?raw";
+
+const SAMPLE_MIME = "application/typescript";
+
+export default function CodeNoteSettings() {
+ const [codeLineWrapEnabled, setCodeLineWrapEnabled] = useTriliumOptionBool("codeLineWrapEnabled");
+ const [codeNoteTabWidth] = useTriliumOption("codeNoteTabWidth");
+
+ return (
+ <>
+ <OptionsPageHeader />
+ <Editor wordWrapping={codeLineWrapEnabled} setWordWrapping={setCodeLineWrapEnabled} />
+ <Appearance wordWrapping={codeLineWrapEnabled} indentSize={parseInt(codeNoteTabWidth) || 4} />
+ <CodeMimeTypes />
+ </>
+ );
+}
+
+interface EditorProps {
+ wordWrapping: boolean;
+ setWordWrapping: (newValue: boolean) => void;
+}
+
+function Editor({ wordWrapping, setWordWrapping }: EditorProps) {
+ const [vimKeymapEnabled, setVimKeymapEnabled] = useTriliumOptionBool("vimKeymapEnabled");
+ const [autoReadonlySize, setAutoReadonlySize] = useTriliumOption("autoReadonlySizeCode");
+ const [codeNoteTabWidth, setCodeNoteTabWidth] = useTriliumOption("codeNoteTabWidth");
+
+ return (
+ <div className="options-section">
+ <Card heading={t("code-editor-options.title")}>
+ <CardOption name="word-wrap" label={t("code_theme.word_wrapping")}>
+ <FormToggle currentValue={wordWrapping} onChange={setWordWrapping} />
+ </CardOption>
+
+ {/* Avoid using "code" in the name of numeric inputs to prevent KeepassXC from triggering. */}
+ <CardOption
+ name="editor-tab-width"
+ label={t("code-editor-options.tab_width")}
+ >
+ <FormTextBoxWithUnit
+ type="number" min={1} max={16} step={1}
+ unit={t("code-editor-options.tab_width_unit")}
+ currentValue={codeNoteTabWidth}
+ onChange={setCodeNoteTabWidth}
+ onBlur={setCodeNoteTabWidth}
+ />
+ </CardOption>
+
+ <CardOption
+ name="source-readonly-threshold"
+ label={t("code_auto_read_only_size.label")}
+ description={t("text_auto_read_only_size.description")}
+ >
+ <FormTextBoxWithUnit
+ type="number" min={0}
+ unit={t("text_auto_read_only_size.unit")}
+ currentValue={autoReadonlySize}
+ onBlur={setAutoReadonlySize}
+ />
+ </CardOption>
+
+ <CardOption
+ name="vim-keymap-enabled"
+ label={t("vim_key_bindings.use_vim_keybindings_in_code_notes")}
+ description={t("vim_key_bindings.enable_vim_keybindings")}
+ >
+ <FormToggle currentValue={vimKeymapEnabled} onChange={setVimKeymapEnabled} />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+interface AppearanceProps {
+ wordWrapping: boolean;
+ indentSize: number;
+}
+
+function useFilteredThemes(variant?: ThemeVariant) {
+ return useMemo(() => {
+ return ColorThemes
+ .filter((theme) => !variant || theme.variant === variant)
+ .map(({ id, name }) => ({
+ id: `default:${id}`,
+ name
+ }));
+ }, [variant]);
+}
+
+function Appearance({ wordWrapping, indentSize }: AppearanceProps) {
+ const [codeNoteTheme, setCodeNoteTheme] = useTriliumOption("codeNoteTheme");
+ const [matchesApp, setMatchesApp] = useTriliumOptionBool("codeNoteThemeMatchesApp");
+ const [lightTheme, setLightTheme] = useTriliumOption("codeNoteThemeLight");
+ const [darkTheme, setDarkTheme] = useTriliumOption("codeNoteThemeDark");
+
+ const colorScheme = useColorScheme();
+ const allThemes = useFilteredThemes();
+ const lightThemes = useFilteredThemes("light");
+ const darkThemes = useFilteredThemes("dark");
+
+ const effectiveTheme = matchesApp
+ ? (colorScheme === "dark" ? darkTheme : lightTheme)
+ : codeNoteTheme;
+
+ return (
+ <div className="options-section">
+ <Card heading={t("code_theme.title")}>
+ <ThemeModeSelector matchesApp={matchesApp} onMatchesAppChange={setMatchesApp} />
+
+ {matchesApp ? (
+ <>
+ <CardOption name="light-theme" label={t("code_theme.light_theme")}>
+ <FormSelect
+ values={lightThemes}
+ keyProperty="id" titleProperty="name"
+ currentValue={lightTheme} onChange={setLightTheme}
+ />
+ </CardOption>
+ <CardOption name="dark-theme" label={t("code_theme.dark_theme")}>
+ <FormSelect
+ values={darkThemes}
+ keyProperty="id" titleProperty="name"
+ currentValue={darkTheme} onChange={setDarkTheme}
+ />
+ </CardOption>
+ </>
+ ) : (
+ <CardOption name="color-scheme" label={t("code_theme.color-scheme")}>
+ <FormSelect
+ values={allThemes}
+ keyProperty="id" titleProperty="name"
+ currentValue={codeNoteTheme} onChange={setCodeNoteTheme}
+ />
+ </CardOption>
+ )}
+
+ {/* The whole segment, edge to edge: a specimen of the editor rather than a control
+ standing beside a label. */}
+ <CardSection className="code-note-preview" noPadding>
+ <CodeNotePreview wordWrapping={wordWrapping} themeName={effectiveTheme} indentSize={indentSize} />
+ </CardSection>
+ </Card>
+ </div>
+ );
+}
+
+function CodeNotePreview({ themeName, wordWrapping, indentSize }: { themeName: string, wordWrapping: boolean, indentSize: number }) {
+ const editorRef = useRef<CodeMirror>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!containerRef.current) {
+ return;
+ }
+
+ // Clean up previous instance.
+ editorRef.current?.destroy();
+ containerRef.current.innerHTML = "";
+
+ // Set up a new instance.
+ const editor = new CodeMirror({
+ parent: containerRef.current
+ });
+ editor.setText(codeNoteSample);
+ editor.setMimeType(SAMPLE_MIME);
+ editorRef.current = editor;
+ }, []);
+
+ useEffect(() => {
+ editorRef.current?.setLineWrapping(wordWrapping);
+ }, [ wordWrapping ]);
+
+ useEffect(() => {
+ const editor = editorRef.current;
+ if (!editor) return;
+ editor.setIndentSize(indentSize);
+ editor.setText(reindentSample(codeNoteSample, indentSize));
+ }, [ indentSize ]);
+
+ useEffect(() => {
+ if (themeName?.startsWith(DEFAULT_PREFIX)) {
+ const theme = getThemeById(themeName.substring(DEFAULT_PREFIX.length));
+ if (theme) {
+ editorRef.current?.setTheme(theme);
+ }
+ }
+ }, [ themeName ]);
+
+ return (
+ <div
+ ref={containerRef}
+ class="note-detail-readonly-code-content"
+ style={{ margin: 0, height: "200px" }}
+ />
+ );
+}
+
+const SAMPLE_BASE_INDENT = 4;
+
+function reindentSample(sample: string, indentSize: number): string {
+ return sample.replace(/^( +)/gm, (match) => {
+ const level = match.length / SAMPLE_BASE_INDENT;
+ return " ".repeat(Math.round(level) * indentSize);
+ });
+}
+
+function CodeMimeTypes() {
+ return (
+ <div className="options-section">
+ <Card heading={t("code_mime_types.title")}>
+ <CardSection>
+ <CodeMimeTypesList />
+ </CardSection>
+ </Card>
+ </div>
+ );
+}
+
diff --git a/apps/client/src/widgets/type_widgets/options/i18n.css b/apps/client/src/widgets/type_widgets/options/i18n.css
index 82ba253fb9..949e8cfaf2 100644
--- a/apps/client/src/widgets/type_widgets/options/i18n.css
+++ b/apps/client/src/widgets/type_widgets/options/i18n.css
@@ -1,15 +1,3 @@
-/* Bootstrap gives a select the whole width of what holds it; in a card row it stands beside the
- label instead, so it takes the width of what it offers — capped, one of the choices being a
- sentence. The bounds are the ones these rows carried before they were card sections. */
-.i18n-dates select {
- width: auto;
- min-width: 150px;
- max-width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
/* Many lines rather than a control on one, so it is given room from the section's own edges.
`!important` because CheckboxList zeroes its bottom margin inline, which no selector outweighs. */
.i18n-content-languages ul {
diff --git a/apps/client/src/widgets/type_widgets/options/i18n.tsx b/apps/client/src/widgets/type_widgets/options/i18n.tsx
index 08c5497a1c..66dddb8a91 100644
--- a/apps/client/src/widgets/type_widgets/options/i18n.tsx
+++ b/apps/client/src/widgets/type_widgets/options/i18n.tsx
@@ -107,7 +107,7 @@ function DateSettings() {
const [ minDaysInFirstWeek, setMinDaysInFirstWeek ] = useTriliumOption("minDaysInFirstWeek");
return (
- <div className="options-section i18n-dates">
+ <div className="options-section">
<Card heading={t("i18n.dates-title")}>
<CardOption name="first-day-of-week" label={t("i18n.first-day-of-the-week")}>
<FormSelect
diff --git a/apps/client/src/widgets/type_widgets/options/other.css b/apps/client/src/widgets/type_widgets/options/other.css
index eef5d7afba..d95c3d05f7 100644
--- a/apps/client/src/widgets/type_widgets/options/other.css
+++ b/apps/client/src/widgets/type_widgets/options/other.css
@@ -1,13 +1,3 @@
-/* A figure and the unit or scale it is read in, sized to the figure: Bootstrap gives an input group
- the whole width of what holds it, which in a card row is the row. */
-.other-number .tn-number-unit-pair {
- width: auto;
-}
-
-.other-number input[type="number"] {
- width: 7em;
-}
-
.other-html-tags {
display: flex;
flex-direction: column;
diff --git a/apps/client/src/widgets/type_widgets/options/other.tsx b/apps/client/src/widgets/type_widgets/options/other.tsx
index 00d1721408..2116eba468 100644
--- a/apps/client/src/widgets/type_widgets/options/other.tsx
+++ b/apps/client/src/widgets/type_widgets/options/other.tsx
@@ -1,334 +1,330 @@
-import "./other.css";
-
-import { SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";
-
-import { t } from "../../../services/i18n";
-import search from "../../../services/search";
-import server from "../../../services/server";
-import toast from "../../../services/toast";
-import Button from "../../react/Button";
-import { Card, CardOption, CardSection } from "../../react/Card";
-import { FormTextBoxWithUnit } from "../../react/FormTextBox";
-import FormToggle from "../../react/FormToggle";
-import { useNoteContext, useTriliumOption, useTriliumOptionBool, useTriliumOptionJson } from "../../react/hooks";
-import OptionsPageHeader from "./components/OptionsPageHeader";
-import RelatedSettings from "./components/RelatedSettings";
-import TimeSelector from "./components/TimeSelector";
-import { requestContentManagerSection } from "./content_manager";
-
-export default function OtherSettings() {
- return (
- <>
- <OptionsPageHeader />
- <SearchSettings />
- <NoteErasureTimeout />
- <AttachmentErasureTimeout />
- <RevisionSettings />
- <HtmlImportTags />
- <ShareSettings />
- <NetworkSettings />
- <RelatedActions />
- </>
- );
-}
-
-function RelatedActions() {
- const { noteContext } = useNoteContext();
-
- return (
- <RelatedSettings
- title={t("settings.related_actions")}
- items={[
- {
- title: t("settings.related_space_usage"),
- description: t("settings.related_space_usage_description"),
- targetPage: "_optionsContentManager",
- onClick: (e) => {
- // The Content Manager opens on Active Content unless asked otherwise, and
- // navigating here rather than by the href is what lets us ask first.
- e.preventDefault();
- e.stopPropagation();
- requestContentManagerSection("spaceUsage");
- // Kept in whichever context this page is shown in — the settings dialog
- // holds a note context of its own, outside the tab manager.
- void noteContext?.setNote("_optionsContentManager", { keepActiveDialog: true });
- }
- }
- ]}
- />
- );
-}
-
-function SearchSettings() {
- const [ fuzzyEnabled, setFuzzyEnabled ] = useTriliumOptionBool("searchEnableFuzzyMatching");
- const [ autocompleteFuzzy, setAutocompleteFuzzy ] = useTriliumOptionBool("searchAutocompleteFuzzy");
-
- return (
- <div className="options-section">
- <Card heading={t("search.title")}>
- <CardOption
- name="search-fuzzy-matching"
- label={t("search.fuzzy_matching_label")}
- description={t("search.fuzzy_matching_description")}
- >
- <FormToggle currentValue={fuzzyEnabled} onChange={setFuzzyEnabled} />
- </CardOption>
-
- <CardOption
- name="search-autocomplete-fuzzy"
- label={t("search.autocomplete_fuzzy_label")}
- description={t("search.autocomplete_fuzzy_description")}
- >
- <FormToggle currentValue={autocompleteFuzzy} onChange={setAutocompleteFuzzy} />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-function NoteErasureTimeout() {
- return (
- <div className="options-section">
- <Card
- heading={t("note_erasure_timeout.note_erasure_timeout_title")}
- description={t("note_erasure_timeout.description")}
- >
- <CardOption
- className="other-number"
- name="erase-entities-after"
- label={t("note_erasure_timeout.erase_notes_after")}
- description={t("note_erasure_timeout.erase_notes_after_description")}
- >
- <TimeSelector
- name="erase-entities-after"
- optionValueId="eraseEntitiesAfterTimeInSeconds" optionTimeScaleId="eraseEntitiesAfterTimeScale"
- />
- </CardOption>
-
- <CardOption
- label={t("note_erasure_timeout.erase_deleted_notes_now")}
- description={t("note_erasure_timeout.manual_erasing_description")}
- >
- <Button
- name="erase-deleted-notes-now-button"
- text={t("note_erasure_timeout.erase_now_button")}
- size="micro"
- onClick={() => {
- server.post("notes/erase-deleted-notes-now").then(() => {
- toast.showMessage(t("note_erasure_timeout.deleted_notes_erased"));
- });
- }}
- />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-function AttachmentErasureTimeout() {
- return (
- <div className="options-section">
- <Card
- heading={t("attachment_erasure_timeout.attachment_erasure_timeout")}
- description={t("attachment_erasure_timeout.description")}
- >
- <CardOption
- className="other-number"
- name="erase-unused-attachments-after"
- label={t("attachment_erasure_timeout.erase_attachments_after")}
- description={t("attachment_erasure_timeout.erase_attachments_after_description")}
- >
- <TimeSelector
- name="erase-unused-attachments-after"
- optionValueId="eraseUnusedAttachmentsAfterSeconds" optionTimeScaleId="eraseUnusedAttachmentsAfterTimeScale"
- />
- </CardOption>
-
- <CardOption
- label={t("attachment_erasure_timeout.erase_unused_attachments_now")}
- description={t("attachment_erasure_timeout.manual_erasing_description")}
- >
- <Button
- name="erase-unused-attachments-now-button"
- text={t("attachment_erasure_timeout.erase_now_button")}
- size="micro"
- onClick={() => {
- server.post("notes/erase-unused-attachments-now").then(() => {
- toast.showMessage(t("attachment_erasure_timeout.unused_attachments_erased"));
- });
- }}
- />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-function RevisionSettings() {
- const [ revisionSnapshotNumberLimit, setRevisionSnapshotNumberLimit ] = useTriliumOption("revisionSnapshotNumberLimit");
- const [ revisionIgnoreNamedSnapshots, setRevisionIgnoreNamedSnapshots ] = useTriliumOptionBool("revisionIgnoreNamedSnapshots");
-
- return (
- <div className="options-section">
- <Card heading={t("revisions_snapshot.title")}>
- <CardOption
- className="other-number"
- name="revision-snapshot-time-interval"
- label={t("revisions_snapshot_interval.snapshot_time_interval_label")}
- description={t("revisions_snapshot_interval.note_revisions_snapshot_description_short")}
- >
- <TimeSelector
- name="revision-snapshot-time-interval"
- optionValueId="revisionSnapshotTimeInterval" optionTimeScaleId="revisionSnapshotTimeIntervalTimeScale"
- minimumSeconds={10}
- />
- </CardOption>
-
- <CardOption
- className="other-number"
- name="revision-snapshot-number-limit"
- label={t("revisions_snapshot_limit.snapshot_number_limit_label")}
- description={t("revisions_snapshot_limit.note_revisions_snapshot_limit_description_short")}
- >
- <FormTextBoxWithUnit
- type="number" min={-1}
- currentValue={revisionSnapshotNumberLimit}
- unit={t("revisions_snapshot_limit.snapshot_number_limit_unit")}
- onBlur={value => {
- const newValue = parseInt(value, 10);
- if (!isNaN(newValue) && newValue >= -1) {
- setRevisionSnapshotNumberLimit(newValue);
- }
- }}
- />
- </CardOption>
-
- <CardOption
- name="revision-keep-named-snapshots"
- label={t("revisions_snapshot_limit.keep_named_revisions_label")}
- description={t("revisions_snapshot_limit.keep_named_revisions_description")}
- >
- <FormToggle currentValue={revisionIgnoreNamedSnapshots} onChange={setRevisionIgnoreNamedSnapshots} />
- </CardOption>
-
- <CardOption
- label={t("revisions_snapshot_limit.erase_excess_revision_snapshots")}
- description={t("revisions_snapshot_limit.erase_excess_revision_snapshots_description")}
- >
- <Button
- name="erase-excess-revisions-button"
- text={t("revisions_snapshot_limit.erase_now_button")}
- size="micro"
- // A negative limit keeps every snapshot, so nothing is excess and the erasure
- // would report success having dropped nothing. Offered again as soon as a
- // limit is set.
- disabled={parseInt(revisionSnapshotNumberLimit, 10) < 0}
- onClick={async () => {
- await server.post("revisions/erase-all-excess-revisions");
- toast.showMessage(t("revisions_snapshot_limit.erase_excess_revision_snapshots_prompt"));
- }}
- />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-function HtmlImportTags() {
- const [ allowedHtmlTags, setAllowedHtmlTags ] = useTriliumOptionJson<readonly string[]>("allowedHtmlTags");
- const parsedValue = allowedHtmlTags.join(" ");
-
- return (
- <div className="options-section">
- <Card
- heading={t("import.html_import_tags.title")}
- description={t("import.html_import_tags.description")}
- >
- <CardSection className="other-html-tags">
- <textarea
- className="allowed-html-tags"
- spellcheck={false}
- placeholder={t("import.html_import_tags.placeholder")}
- value={parsedValue}
- onBlur={e => {
- const tags = e.currentTarget.value
- .split(/[\n,\s]+/) // Split on newlines, commas, or spaces
- .map((tag) => tag.trim())
- .filter((tag) => tag.length > 0);
- setAllowedHtmlTags(tags);
- }}
- />
-
- <Button
- name="reset-allowed-html-tags-button"
- text={t("import.html_import_tags.reset_button")}
- size="micro"
- onClick={() => setAllowedHtmlTags(SANITIZER_DEFAULT_ALLOWED_TAGS)}
- />
- </CardSection>
- </Card>
- </div>
- );
-}
-
-function ShareSettings() {
- const [ redirectBareDomain, setRedirectBareDomain ] = useTriliumOptionBool("redirectBareDomain");
- const [ showLogInShareTheme, setShowLogInShareTheme ] = useTriliumOptionBool("showLoginInShareTheme");
-
- return (
- <div className="options-section">
- <Card heading={t("share.title")}>
- <CardOption
- name="redirect-bare-domain"
- label={t("share.redirect_bare_domain")}
- description={t("share.redirect_bare_domain_description")}
- >
- <FormToggle
- currentValue={redirectBareDomain}
- onChange={async value => {
- if (value) {
- const shareRootNotes = await search.searchForNotes("#shareRoot");
- const sharedShareRootNote = shareRootNotes.find((note) => note.isShared());
-
- if (sharedShareRootNote) {
- toast.showMessage(t("share.share_root_found", { noteTitle: sharedShareRootNote.title }));
- } else if (shareRootNotes.length > 0) {
- toast.showError(t("share.share_root_not_shared", { noteTitle: shareRootNotes[0].title }));
- } else {
- toast.showError(t("share.share_root_not_found"));
- }
- }
- setRedirectBareDomain(value);
- }}
- />
- </CardOption>
-
- <CardOption
- name="show-login-in-share-theme"
- label={t("share.show_login_link")}
- description={t("share.show_login_link_description")}
- >
- <FormToggle currentValue={showLogInShareTheme} onChange={setShowLogInShareTheme} />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-function NetworkSettings() {
- const [ checkForUpdates, setCheckForUpdates ] = useTriliumOptionBool("checkForUpdates");
-
- return (
- <div className="options-section">
- <Card heading={t("network_connections.network_connections_title")}>
- <CardOption
- name="check-for-updates"
- label={t("network_connections.check_for_updates")}
- description={t("network_connections.check_for_updates_description")}
- >
- <FormToggle currentValue={checkForUpdates} onChange={setCheckForUpdates} />
- </CardOption>
- </Card>
- </div>
- );
-}
+import "./other.css";
+
+import { SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";
+
+import { t } from "../../../services/i18n";
+import search from "../../../services/search";
+import server from "../../../services/server";
+import toast from "../../../services/toast";
+import Button from "../../react/Button";
+import { Card, CardOption, CardSection } from "../../react/Card";
+import { FormTextBoxWithUnit } from "../../react/FormTextBox";
+import FormToggle from "../../react/FormToggle";
+import { useNoteContext, useTriliumOption, useTriliumOptionBool, useTriliumOptionJson } from "../../react/hooks";
+import OptionsPageHeader from "./components/OptionsPageHeader";
+import RelatedSettings from "./components/RelatedSettings";
+import TimeSelector from "./components/TimeSelector";
+import { requestContentManagerSection } from "./content_manager";
+
+export default function OtherSettings() {
+ return (
+ <>
+ <OptionsPageHeader />
+ <SearchSettings />
+ <NoteErasureTimeout />
+ <AttachmentErasureTimeout />
+ <RevisionSettings />
+ <HtmlImportTags />
+ <ShareSettings />
+ <NetworkSettings />
+ <RelatedActions />
+ </>
+ );
+}
+
+function RelatedActions() {
+ const { noteContext } = useNoteContext();
+
+ return (
+ <RelatedSettings
+ title={t("settings.related_actions")}
+ items={[
+ {
+ title: t("settings.related_space_usage"),
+ description: t("settings.related_space_usage_description"),
+ targetPage: "_optionsContentManager",
+ onClick: (e) => {
+ // The Content Manager opens on Active Content unless asked otherwise, and
+ // navigating here rather than by the href is what lets us ask first.
+ e.preventDefault();
+ e.stopPropagation();
+ requestContentManagerSection("spaceUsage");
+ // Kept in whichever context this page is shown in — the settings dialog
+ // holds a note context of its own, outside the tab manager.
+ void noteContext?.setNote("_optionsContentManager", { keepActiveDialog: true });
+ }
+ }
+ ]}
+ />
+ );
+}
+
+function SearchSettings() {
+ const [ fuzzyEnabled, setFuzzyEnabled ] = useTriliumOptionBool("searchEnableFuzzyMatching");
+ const [ autocompleteFuzzy, setAutocompleteFuzzy ] = useTriliumOptionBool("searchAutocompleteFuzzy");
+
+ return (
+ <div className="options-section">
+ <Card heading={t("search.title")}>
+ <CardOption
+ name="search-fuzzy-matching"
+ label={t("search.fuzzy_matching_label")}
+ description={t("search.fuzzy_matching_description")}
+ >
+ <FormToggle currentValue={fuzzyEnabled} onChange={setFuzzyEnabled} />
+ </CardOption>
+
+ <CardOption
+ name="search-autocomplete-fuzzy"
+ label={t("search.autocomplete_fuzzy_label")}
+ description={t("search.autocomplete_fuzzy_description")}
+ >
+ <FormToggle currentValue={autocompleteFuzzy} onChange={setAutocompleteFuzzy} />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+function NoteErasureTimeout() {
+ return (
+ <div className="options-section">
+ <Card
+ heading={t("note_erasure_timeout.note_erasure_timeout_title")}
+ description={t("note_erasure_timeout.description")}
+ >
+ <CardOption
+ name="erase-entities-after"
+ label={t("note_erasure_timeout.erase_notes_after")}
+ description={t("note_erasure_timeout.erase_notes_after_description")}
+ >
+ <TimeSelector
+ name="erase-entities-after"
+ optionValueId="eraseEntitiesAfterTimeInSeconds" optionTimeScaleId="eraseEntitiesAfterTimeScale"
+ />
+ </CardOption>
+
+ <CardOption
+ label={t("note_erasure_timeout.erase_deleted_notes_now")}
+ description={t("note_erasure_timeout.manual_erasing_description")}
+ >
+ <Button
+ name="erase-deleted-notes-now-button"
+ text={t("note_erasure_timeout.erase_now_button")}
+ size="micro"
+ onClick={() => {
+ server.post("notes/erase-deleted-notes-now").then(() => {
+ toast.showMessage(t("note_erasure_timeout.deleted_notes_erased"));
+ });
+ }}
+ />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+function AttachmentErasureTimeout() {
+ return (
+ <div className="options-section">
+ <Card
+ heading={t("attachment_erasure_timeout.attachment_erasure_timeout")}
+ description={t("attachment_erasure_timeout.description")}
+ >
+ <CardOption
+ name="erase-unused-attachments-after"
+ label={t("attachment_erasure_timeout.erase_attachments_after")}
+ description={t("attachment_erasure_timeout.erase_attachments_after_description")}
+ >
+ <TimeSelector
+ name="erase-unused-attachments-after"
+ optionValueId="eraseUnusedAttachmentsAfterSeconds" optionTimeScaleId="eraseUnusedAttachmentsAfterTimeScale"
+ />
+ </CardOption>
+
+ <CardOption
+ label={t("attachment_erasure_timeout.erase_unused_attachments_now")}
+ description={t("attachment_erasure_timeout.manual_erasing_description")}
+ >
+ <Button
+ name="erase-unused-attachments-now-button"
+ text={t("attachment_erasure_timeout.erase_now_button")}
+ size="micro"
+ onClick={() => {
+ server.post("notes/erase-unused-attachments-now").then(() => {
+ toast.showMessage(t("attachment_erasure_timeout.unused_attachments_erased"));
+ });
+ }}
+ />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+function RevisionSettings() {
+ const [ revisionSnapshotNumberLimit, setRevisionSnapshotNumberLimit ] = useTriliumOption("revisionSnapshotNumberLimit");
+ const [ revisionIgnoreNamedSnapshots, setRevisionIgnoreNamedSnapshots ] = useTriliumOptionBool("revisionIgnoreNamedSnapshots");
+
+ return (
+ <div className="options-section">
+ <Card heading={t("revisions_snapshot.title")}>
+ <CardOption
+ name="revision-snapshot-time-interval"
+ label={t("revisions_snapshot_interval.snapshot_time_interval_label")}
+ description={t("revisions_snapshot_interval.note_revisions_snapshot_description_short")}
+ >
+ <TimeSelector
+ name="revision-snapshot-time-interval"
+ optionValueId="revisionSnapshotTimeInterval" optionTimeScaleId="revisionSnapshotTimeIntervalTimeScale"
+ minimumSeconds={10}
+ />
+ </CardOption>
+
+ <CardOption
+ name="revision-snapshot-number-limit"
+ label={t("revisions_snapshot_limit.snapshot_number_limit_label")}
+ description={t("revisions_snapshot_limit.note_revisions_snapshot_limit_description_short")}
+ >
+ <FormTextBoxWithUnit
+ type="number" min={-1}
+ currentValue={revisionSnapshotNumberLimit}
+ unit={t("revisions_snapshot_limit.snapshot_number_limit_unit")}
+ onBlur={value => {
+ const newValue = parseInt(value, 10);
+ if (!isNaN(newValue) && newValue >= -1) {
+ setRevisionSnapshotNumberLimit(newValue);
+ }
+ }}
+ />
+ </CardOption>
+
+ <CardOption
+ name="revision-keep-named-snapshots"
+ label={t("revisions_snapshot_limit.keep_named_revisions_label")}
+ description={t("revisions_snapshot_limit.keep_named_revisions_description")}
+ >
+ <FormToggle currentValue={revisionIgnoreNamedSnapshots} onChange={setRevisionIgnoreNamedSnapshots} />
+ </CardOption>
+
+ <CardOption
+ label={t("revisions_snapshot_limit.erase_excess_revision_snapshots")}
+ description={t("revisions_snapshot_limit.erase_excess_revision_snapshots_description")}
+ >
+ <Button
+ name="erase-excess-revisions-button"
+ text={t("revisions_snapshot_limit.erase_now_button")}
+ size="micro"
+ // A negative limit keeps every snapshot, so nothing is excess and the erasure
+ // would report success having dropped nothing. Offered again as soon as a
+ // limit is set.
+ disabled={parseInt(revisionSnapshotNumberLimit, 10) < 0}
+ onClick={async () => {
+ await server.post("revisions/erase-all-excess-revisions");
+ toast.showMessage(t("revisions_snapshot_limit.erase_excess_revision_snapshots_prompt"));
+ }}
+ />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+function HtmlImportTags() {
+ const [ allowedHtmlTags, setAllowedHtmlTags ] = useTriliumOptionJson<readonly string[]>("allowedHtmlTags");
+ const parsedValue = allowedHtmlTags.join(" ");
+
+ return (
+ <div className="options-section">
+ <Card
+ heading={t("import.html_import_tags.title")}
+ description={t("import.html_import_tags.description")}
+ >
+ <CardSection className="other-html-tags">
+ <textarea
+ className="allowed-html-tags"
+ spellcheck={false}
+ placeholder={t("import.html_import_tags.placeholder")}
+ value={parsedValue}
+ onBlur={e => {
+ const tags = e.currentTarget.value
+ .split(/[\n,\s]+/) // Split on newlines, commas, or spaces
+ .map((tag) => tag.trim())
+ .filter((tag) => tag.length > 0);
+ setAllowedHtmlTags(tags);
+ }}
+ />
+
+ <Button
+ name="reset-allowed-html-tags-button"
+ text={t("import.html_import_tags.reset_button")}
+ size="micro"
+ onClick={() => setAllowedHtmlTags(SANITIZER_DEFAULT_ALLOWED_TAGS)}
+ />
+ </CardSection>
+ </Card>
+ </div>
+ );
+}
+
+function ShareSettings() {
+ const [ redirectBareDomain, setRedirectBareDomain ] = useTriliumOptionBool("redirectBareDomain");
+ const [ showLogInShareTheme, setShowLogInShareTheme ] = useTriliumOptionBool("showLoginInShareTheme");
+
+ return (
+ <div className="options-section">
+ <Card heading={t("share.title")}>
+ <CardOption
+ name="redirect-bare-domain"
+ label={t("share.redirect_bare_domain")}
+ description={t("share.redirect_bare_domain_description")}
+ >
+ <FormToggle
+ currentValue={redirectBareDomain}
+ onChange={async value => {
+ if (value) {
+ const shareRootNotes = await search.searchForNotes("#shareRoot");
+ const sharedShareRootNote = shareRootNotes.find((note) => note.isShared());
+
+ if (sharedShareRootNote) {
+ toast.showMessage(t("share.share_root_found", { noteTitle: sharedShareRootNote.title }));
+ } else if (shareRootNotes.length > 0) {
+ toast.showError(t("share.share_root_not_shared", { noteTitle: shareRootNotes[0].title }));
+ } else {
+ toast.showError(t("share.share_root_not_found"));
+ }
+ }
+ setRedirectBareDomain(value);
+ }}
+ />
+ </CardOption>
+
+ <CardOption
+ name="show-login-in-share-theme"
+ label={t("share.show_login_link")}
+ description={t("share.show_login_link_description")}
+ >
+ <FormToggle currentValue={showLogInShareTheme} onChange={setShowLogInShareTheme} />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+function NetworkSettings() {
+ const [ checkForUpdates, setCheckForUpdates ] = useTriliumOptionBool("checkForUpdates");
+
+ return (
+ <div className="options-section">
+ <Card heading={t("network_connections.network_connections_title")}>
+ <CardOption
+ name="check-for-updates"
+ label={t("network_connections.check_for_updates")}
+ description={t("network_connections.check_for_updates_description")}
+ >
+ <FormToggle currentValue={checkForUpdates} onChange={setCheckForUpdates} />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/options/password.css b/apps/client/src/widgets/type_widgets/options/password.css
index 24ce9e5984..0a1fc597ae 100644
--- a/apps/client/src/widgets/type_widgets/options/password.css
+++ b/apps/client/src/widgets/type_widgets/options/password.css
@@ -1,16 +1,3 @@
-/* A figure and the scale it is read in, sized to the figure rather than to the row it stands in. */
-.password-number input[type="number"] {
- width: 7em;
-}
-
-/* Bootstrap gives a select the whole width of what holds it, which in a card row leaves the label
- beside it a word to the line. */
-.signin-method select {
- width: auto;
- min-width: 150px;
- max-width: 260px;
-}
-
/* Sentences rather than a control, so the segment carries them with no margin of their own. */
.signin-method-description p {
margin-bottom: 0;
diff --git a/apps/client/src/widgets/type_widgets/options/password.tsx b/apps/client/src/widgets/type_widgets/options/password.tsx
index 9dc2c25d6d..b2e40db06a 100644
--- a/apps/client/src/widgets/type_widgets/options/password.tsx
+++ b/apps/client/src/widgets/type_widgets/options/password.tsx
@@ -1,449 +1,448 @@
-import "./password.css";
-
-import { ChangePasswordResponse, OAuthStatus, TOTPStatus } from "@triliumnext/commons";
-import { createPortal } from "preact/compat";
-import { useCallback, useEffect, useState } from "preact/hooks";
-
-import dialog from "../../../services/dialog";
-import { t } from "../../../services/i18n";
-import { oauthAccountLabel, oauthProviderDisplayName } from "../../../services/oauth_status";
-import protected_session_holder from "../../../services/protected_session_holder";
-import server from "../../../services/server";
-import toast from "../../../services/toast";
-import { isElectron } from "../../../services/utils";
-import { ExtendedAdmonition } from "../../react/Admonition";
-import Button from "../../react/Button";
-import { Card, CardOption, CardSection } from "../../react/Card";
-import FormGroup from "../../react/FormGroup";
-import FormSelect from "../../react/FormSelect";
-import FormText from "../../react/FormText";
-import FormTextBox from "../../react/FormTextBox";
-import { useTriliumOption } from "../../react/hooks";
-import Modal from "../../react/Modal";
-import RawHtml from "../../react/RawHtml";
-import MfaStatusBadge, { MfaStatusTone } from "./components/MfaStatusBadge";
-import OptionsPageHeader from "./components/OptionsPageHeader";
-import TimeSelector from "./components/TimeSelector";
-import { TotpSettings } from "./totp";
-
-export default function PasswordSettings() {
- return (
- <>
- <OptionsPageHeader />
- {/* The sign-in method (and its two-factor / OAuth settings) is only available on the server
- build — the desktop app authenticates differently — matching the former MFA page's
- serverOnly scope. */}
- {!isElectron() && <SignInMethod />}
- <ChangePassword />
- <ProtectedSessionTimeout />
- </>
- );
-}
-
-function ChangePassword() {
- const [showModal, setShowModal] = useState(false);
-
- return (
- <div className="options-section">
- <Card heading={t("password.heading")}>
- <CardOption
- label={t("password.change_password")}
- description={t("password.change_password_description")}
- >
- <Button
- name="change-password-button"
- text={t("password.change_password_button")}
- size="micro"
- onClick={() => setShowModal(true)}
- />
- </CardOption>
-
- <CardOption
- label={t("password.reset_password")}
- description={t("password.reset_password_description")}
- >
- <Button
- name="reset-password-button"
- text={t("password.reset_password_button")}
- size="micro"
- onClick={async () => {
- if (!await dialog.confirm(t("password.reset_confirmation"))) {
- return;
- }
-
- await server.post("password/reset?really=yesIReallyWantToResetPasswordAndLoseAccessToMyProtectedNotes");
- toast.showError(t("password.reset_success_message"));
- }}
- />
- </CardOption>
- </Card>
-
- {createPortal(
- <ChangePasswordModal show={showModal} onHidden={() => setShowModal(false)} />,
- document.body
- )}
- </div>
- );
-}
-
-interface ChangePasswordModalProps {
- show: boolean;
- onHidden: () => void;
-}
-
-function ChangePasswordModal({ show, onHidden }: ChangePasswordModalProps) {
- const [oldPassword, setOldPassword] = useState("");
- const [newPassword1, setNewPassword1] = useState("");
- const [newPassword2, setNewPassword2] = useState("");
-
- const handleSubmit = async () => {
- if (newPassword1 !== newPassword2) {
- toast.showError(t("password.password_mismatch"));
- return;
- }
-
- const result = await server.post<ChangePasswordResponse>("password/change", {
- current_password: oldPassword,
- new_password: newPassword1
- });
-
- if (result.success) {
- onHidden();
- setOldPassword("");
- setNewPassword1("");
- setNewPassword2("");
- toast.showMessage(t("password.password_changed_success"));
-
- // password changed so current protected session is invalid and needs to be cleared
- protected_session_holder.resetProtectedSession();
- } else if (result.message) {
- toast.showError(result.message);
- }
- };
-
- const handleHidden = () => {
- setOldPassword("");
- setNewPassword1("");
- setNewPassword2("");
- onHidden();
- };
-
- return (
- <Modal
- show={show}
- onHidden={handleHidden}
- onSubmit={handleSubmit}
- title={t("password.change_password_heading")}
- className="change-password-modal"
- size="md"
- stackable
- footer={
- <>
- <Button text={t("password.cancel")} onClick={handleHidden} />
- <Button text={t("password.change_password")} kind="primary" />
- </>
- }
- >
- <FormGroup name="old-password" label={t("password.old_password")}>
- <FormTextBox
- type="password"
- currentValue={oldPassword}
- onChange={setOldPassword}
- />
- </FormGroup>
-
- <FormGroup name="new-password1" label={t("password.new_password")}>
- <FormTextBox
- type="password"
- currentValue={newPassword1}
- onChange={setNewPassword1}
- />
- </FormGroup>
-
- <FormGroup name="new-password2" label={t("password.new_password_confirmation")}>
- <FormTextBox
- type="password"
- currentValue={newPassword2}
- onChange={setNewPassword2}
- />
- </FormGroup>
- </Modal>
- );
-}
-
-function ProtectedSessionTimeout() {
- return (
- <div className="options-section">
- <Card heading={t("password.protected_session_timeout")}>
- <CardOption
- className="password-number"
- name="protected-session-timeout"
- label={t("password.protected_session_timeout_label")}
- description={<>{t("password.protected_session_timeout_description")} <a class="tn-link" href="https://triliumnext.github.io/Docs/Wiki/protected-notes.html">{t("password.wiki")}</a> {t("password.for_more_info")}</>}
- >
- <TimeSelector
- name="protected-session-timeout"
- optionValueId="protectedSessionTimeout"
- optionTimeScaleId="protectedSessionTimeoutTimeScale"
- minimumSeconds={60}
- />
- </CardOption>
- </Card>
- </div>
- );
-}
-
-/**
- * Two-factor authentication settings. Owns the live TOTP/OAuth status (the method selector needs
- * `totpStatus.set` to know whether to offer switching methods) and delegates the heavier TOTP UI to
- * its own module; OAuth is small and read-only, so it lives here.
- */
-function SignInMethod() {
- // `mfaMethod` is the persisted choice: "oauth" means sign in via an OAuth provider, anything else
- // ("totp") means the local password (with TOTP as optional second factor). The dropdown speaks in
- // the user-facing "local"/"oauth" terms and maps back to the option here.
- const [ mfaMethod, setMfaMethod ] = useTriliumOption("mfaMethod");
- const [ totpStatus, setTotpStatus ] = useState<TOTPStatus>();
- const [ oauthStatus, setOauthStatus ] = useState<OAuthStatus>();
-
- const refreshTotpStatus = useCallback(() => {
- server.get<TOTPStatus>("totp/status").then(setTotpStatus);
- }, []);
-
- const refreshOauthStatus = useCallback(() => {
- server.get<OAuthStatus>("oauth/status").then(setOauthStatus);
- }, []);
-
- useEffect(() => {
- refreshTotpStatus();
- refreshOauthStatus();
- }, [ refreshTotpStatus, refreshOauthStatus ]);
-
- const usingOAuth = mfaMethod === "oauth";
-
- return (
- <>
- <div className="options-section signin-method">
- <Card heading={t("multi_factor_authentication.authentication_title")}>
- <CardOption name="signin-method" label={t("multi_factor_authentication.signin_method")}>
- <FormSelect
- values={[
- { value: "local", label: t("multi_factor_authentication.signin_local") },
- { value: "oauth", label: t("multi_factor_authentication.signin_oauth") }
- ]}
- keyProperty="value" titleProperty="label"
- currentValue={usingOAuth ? "oauth" : "local"}
- onChange={(value) => setMfaMethod(value === "oauth" ? "oauth" : "totp")}
- />
- </CardOption>
-
- {/* What the chosen method means, below the choice rather than above it — it
- describes what was picked, not what is on offer. */}
- <CardSection className="signin-method-description">
- <FormText>
- { usingOAuth
- ? <RawHtml html={t("multi_factor_authentication.oauth_description")} />
- : t("multi_factor_authentication.signin_local_description") }
- </FormText>
- </CardSection>
- </Card>
- </div>
-
- { usingOAuth
- ? <OAuthStatusCard status={oauthStatus} refreshStatus={refreshOauthStatus} />
- : <TotpSettings totpStatus={totpStatus} refreshTotpStatus={refreshTotpStatus} /> }
- </>
- );
-}
-
-/**
- * OAuth status card, shown when OAuth is the selected sign-in method. The provider credentials are
- * configured server-side (env vars / config.ini), but binding an account is an explicit in-app step —
- * mirroring TOTP's verify-before-enable. Three states:
- * - **not configured** → show the config hint (the server vars are missing);
- * - **configured, not enrolled** → offer "Connect account", which runs the provider round-trip and
- * binds the returned identity. SSO only becomes the live login method once this completes;
- * - **enrolled** → show the connected account and a "Disconnect" action.
- */
-function OAuthStatusCard({ status, refreshStatus }: { status?: OAuthStatus, refreshStatus: () => void }) {
- // "Configured" is purely about the server-side variables being present (the server's `enabled` flag
- // additionally requires mfaMethod === 'oauth', which is implied here since this card only renders then).
- const configured = (status?.missingVars?.length ?? 1) === 0;
- const enrolled = status?.enrolled ?? false;
-
- // The status badge mirrors the card's three states: an account is bound (green "Connected"),
- // the server is set up but no account is bound yet (amber "Not connected"), or the server-side
- // variables are missing entirely (muted "Not configured").
- const badge: { tone: MfaStatusTone, text: string } = enrolled
- ? { tone: "active", text: t("multi_factor_authentication.oauth_status_connected") }
- : configured
- ? { tone: "pending", text: t("multi_factor_authentication.oauth_status_not_connected") }
- : { tone: "inactive", text: t("multi_factor_authentication.oauth_status_not_configured") };
-
- // Enrollment is a full-page provider round-trip (not an XHR): navigate to the OIDC login route,
- // which on return binds the identity to this still-authenticated session (see open_id afterCallback).
- // The return lands on the app root and drops this modal; the resulting "connected" toast is driven by
- // a one-shot bootstrap flag (see showOAuthEnrollmentResultToast), so nothing is tracked here.
- const connectAccount = useCallback(() => {
- window.location.href = "authenticate";
- }, []);
-
- const disconnectAccount = useCallback(async () => {
- if (!await dialog.confirm(t("multi_factor_authentication.oauth_disconnect_confirm"))) {
- return;
- }
-
- // Resolve the labels before disconnecting, while the account is still bound.
- const account = oauthAccountLabel(status);
- const provider = oauthProviderDisplayName(status);
-
- await server.post("oauth/disconnect");
- toast.showMessage(t("multi_factor_authentication.oauth_disconnected", { account, provider }));
- refreshStatus();
- }, [ status, refreshStatus ]);
-
- return (
- <div className="options-section">
- <Card
- heading={t("multi_factor_authentication.oauth_title")}
- actions={<MfaStatusBadge tone={badge.tone} text={badge.text} />}
- >
- { !configured ? (
- <CardSection className="mfa-notice">
- <ExtendedAdmonition
- type="note"
- icon="bx bx-info-circle"
- title={t("multi_factor_authentication.oauth_not_configured_title")}
- detailsLabel={t("multi_factor_authentication.oauth_how_to_enable")}
- details={<OAuthConfigInstructions />}
- >
- <p>{t("multi_factor_authentication.oauth_not_configured_hint")}</p>
-
- { status?.missingVars && status.missingVars.length > 0 && (
- <p>
- {t("multi_factor_authentication.oauth_missing_vars", {
- variables: status.missingVars.map(v => `"${v}"`).join(", ")
- })}
- </p>
- )}
- </ExtendedAdmonition>
- </CardSection>
- ) : enrolled ? (
- <>
- <OAuthProviderRows status={status} />
- <CardOption label={t("multi_factor_authentication.oauth_user_account")}>
- <span>{status?.name ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
- </CardOption>
- <CardOption label={t("multi_factor_authentication.oauth_user_email")}>
- <span>{status?.email ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
- </CardOption>
-
- <CardOption
- label={t("multi_factor_authentication.oauth_disconnect_label")}
- description={t("multi_factor_authentication.oauth_disconnect_description")}
- >
- <Button
- name="oauth-disconnect-button"
- className="oauth-disconnect-button"
- icon="bx-trash"
- text={t("multi_factor_authentication.oauth_disconnect_button")}
- size="micro"
- onClick={() => void disconnectAccount()}
- />
- </CardOption>
- </>
- ) : (
- <>
- <CardSection className="mfa-notice">
- <ExtendedAdmonition
- type="note"
- icon="bx bx-info-circle"
- title={t("multi_factor_authentication.oauth_not_enrolled_title")}
- detailsLabel={t("multi_factor_authentication.oauth_not_enrolled_details_label")}
- details={t("multi_factor_authentication.oauth_not_enrolled_details")}
- >
- {t("multi_factor_authentication.oauth_not_enrolled_hint")}
- </ExtendedAdmonition>
- </CardSection>
-
- <OAuthProviderRows status={status} />
-
- <CardOption
- label={t("multi_factor_authentication.oauth_connect_label")}
- description={t("multi_factor_authentication.oauth_connect_description")}
- >
- <Button
- name="oauth-connect-button"
- icon="bx-log-in"
- text={t("multi_factor_authentication.oauth_connect_button")}
- size="micro"
- onClick={connectAccount}
- />
- </CardOption>
- </>
- )}
- </Card>
- </div>
- );
-}
-
-/**
- * Identifies the configured OAuth provider: its icon and display name, plus the issuer URL. Shown
- * whenever OAuth is configured so the owner can confirm which server they'll be redirected to.
- */
-function OAuthProviderRows({ status }: { status?: OAuthStatus }) {
- const displayName = oauthProviderDisplayName(status);
- return (
- <>
- <CardOption label={t("multi_factor_authentication.oauth_provider")}>
- <span className="oauth-provider">
- <OAuthProviderIcon src={status?.issuerIcon} />
- <span>{displayName}</span>
- </span>
- </CardOption>
- { status?.issuerUrl && (
- <CardOption label={t("multi_factor_authentication.oauth_provider_url")}>
- <span>{status.issuerUrl}</span>
- </CardOption>
- )}
- </>
- );
-}
-
-/**
- * Provider icon for the OAuth status card. Renders the configured/derived issuer icon, falling back
- * to a neutral key glyph when no icon is available or the image fails to load (e.g. a derived
- * favicon URL that the issuer doesn't actually serve).
- */
-function OAuthProviderIcon({ src }: { src?: string }) {
- const [ failed, setFailed ] = useState(false);
-
- // Reset the fallback flag when the source changes (e.g. the user switches providers), otherwise a
- // previously-failed load would keep showing the key glyph even when the new URL is perfectly valid.
- useEffect(() => setFailed(false), [src]);
-
- if (!src || failed) {
- return <span className="bx bx-key oauth-provider-icon" />;
- }
-
- return <img className="oauth-provider-icon" src={src} alt="" onError={() => setFailed(true)} />;
-}
-
-/**
- * "How to enable" instructions for OAuth, shown in the not-configured admonition's collapsible. Lists
- * the config.ini section and the equivalent environment variables the server reads — OAuth has no
- * in-app setup, so this is the only place the values are documented in the UI.
- */
-function OAuthConfigInstructions() {
- // oauthBaseUrl is the app's externally-reachable base URL, which for the user reading this is
- // exactly the origin they're browsing from — so prefill it as a sensible example value.
- const baseUrl = window.location.origin;
- return (
- <>
- <p>{t("multi_factor_authentication.oauth_server_config_hint")}</p>
- <pre><code>{`[MultiFactorAuthentication]\noauthBaseUrl=${baseUrl}\noauthClientId=\noauthClientSecret=`}</code></pre>
- <p>{t("multi_factor_authentication.oauth_server_env_hint")}</p>
- <pre><code>{`TRILIUM_OAUTH_BASE_URL=${baseUrl}\nTRILIUM_OAUTH_CLIENT_ID=\nTRILIUM_OAUTH_CLIENT_SECRET=`}</code></pre>
- </>
- );
-}
+import "./password.css";
+
+import { ChangePasswordResponse, OAuthStatus, TOTPStatus } from "@triliumnext/commons";
+import { createPortal } from "preact/compat";
+import { useCallback, useEffect, useState } from "preact/hooks";
+
+import dialog from "../../../services/dialog";
+import { t } from "../../../services/i18n";
+import { oauthAccountLabel, oauthProviderDisplayName } from "../../../services/oauth_status";
+import protected_session_holder from "../../../services/protected_session_holder";
+import server from "../../../services/server";
+import toast from "../../../services/toast";
+import { isElectron } from "../../../services/utils";
+import { ExtendedAdmonition } from "../../react/Admonition";
+import Button from "../../react/Button";
+import { Card, CardOption, CardSection } from "../../react/Card";
+import FormGroup from "../../react/FormGroup";
+import FormSelect from "../../react/FormSelect";
+import FormText from "../../react/FormText";
+import FormTextBox from "../../react/FormTextBox";
+import { useTriliumOption } from "../../react/hooks";
+import Modal from "../../react/Modal";
+import RawHtml from "../../react/RawHtml";
+import MfaStatusBadge, { MfaStatusTone } from "./components/MfaStatusBadge";
+import OptionsPageHeader from "./components/OptionsPageHeader";
+import TimeSelector from "./components/TimeSelector";
+import { TotpSettings } from "./totp";
+
+export default function PasswordSettings() {
+ return (
+ <>
+ <OptionsPageHeader />
+ {/* The sign-in method (and its two-factor / OAuth settings) is only available on the server
+ build — the desktop app authenticates differently — matching the former MFA page's
+ serverOnly scope. */}
+ {!isElectron() && <SignInMethod />}
+ <ChangePassword />
+ <ProtectedSessionTimeout />
+ </>
+ );
+}
+
+function ChangePassword() {
+ const [showModal, setShowModal] = useState(false);
+
+ return (
+ <div className="options-section">
+ <Card heading={t("password.heading")}>
+ <CardOption
+ label={t("password.change_password")}
+ description={t("password.change_password_description")}
+ >
+ <Button
+ name="change-password-button"
+ text={t("password.change_password_button")}
+ size="micro"
+ onClick={() => setShowModal(true)}
+ />
+ </CardOption>
+
+ <CardOption
+ label={t("password.reset_password")}
+ description={t("password.reset_password_description")}
+ >
+ <Button
+ name="reset-password-button"
+ text={t("password.reset_password_button")}
+ size="micro"
+ onClick={async () => {
+ if (!await dialog.confirm(t("password.reset_confirmation"))) {
+ return;
+ }
+
+ await server.post("password/reset?really=yesIReallyWantToResetPasswordAndLoseAccessToMyProtectedNotes");
+ toast.showError(t("password.reset_success_message"));
+ }}
+ />
+ </CardOption>
+ </Card>
+
+ {createPortal(
+ <ChangePasswordModal show={showModal} onHidden={() => setShowModal(false)} />,
+ document.body
+ )}
+ </div>
+ );
+}
+
+interface ChangePasswordModalProps {
+ show: boolean;
+ onHidden: () => void;
+}
+
+function ChangePasswordModal({ show, onHidden }: ChangePasswordModalProps) {
+ const [oldPassword, setOldPassword] = useState("");
+ const [newPassword1, setNewPassword1] = useState("");
+ const [newPassword2, setNewPassword2] = useState("");
+
+ const handleSubmit = async () => {
+ if (newPassword1 !== newPassword2) {
+ toast.showError(t("password.password_mismatch"));
+ return;
+ }
+
+ const result = await server.post<ChangePasswordResponse>("password/change", {
+ current_password: oldPassword,
+ new_password: newPassword1
+ });
+
+ if (result.success) {
+ onHidden();
+ setOldPassword("");
+ setNewPassword1("");
+ setNewPassword2("");
+ toast.showMessage(t("password.password_changed_success"));
+
+ // password changed so current protected session is invalid and needs to be cleared
+ protected_session_holder.resetProtectedSession();
+ } else if (result.message) {
+ toast.showError(result.message);
+ }
+ };
+
+ const handleHidden = () => {
+ setOldPassword("");
+ setNewPassword1("");
+ setNewPassword2("");
+ onHidden();
+ };
+
+ return (
+ <Modal
+ show={show}
+ onHidden={handleHidden}
+ onSubmit={handleSubmit}
+ title={t("password.change_password_heading")}
+ className="change-password-modal"
+ size="md"
+ stackable
+ footer={
+ <>
+ <Button text={t("password.cancel")} onClick={handleHidden} />
+ <Button text={t("password.change_password")} kind="primary" />
+ </>
+ }
+ >
+ <FormGroup name="old-password" label={t("password.old_password")}>
+ <FormTextBox
+ type="password"
+ currentValue={oldPassword}
+ onChange={setOldPassword}
+ />
+ </FormGroup>
+
+ <FormGroup name="new-password1" label={t("password.new_password")}>
+ <FormTextBox
+ type="password"
+ currentValue={newPassword1}
+ onChange={setNewPassword1}
+ />
+ </FormGroup>
+
+ <FormGroup name="new-password2" label={t("password.new_password_confirmation")}>
+ <FormTextBox
+ type="password"
+ currentValue={newPassword2}
+ onChange={setNewPassword2}
+ />
+ </FormGroup>
+ </Modal>
+ );
+}
+
+function ProtectedSessionTimeout() {
+ return (
+ <div className="options-section">
+ <Card heading={t("password.protected_session_timeout")}>
+ <CardOption
+ name="protected-session-timeout"
+ label={t("password.protected_session_timeout_label")}
+ description={<>{t("password.protected_session_timeout_description")} <a class="tn-link" href="https://triliumnext.github.io/Docs/Wiki/protected-notes.html">{t("password.wiki")}</a> {t("password.for_more_info")}</>}
+ >
+ <TimeSelector
+ name="protected-session-timeout"
+ optionValueId="protectedSessionTimeout"
+ optionTimeScaleId="protectedSessionTimeoutTimeScale"
+ minimumSeconds={60}
+ />
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
+/**
+ * Two-factor authentication settings. Owns the live TOTP/OAuth status (the method selector needs
+ * `totpStatus.set` to know whether to offer switching methods) and delegates the heavier TOTP UI to
+ * its own module; OAuth is small and read-only, so it lives here.
+ */
+function SignInMethod() {
+ // `mfaMethod` is the persisted choice: "oauth" means sign in via an OAuth provider, anything else
+ // ("totp") means the local password (with TOTP as optional second factor). The dropdown speaks in
+ // the user-facing "local"/"oauth" terms and maps back to the option here.
+ const [ mfaMethod, setMfaMethod ] = useTriliumOption("mfaMethod");
+ const [ totpStatus, setTotpStatus ] = useState<TOTPStatus>();
+ const [ oauthStatus, setOauthStatus ] = useState<OAuthStatus>();
+
+ const refreshTotpStatus = useCallback(() => {
+ server.get<TOTPStatus>("totp/status").then(setTotpStatus);
+ }, []);
+
+ const refreshOauthStatus = useCallback(() => {
+ server.get<OAuthStatus>("oauth/status").then(setOauthStatus);
+ }, []);
+
+ useEffect(() => {
+ refreshTotpStatus();
+ refreshOauthStatus();
+ }, [ refreshTotpStatus, refreshOauthStatus ]);
+
+ const usingOAuth = mfaMethod === "oauth";
+
+ return (
+ <>
+ <div className="options-section signin-method">
+ <Card heading={t("multi_factor_authentication.authentication_title")}>
+ <CardOption name="signin-method" label={t("multi_factor_authentication.signin_method")}>
+ <FormSelect
+ values={[
+ { value: "local", label: t("multi_factor_authentication.signin_local") },
+ { value: "oauth", label: t("multi_factor_authentication.signin_oauth") }
+ ]}
+ keyProperty="value" titleProperty="label"
+ currentValue={usingOAuth ? "oauth" : "local"}
+ onChange={(value) => setMfaMethod(value === "oauth" ? "oauth" : "totp")}
+ />
+ </CardOption>
+
+ {/* What the chosen method means, below the choice rather than above it — it
+ describes what was picked, not what is on offer. */}
+ <CardSection className="signin-method-description">
+ <FormText>
+ { usingOAuth
+ ? <RawHtml html={t("multi_factor_authentication.oauth_description")} />
+ : t("multi_factor_authentication.signin_local_description") }
+ </FormText>
+ </CardSection>
+ </Card>
+ </div>
+
+ { usingOAuth
+ ? <OAuthStatusCard status={oauthStatus} refreshStatus={refreshOauthStatus} />
+ : <TotpSettings totpStatus={totpStatus} refreshTotpStatus={refreshTotpStatus} /> }
+ </>
+ );
+}
+
+/**
+ * OAuth status card, shown when OAuth is the selected sign-in method. The provider credentials are
+ * configured server-side (env vars / config.ini), but binding an account is an explicit in-app step —
+ * mirroring TOTP's verify-before-enable. Three states:
+ * - **not configured** → show the config hint (the server vars are missing);
+ * - **configured, not enrolled** → offer "Connect account", which runs the provider round-trip and
+ * binds the returned identity. SSO only becomes the live login method once this completes;
+ * - **enrolled** → show the connected account and a "Disconnect" action.
+ */
+function OAuthStatusCard({ status, refreshStatus }: { status?: OAuthStatus, refreshStatus: () => void }) {
+ // "Configured" is purely about the server-side variables being present (the server's `enabled` flag
+ // additionally requires mfaMethod === 'oauth', which is implied here since this card only renders then).
+ const configured = (status?.missingVars?.length ?? 1) === 0;
+ const enrolled = status?.enrolled ?? false;
+
+ // The status badge mirrors the card's three states: an account is bound (green "Connected"),
+ // the server is set up but no account is bound yet (amber "Not connected"), or the server-side
+ // variables are missing entirely (muted "Not configured").
+ const badge: { tone: MfaStatusTone, text: string } = enrolled
+ ? { tone: "active", text: t("multi_factor_authentication.oauth_status_connected") }
+ : configured
+ ? { tone: "pending", text: t("multi_factor_authentication.oauth_status_not_connected") }
+ : { tone: "inactive", text: t("multi_factor_authentication.oauth_status_not_configured") };
+
+ // Enrollment is a full-page provider round-trip (not an XHR): navigate to the OIDC login route,
+ // which on return binds the identity to this still-authenticated session (see open_id afterCallback).
+ // The return lands on the app root and drops this modal; the resulting "connected" toast is driven by
+ // a one-shot bootstrap flag (see showOAuthEnrollmentResultToast), so nothing is tracked here.
+ const connectAccount = useCallback(() => {
+ window.location.href = "authenticate";
+ }, []);
+
+ const disconnectAccount = useCallback(async () => {
+ if (!await dialog.confirm(t("multi_factor_authentication.oauth_disconnect_confirm"))) {
+ return;
+ }
+
+ // Resolve the labels before disconnecting, while the account is still bound.
+ const account = oauthAccountLabel(status);
+ const provider = oauthProviderDisplayName(status);
+
+ await server.post("oauth/disconnect");
+ toast.showMessage(t("multi_factor_authentication.oauth_disconnected", { account, provider }));
+ refreshStatus();
+ }, [ status, refreshStatus ]);
+
+ return (
+ <div className="options-section">
+ <Card
+ heading={t("multi_factor_authentication.oauth_title")}
+ actions={<MfaStatusBadge tone={badge.tone} text={badge.text} />}
+ >
+ { !configured ? (
+ <CardSection className="mfa-notice">
+ <ExtendedAdmonition
+ type="note"
+ icon="bx bx-info-circle"
+ title={t("multi_factor_authentication.oauth_not_configured_title")}
+ detailsLabel={t("multi_factor_authentication.oauth_how_to_enable")}
+ details={<OAuthConfigInstructions />}
+ >
+ <p>{t("multi_factor_authentication.oauth_not_configured_hint")}</p>
+
+ { status?.missingVars && status.missingVars.length > 0 && (
+ <p>
+ {t("multi_factor_authentication.oauth_missing_vars", {
+ variables: status.missingVars.map(v => `"${v}"`).join(", ")
+ })}
+ </p>
+ )}
+ </ExtendedAdmonition>
+ </CardSection>
+ ) : enrolled ? (
+ <>
+ <OAuthProviderRows status={status} />
+ <CardOption label={t("multi_factor_authentication.oauth_user_account")}>
+ <span>{status?.name ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
+ </CardOption>
+ <CardOption label={t("multi_factor_authentication.oauth_user_email")}>
+ <span>{status?.email ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
+ </CardOption>
+
+ <CardOption
+ label={t("multi_factor_authentication.oauth_disconnect_label")}
+ description={t("multi_factor_authentication.oauth_disconnect_description")}
+ >
+ <Button
+ name="oauth-disconnect-button"
+ className="oauth-disconnect-button"
+ icon="bx-trash"
+ text={t("multi_factor_authentication.oauth_disconnect_button")}
+ size="micro"
+ onClick={() => void disconnectAccount()}
+ />
+ </CardOption>
+ </>
+ ) : (
+ <>
+ <CardSection className="mfa-notice">
+ <ExtendedAdmonition
+ type="note"
+ icon="bx bx-info-circle"
+ title={t("multi_factor_authentication.oauth_not_enrolled_title")}
+ detailsLabel={t("multi_factor_authentication.oauth_not_enrolled_details_label")}
+ details={t("multi_factor_authentication.oauth_not_enrolled_details")}
+ >
+ {t("multi_factor_authentication.oauth_not_enrolled_hint")}
+ </ExtendedAdmonition>
+ </CardSection>
+
+ <OAuthProviderRows status={status} />
+
+ <CardOption
+ label={t("multi_factor_authentication.oauth_connect_label")}
+ description={t("multi_factor_authentication.oauth_connect_description")}
+ >
+ <Button
+ name="oauth-connect-button"
+ icon="bx-log-in"
+ text={t("multi_factor_authentication.oauth_connect_button")}
+ size="micro"
+ onClick={connectAccount}
+ />
+ </CardOption>
+ </>
+ )}
+ </Card>
+ </div>
+ );
+}
+
+/**
+ * Identifies the configured OAuth provider: its icon and display name, plus the issuer URL. Shown
+ * whenever OAuth is configured so the owner can confirm which server they'll be redirected to.
+ */
+function OAuthProviderRows({ status }: { status?: OAuthStatus }) {
+ const displayName = oauthProviderDisplayName(status);
+ return (
+ <>
+ <CardOption label={t("multi_factor_authentication.oauth_provider")}>
+ <span className="oauth-provider">
+ <OAuthProviderIcon src={status?.issuerIcon} />
+ <span>{displayName}</span>
+ </span>
+ </CardOption>
+ { status?.issuerUrl && (
+ <CardOption label={t("multi_factor_authentication.oauth_provider_url")}>
+ <span>{status.issuerUrl}</span>
+ </CardOption>
+ )}
+ </>
+ );
+}
+
+/**
+ * Provider icon for the OAuth status card. Renders the configured/derived issuer icon, falling back
+ * to a neutral key glyph when no icon is available or the image fails to load (e.g. a derived
+ * favicon URL that the issuer doesn't actually serve).
+ */
+function OAuthProviderIcon({ src }: { src?: string }) {
+ const [ failed, setFailed ] = useState(false);
+
+ // Reset the fallback flag when the source changes (e.g. the user switches providers), otherwise a
+ // previously-failed load would keep showing the key glyph even when the new URL is perfectly valid.
+ useEffect(() => setFailed(false), [src]);
+
+ if (!src || failed) {
+ return <span className="bx bx-key oauth-provider-icon" />;
+ }
+
+ return <img className="oauth-provider-icon" src={src} alt="" onError={() => setFailed(true)} />;
+}
+
+/**
+ * "How to enable" instructions for OAuth, shown in the not-configured admonition's collapsible. Lists
+ * the config.ini section and the equivalent environment variables the server reads — OAuth has no
+ * in-app setup, so this is the only place the values are documented in the UI.
+ */
+function OAuthConfigInstructions() {
+ // oauthBaseUrl is the app's externally-reachable base URL, which for the user reading this is
+ // exactly the origin they're browsing from — so prefill it as a sensible example value.
+ const baseUrl = window.location.origin;
+ return (
+ <>
+ <p>{t("multi_factor_authentication.oauth_server_config_hint")}</p>
+ <pre><code>{`[MultiFactorAuthentication]\noauthBaseUrl=${baseUrl}\noauthClientId=\noauthClientSecret=`}</code></pre>
+ <p>{t("multi_factor_authentication.oauth_server_env_hint")}</p>
+ <pre><code>{`TRILIUM_OAUTH_BASE_URL=${baseUrl}\nTRILIUM_OAUTH_CLIENT_ID=\nTRILIUM_OAUTH_CLIENT_SECRET=`}</code></pre>
+ </>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/options/sync.css b/apps/client/src/widgets/type_widgets/options/sync.css
deleted file mode 100644
index e94841f0fb..0000000000
--- a/apps/client/src/widgets/type_widgets/options/sync.css
+++ /dev/null
@@ -1,5 +0,0 @@
-/* The width a duration box was given while the page framed its own cards (`.options-section-card` in
- style.css), which a Card does not carry. */
-.sync-timeout input[type="number"] {
- width: 7em;
-}
diff --git a/apps/client/src/widgets/type_widgets/options/sync.tsx b/apps/client/src/widgets/type_widgets/options/sync.tsx
index a885607362..c172946b23 100644
--- a/apps/client/src/widgets/type_widgets/options/sync.tsx
+++ b/apps/client/src/widgets/type_widgets/options/sync.tsx
@@ -1,5 +1,3 @@
-import "./sync.css";
-
import { SyncTestResponse } from "@triliumnext/commons";
import { useEffect, useState } from "preact/hooks";
@@ -85,7 +83,6 @@ export function SyncConfiguration() {
</CardOption>
<CardOption
- className="sync-timeout"
name="sync-server-timeout"
label={t("sync_2.timeout")}
description={t("sync_2.timeout_description")}
diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.css b/apps/client/src/widgets/type_widgets/options/text_notes.css
index cb7d09ee09..6f4925b110 100644
--- a/apps/client/src/widgets/type_widgets/options/text_notes.css
+++ b/apps/client/src/widgets/type_widgets/options/text_notes.css
@@ -124,29 +124,16 @@
}
}
-/* Bootstrap gives a select the whole width of what holds it, which in a card row leaves the label
- beside it a word to the line. Sized to what it offers instead, and cut short rather than carried
- across the row — the bounds the option rows carried before these were card segments. */
-.text-notes-replacements select,
-.text-notes-code-blocks select {
- width: auto;
- min-width: 150px;
- max-width: 260px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* The same for a text box, which is a format string of known length rather than a sentence: `auto`
- is the browser's own twenty characters, which is what the format written in it needs. */
+/* A format string of known length rather than a sentence: `auto` is the browser's own twenty
+ characters, which is what the format written in it needs. */
.text-notes-editor input[type="text"] {
width: auto;
max-width: 100%;
}
-/* A figure and the unit it is read in, sized to the figure: Bootstrap gives an input group the whole
- width of what holds it, which in a card row is the row. */
-.text-notes-number .tn-number-unit-pair {
+/* The heading threshold stands in a plain segment rather than a settings row, so the figure sizing a
+ card option gets does not reach it. */
+.text-notes-toc .tn-number-unit-pair {
width: auto;
input[type="number"] {
diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.tsx
index b446a3b490..4ce563acd4 100644
--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx
+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx
@@ -435,7 +435,6 @@ function Editor() {
</CardOption>
<CardOption
- className="text-notes-number"
name="auto-readonly-size-text"
label={t("text_auto_read_only_size.label")}
description={t("text_auto_read_only_size.description")}
@@ -598,7 +597,7 @@ function CodeBlockStyle() {
</CardOption>
{/* Avoid using "code" in the name of numeric inputs to prevent KeepassXC from triggering. */}
- <CardOption className="text-notes-number" name="block-tab-width" label={t("code_block.tab_width")}>
+ <CardOption name="block-tab-width" label={t("code_block.tab_width")}>
<FormTextBoxWithUnit
type="number" min={1} max={16} step={1}
unit={t("code_block.tab_width_unit")}
@@ -682,7 +681,7 @@ function TableOfContent() {
heading={t("table_of_contents.title")}
description={t("table_of_contents.description")}
>
- <CardSection className="text-notes-number">
+ <CardSection>
<FormGroup name="min-toc-headings">
<FormTextBoxWithUnit
type="number"