Skip to content

Build your personal knowledge base with Trilium Notes

15.7 KB
Raw Blame
import { FilterLabelsByType } from "@triliumnext/commons";
import { Fragment, VNode } from "preact";
import { useContext, useEffect, useState } from "preact/hooks";

import Component from "../../components/component";
import FNote from "../../entities/fnote";
import NoteContextAwareWidget from "../note_context_aware_widget";
import { OptionCardSection } from "./Card";
import { FormDropdownDivider, FormDropdownSubmenu, FormListItem, FormListToggleableItem } from "./FormList";
import FormSelect, { FormSelectWithGroups } from "./FormSelect";
import FormToggle from "./FormToggle";
import HelpTooltipButton from "./HelpTooltipButton";
import FormTextBox from "./FormTextBox";
import { useNoteLabel, useNoteLabelBoolean } from "./hooks";
import { NoteContextContext, ParentComponent } from "./react_utils";

export interface ClickContext {
    note: FNote;
    /** The note context the menu stands in, when it stands in one other than a split's. */
    ntxId?: string | null;
    triggerCommand: NoteContextAwareWidget["triggerCommand"];
}

/** Available on a property of any kind, for one whose label needs explaining. */
export interface PropertyHelp {
    /** What the property does, shown on hover beside its label. */
    helpTooltip?: string;
}

export interface CheckBoxProperty {
    type: "checkbox",
    label: string;
    bindToLabel: FilterLabelsByType<boolean>;
    icon?: string;
    /** When true, the checkbox will be checked when the label value is false. Useful when the label represents a "hide" action, without exposing double negatives to the user. */
    reverseValue?: boolean;
    /** What the setting does, shown on hover beside the label. */
    helpTooltip?: string;
}

export interface ButtonProperty {
    type: "button",
    label: string;
    title?: string;
    icon?: string;
    onClick(context: ClickContext): void;
}

export interface SplitButtonProperty extends Omit<ButtonProperty, "type"> {
    type: "split-button";
    items({ note, parentComponent }: { note: FNote, parentComponent: Component }): VNode;
}

export interface NumberProperty {
    type: "number",
    label: string;
    bindToLabel: FilterLabelsByType<number>;
    width?: number;
    min?: number;
    icon?: string;
    disabled?: (note: FNote) => boolean;
}

export interface ComboBoxItem {
    /**
     * The value to set to the bound label, `null` has a special meaning which removes the label entirely.
     */
    value: string | null;
    label: string;
}

export interface ComboBoxGroup {
    title: string;
    items: ComboBoxItem[];
}

interface Separator {
    type: "separator"
}

export interface ComboBoxProperty {
    type: "combobox",
    label: string;
    icon?: string;
    bindToLabel: FilterLabelsByType<string>;
    /**
     * The default value is used when the label is not set.
     */
    defaultValue?: string;
    options: (ComboBoxItem | Separator | ComboBoxGroup)[];
    /** When provided, the property is only rendered if this returns true for the current note. */
    isVisible?: (note: FNote) => boolean;
}

export interface SubmenuProperty {
    type: "submenu";
    label: string;
    icon?: string;
    /** When provided, the submenu is only rendered if this returns true for the current note. */
    isVisible?: (note: FNote) => boolean;
    children: BookProperty[];
}

/** A labelled group of radio-style options rendered inline (e.g. inside a {@link SubmenuProperty}), bound to its own label. */
export interface OptionGroupProperty {
    type: "option-group";
    label: string;
    bindToLabel: FilterLabelsByType<string>;
    defaultValue?: string;
    options: ComboBoxItem[];
}

export type BookProperty = (
    CheckBoxProperty | ButtonProperty | NumberProperty | ComboBoxProperty
    | SplitButtonProperty | SubmenuProperty | OptionGroupProperty | Separator
) & PropertyHelp;

/** Whether a property should render for the given note, honouring an optional `isVisible` predicate. */
export function isPropertyVisible(property: BookProperty, note: FNote): boolean {
    return !("isVisible" in property) || (property.isVisible?.(note) ?? true);
}

/** A property's label, followed by its explanation when it has one. */
function PropertyLabel({ property }: { property: BookProperty & { label: string } }) {
    return (
        <>
            {property.label}
            {property.helpTooltip && <HelpTooltipButton description={property.helpTooltip} />}
        </>
    );
}

export function ViewProperty({ note, property }: { note: FNote, property: BookProperty }) {
    if (!isPropertyVisible(property, note)) {
        return null;
    }

    switch (property.type) {
        case "button":
            return <ButtonPropertyView note={note} property={property} />;
        case "split-button":
            return <SplitButtonPropertyView note={note} property={property} />;
        case "checkbox":
            return <CheckBoxPropertyView note={note} property={property} />;
        case "number":
            return <NumberPropertyView note={note} property={property} />;
        case "combobox":
            return <ComboBoxPropertyView note={note} property={property} />;
        case "submenu":
            return <SubmenuPropertyView note={note} property={property} />;
        case "option-group":
            return <OptionGroupPropertyView note={note} property={property} />;
        case "separator":
            return <FormDropdownDivider />;
    }
}

/**
 * A property as a row of a settings card, for a dialog that offers what the collection's settings
 * dropdown does. Covers switches, numbers, option groups, comboboxes and the submenus holding them;
 * buttons and the other kinds that only make sense in a menu render nothing.
 */
export function ViewPropertySection({ note, property }: { note: FNote, property: BookProperty }) {
    switch (property.type) {
        case "checkbox":
            return <CheckBoxPropertySection note={note} property={property} />;
        case "number":
            return <NumberPropertySection note={note} property={property} />;
        case "option-group":
            return <OptionGroupPropertySection note={note} property={property} />;
        case "combobox":
            return <ComboBoxPropertySection note={note} property={property} />;
        case "submenu":
            return (
                <OptionCardSection
                    label={property.label}
                    description={property.helpTooltip}
                    subSectionsVisible
                    subSections={property.children.map((child, index) => (
                        <ViewPropertySection key={index} note={note} property={child} />
                    ))}
                />
            );
        default:
            return null;
    }
}

function SubmenuPropertyView({ note, property }: { note: FNote, property: SubmenuProperty }) {
    return (
        <FormDropdownSubmenu
            title={<PropertyLabel property={property} />}
            icon={property.icon ?? "bx bx-empty"}
        >
            {property.children.map((child, index) => (
                <ViewProperty key={index} note={note} property={child} />
            ))}
        </FormDropdownSubmenu>
    );
}

function OptionGroupPropertyView({ note, property }: { note: FNote, property: OptionGroupProperty }) {
    const [ value, setValue ] = useNoteLabel(note, property.bindToLabel);
    const valueWithDefault = value ?? property.defaultValue ?? null;

    return (
        <Fragment>
            <FormListItem disabled><PropertyLabel property={property} /></FormListItem>
            {property.options.map((option) => (
                <FormListItem
                    key={option.value}
                    checked={valueWithDefault === option.value}
                    // Keep the menu open so several grouped settings can be adjusted in one go.
                    onClick={(e) => {
                        e.stopPropagation();
                        setValue(option.value);
                    }}
                >
                    {option.label}
                </FormListItem>
            ))}
        </Fragment>
    );
}

function ButtonPropertyView({ note, property }: { note: FNote, property: ButtonProperty }) {
    const parentComponent = useContext(ParentComponent);
    const noteContext = useContext(NoteContextContext);

    return (
        <FormListItem
            icon={property.icon}
            title={property.title}
            onClick={() => {
                if (!parentComponent) return;
                property.onClick({
                    note,
                    ntxId: noteContext?.ntxId,
                    triggerCommand: parentComponent.triggerCommand.bind(parentComponent)
                });
            }}
        ><PropertyLabel property={property} /></FormListItem>
    );
}

function SplitButtonPropertyView({ note, property }: { note: FNote, property: SplitButtonProperty }) {
    const parentComponent = useContext(ParentComponent);
    const ItemsComponent = property.items;
    const noteContext = useContext(NoteContextContext);
    const clickContext = parentComponent && {
        note,
        ntxId: noteContext?.ntxId,
        triggerCommand: parentComponent.triggerCommand.bind(parentComponent)
    };

    return (parentComponent &&
        <FormDropdownSubmenu
            icon={property.icon ?? "bx bx-empty"}
            title={<PropertyLabel property={property} />}
            onDropdownToggleClicked={() => clickContext && property.onClick(clickContext)}
        >
            <ItemsComponent note={note} parentComponent={parentComponent} />
        </FormDropdownSubmenu>
    );
}

function NumberPropertyView({ note, property }: { note: FNote, property: NumberProperty }) {
    const [ draft, setDraft, commit ] = useNumberLabelDraft(note, property.bindToLabel);
    const disabled = property.disabled?.(note);

    return (
        <FormListItem
            icon={property.icon}
            disabled={disabled}
            onClick={(e) => e.stopPropagation()}
        >
            <PropertyLabel property={property} />
            <FormTextBox
                type="number"
                allowEmpty
                currentValue={draft} onChange={setDraft} onBlur={commit}
                style={{ width: `${property.width ?? 100}px` }}
                min={property.min ?? 0}
                disabled={disabled}
            />
        </FormListItem>
    );
}

function ComboBoxPropertyView({ note, property }: { note: FNote, property: ComboBoxProperty }) {
    const [ value, setValue ] = useNoteLabel(note, property.bindToLabel);
    const valueWithDefault = value ?? property.defaultValue ?? null;

    function renderItem(option: ComboBoxItem) {
        return (
            <FormListItem
                key={option.value}
                checked={valueWithDefault === option.value}
                onClick={() => setValue(option.value)}
            >
                {option.label}
            </FormListItem>
        );
    }

    return (
        <FormDropdownSubmenu
            title={<PropertyLabel property={property} />}
            icon={property.icon ?? "bx bx-empty"}
        >
            {(property.options).map((option, index) => {
                if ("items" in option) {
                    return (
                        <Fragment key={option.title}>
                            <FormListItem key={option.title} disabled>{option.title}</FormListItem>
                            {option.items.map(renderItem)}
                            {index < property.options.length - 1 && <FormDropdownDivider />}
                        </Fragment>
                    );
                }
                if ("type" in option) {
                    return <FormDropdownDivider key={index} />;
                }

                return renderItem(option);

            })}
        </FormDropdownSubmenu>
    );
}

function CheckBoxPropertyView({ note, property }: { note: FNote, property: CheckBoxProperty }) {
    const [ value, setValue ] = useNoteLabelBoolean(note, property.bindToLabel);
    return (
        <FormListToggleableItem
            icon={property.icon}
            title={property.label}
            helpTooltip={property.helpTooltip}
            currentValue={ property.reverseValue ? !value : value }
            onChange={newValue => setValue(property.reverseValue ? !newValue : newValue)}
        />
    );
}

function CheckBoxPropertySection({ note, property }: { note: FNote, property: CheckBoxProperty }) {
    const [ value, setValue ] = useNoteLabelBoolean(note, property.bindToLabel);
    return (
        <OptionCardSection
            name={property.bindToLabel}
            label={property.label}
            description={property.helpTooltip}
        >
            <FormToggle
                currentValue={property.reverseValue ? !value : value}
                onChange={(newValue) => setValue(property.reverseValue ? !newValue : newValue)}
            />
        </OptionCardSection>
    );
}

function OptionGroupPropertySection({ note, property }: {
    note: FNote, property: OptionGroupProperty & PropertyHelp
}) {
    const [ value, setValue ] = useNoteLabel(note, property.bindToLabel);
    return (
        <OptionCardSection
            name={property.bindToLabel}
            label={property.label}
            description={property.helpTooltip}
        >
            <FormSelect
                values={property.options}
                keyProperty="value"
                titleProperty="label"
                currentValue={value ?? property.defaultValue ?? undefined}
                onChange={setValue}
            />
        </OptionCardSection>
    );
}

function NumberPropertySection({ note, property }: { note: FNote, property: NumberProperty & PropertyHelp }) {
    const [ draft, setDraft, commit ] = useNumberLabelDraft(note, property.bindToLabel);
    return (
        <OptionCardSection
            name={property.bindToLabel}
            label={property.label}
            description={property.helpTooltip}
        >
            <FormTextBox
                type="number"
                allowEmpty
                currentValue={draft}
                onChange={setDraft}
                onBlur={commit}
                min={property.min ?? 0}
                disabled={property.disabled?.(note)}
            />
        </OptionCardSection>
    );
}

/** A combobox as a select, its groups as option groups; a separator has nothing to show there. */
function ComboBoxPropertySection({ note, property }: {
    note: FNote, property: ComboBoxProperty & PropertyHelp
}) {
    const [ value, setValue ] = useNoteLabel(note, property.bindToLabel);
    const values = property.options.filter(
        (option): option is ComboBoxItem | ComboBoxGroup => !("type" in option));
    return (
        <OptionCardSection
            name={property.bindToLabel}
            label={property.label}
            description={property.helpTooltip}
        >
            <FormSelectWithGroups<ComboBoxItem>
                values={values}
                keyProperty="value"
                titleProperty="label"
                currentValue={value ?? property.defaultValue ?? undefined}
                onChange={setValue}
            />
        </OptionCardSection>
    );
}

/**
 * A number label edited in a box: the typed value is held as a draft, written once the box commits
 * (on leaving it, or on a spinner step), and an emptied box removes the label.
 */
function useNumberLabelDraft(note: FNote, labelName: NumberProperty["bindToLabel"]) {
    //@ts-expect-error Interop with text box which takes in string values even for numbers.
    const [ value, setValue ] = useNoteLabel(note, labelName);
    const [ draft, setDraft ] = useState(value ?? "");

    useEffect(() => setDraft(value ?? ""), [ value ]);

    function commit(newValue: string) {
        const next = newValue.trim() || null;
        if (next !== (value ?? null)) {
            setValue(next);
        }
    }

    return [ draft, setDraft, commit ] as const;
}