Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
Update Preact Components for Scripts
BeatLink7379c835e251
diff --git a/CLAUDE.md b/CLAUDE.mdindex b4c2247edb..650b89ee81 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -125,11 +125,18 @@ Common UI components are available in `apps/client/src/widgets/react/` — **alw- `NoItems` - Empty state placeholder with icon and message (use for "no results", "too many items", error states)- `ActionButton` - Consistent button styling with icon support- `FormTextBox` - Text input with validation and controlled input handling; `FormTextBoxWithUnit` for inputs with a unit suffix (e.g. "mm", "px")+- `FormNumber` - Native `<input type="number">` with `min`/`max`/`step`; thin wrapper over `FormTextBox` (inherits its min/max clamping), value is a string+- `FormTime` - Native `<input type="time">` (browser time picker); thin wrapper over `FormTextBox`, value is an `"HH:mm"` string+- `FormDatetime` - Native `<input type="datetime-local">` (browser date/time picker); thin wrapper over `FormTextBox`- `FormSelect` - Dropdown/combobox taking an object array as data- `Slider` - Range slider with label- `Checkbox`, `RadioButton` - Form controls-- `CollapsibleSection` - Expandable content sections+- `FormToggleButton` - A boolean toggle rendered as a pill button (pressed = on) using the theme's `btn`/`btn-primary` + `active` classes (like `Button`/`ThemeModeSelector`), not Bootstrap's unstyled `btn-check`. `aria-pressed` for accessibility+- `Collapsible` - Expandable content section (animated, theme-styled); `ExternallyControlledCollapsible` is the controlled variant (caller owns `expanded`/`setExpanded`) vs. `Collapsible`'s self-managed `initiallyExpanded`+- `ColorPicker` - Color picker combining preset swatches with the browser's native `<input type="color">`; value is a CSS color string (`onChange("")` clears). Uses the theme `Dropdown` for its popover — don't hand-roll a color popover- `Badge` - Colored pill/label with optional icon, tooltip, and `onClick` (for counts, status flags). Set its color via the `--color` CSS variable on a wrapper class (not inline styles); pass `outline` for a colored-border/transparent-fill variant instead of a solid background. `BadgeWithDropdown` pairs a badge with a dropdown menu. Don't hand-roll pill/badge markup — reuse it+- `Table` - Generic [Tabulator](https://tabulator.info/)-based data grid (`columns`, `data`, `events`, `modules`, `tabulatorRef`; props typed via `TableProps<T>`). Decoupled from the note/collection model — deals purely in columns/data/events, so use it for any grid (e.g. the SQL console results, the note collection table view). Prefer it over instantiating `tabulator-tables` directly+- `Calendar` - Generic [FullCalendar](https://fullcalendar.io/) wrapper (accepts any `CalendarOptions` plus a `calendarRef`; props typed via `CalendarProps`). Decoupled from the note/collection model — deals purely in FullCalendar options, so use it for any calendar rather than instantiating `@fullcalendar/core` directlyFluent builder pattern: `.child()`, `.class()`, `.css()` chaining with position-based ordering.diff --git a/apps/client/src/services/frontend_script_api_preact.ts b/apps/client/src/services/frontend_script_api_preact.tsindex 3edac085f3..6d2efe57e1 100644--- a/apps/client/src/services/frontend_script_api_preact.ts+++ b/apps/client/src/services/frontend_script_api_preact.ts@@ -4,19 +4,25 @@ import * as hooks from "preact/hooks";import ActionButton from "../widgets/react/ActionButton";import Admonition from "../widgets/react/Admonition";import Button from "../widgets/react/Button";+import Calendar from "../widgets/react/Calendar";import CKEditor from "../widgets/react/CKEditor";-import Collapsible from "../widgets/react/Collapsible";+import Collapsible, { ExternallyControlledCollapsible } from "../widgets/react/Collapsible";+import ColorPicker from "../widgets/react/ColorPicker";import Dropdown from "../widgets/react/Dropdown";import FormCheckbox from "../widgets/react/FormCheckbox";+import FormDatetime from "../widgets/react/FormDatetime";import FormDropdownList from "../widgets/react/FormDropdownList";import { FormFileUploadActionButton, FormFileUploadButton } from "../widgets/react/FormFileUpload";import FormGroup from "../widgets/react/FormGroup";import { FormDropdownDivider, FormDropdownSubmenu, FormListItem } from "../widgets/react/FormList";+import FormNumber from "../widgets/react/FormNumber";import FormRadioGroup from "../widgets/react/FormRadioGroup";import FormText from "../widgets/react/FormText";import FormTextArea from "../widgets/react/FormTextArea";import FormTextBox from "../widgets/react/FormTextBox";+import FormTime from "../widgets/react/FormTime";import FormToggle from "../widgets/react/FormToggle";+import FormToggleButton from "../widgets/react/FormToggleButton";import * as triliumHooks from "../widgets/react/hooks";import Icon from "../widgets/react/Icon";import LinkButton from "../widgets/react/LinkButton";@@ -26,6 +32,7 @@ import NoteAutocomplete from "../widgets/react/NoteAutocomplete";import NoteLink from "../widgets/react/NoteLink";import RawHtml from "../widgets/react/RawHtml";import Slider from "../widgets/react/Slider";+import Table from "../widgets/react/Table";import RightPanelWidget from "../widgets/sidebar/RightPanelWidget";export interface WidgetDefinition {@@ -72,19 +79,24 @@ export const preactAPI = Object.freeze({ActionButton,Admonition,Button,+ Calendar,CKEditor,- Collapsible,+ Collapsible, ExternallyControlledCollapsible,+ ColorPicker,Dropdown,FormCheckbox,+ FormDatetime,FormDropdownList,FormFileUploadButton, FormFileUploadActionButton,FormGroup,FormListItem, FormDropdownDivider, FormDropdownSubmenu,+ FormNumber,FormRadioGroup,FormText,FormTextArea,FormTextBox,- FormToggle,+ FormTime,+ FormToggle, FormToggleButton,Icon,LinkButton,LoadingSpinner,@@ -93,6 +105,7 @@ export const preactAPI = Object.freeze({NoteLink,RawHtml,Slider,+ Table,// Specialized widgetsRightPanelWidget,@@ -110,5 +123,4 @@ export const preactAPI = Object.freeze({// so they aren't part of the shared surface and aren't checked.)type _PublicPreactExports = keyof typeof import("@triliumnext/commons/src/lib/script_api_preact.js");type _MissingPreactMembers = Exclude<_PublicPreactExports, keyof typeof preactAPI>;-// eslint-disable-next-line @typescript-eslint/no-unused-varsconst _preactDriftGuard: [_MissingPreactMembers] extends [never] ? true : _MissingPreactMembers = true;diff --git a/apps/client/src/test/render.ts b/apps/client/src/test/render.tsnew file mode 100644index 0000000000..60c7da6649--- /dev/null+++ b/apps/client/src/test/render.ts@@ -0,0 +1,26 @@+import { type ComponentChild, render } from "preact";+import { afterEach } from "vitest";++let container: HTMLDivElement | undefined;++/**+ * Render a Preact vnode into a detached-but-attached div and return the container.+ *+ * The container is torn down automatically after each test (see the `afterEach` below), which also+ * disposes any Bootstrap tooltips / event listeners the component registered, preventing leaks+ * between tests.+ */+export function renderInto(vnode: ComponentChild) {+ container = document.createElement("div");+ document.body.appendChild(container);+ render(vnode, container);+ return container;+}++afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+});diff --git a/apps/client/src/widgets/collections/calendar/calendar.tsx b/apps/client/src/widgets/collections/calendar/calendar.tsxindex 92968bbb27..46511ed925 100644--- a/apps/client/src/widgets/collections/calendar/calendar.tsx+++ b/apps/client/src/widgets/collections/calendar/calendar.tsx@@ -2,7 +2,7 @@ import { useEffect, useLayoutEffect, useRef } from "preact/hooks";import { CalendarOptions, Calendar as FullCalendar, PluginDef } from "@fullcalendar/core";import { RefObject } from "preact";-interface CalendarProps extends CalendarOptions {+export interface CalendarProps extends CalendarOptions {calendarRef?: RefObject<FullCalendar>;}diff --git a/apps/client/src/widgets/collections/table/tabulator.tsx b/apps/client/src/widgets/collections/table/tabulator.tsxindex 62d7283b94..dfb95a4b8b 100644--- a/apps/client/src/widgets/collections/table/tabulator.tsx+++ b/apps/client/src/widgets/collections/table/tabulator.tsx@@ -8,7 +8,7 @@ import { EventCallBackMethods, Module, Options, Tabulator as VanillaTabulator }import { ParentComponent, renderReactWidget } from "../../react/react_utils";-interface TableProps<T> extends Omit<Options, "data" | "footerElement" | "index"> {+export interface TableProps<T> extends Omit<Options, "data" | "footerElement" | "index"> {tabulatorRef?: RefObject<VanillaTabulator>;className?: string;data?: T[];diff --git a/apps/client/src/widgets/react/Calendar.tsx b/apps/client/src/widgets/react/Calendar.tsxnew file mode 100644index 0000000000..65ceccc9d8--- /dev/null+++ b/apps/client/src/widgets/react/Calendar.tsx@@ -0,0 +1,9 @@+/**+ * Public re-export of the generic FullCalendar-based calendar wrapper as a shared Preact widget.+ *+ * The implementation lives at `../collections/calendar/calendar` for historical reasons; this module+ * exposes it from the reusable `widgets/react/` component folder so features outside the note+ * collection view can consume it without reaching into `collections/calendar`. It is decoupled from+ * Trilium's note model — it deals purely in FullCalendar options and a `calendarRef`.+ */+export { default, type CalendarProps } from "../collections/calendar/calendar";diff --git a/apps/client/src/widgets/react/ColorPicker.css b/apps/client/src/widgets/react/ColorPicker.cssnew file mode 100644index 0000000000..2caa2c56d9--- /dev/null+++ b/apps/client/src/widgets/react/ColorPicker.css@@ -0,0 +1,70 @@+.tn-color-picker {+ .tn-color-picker-trigger {+ display: inline-flex;+ align-items: center;+ gap: 0.4em;+ min-width: 0;+ }++ .tn-color-picker-trigger-swatch {+ flex: 0 0 auto;+ width: 1.1em;+ height: 1.1em;+ border-radius: 50%;+ border: 1px solid var(--main-border-color);+ }++ .tn-color-picker-trigger-label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .tn-color-picker-grid {+ display: flex;+ flex-wrap: wrap;+ gap: 0.35em;+ padding: 0.6em;+ max-width: 14em;+ }++ .tn-color-picker-swatch {+ width: 1.5em;+ height: 1.5em;+ padding: 0;+ border-radius: 50%;+ border: 2px solid transparent;+ cursor: pointer;++ &.active {+ border-color: var(--main-text-color);+ }+ }++ .tn-color-picker-custom {+ display: flex;+ align-items: center;+ gap: 0.5em;+ padding: 0.3em 0.6em;+ cursor: pointer;++ input[type="color"] {+ width: 1.6em;+ height: 1.6em;+ padding: 0;+ border: 1px solid var(--main-border-color);+ border-radius: 0.25em;+ background: none;+ cursor: pointer;+ }+ }++ .tn-color-picker-clear {+ display: flex;+ align-items: center;+ gap: 0.3em;+ width: 100%;+ padding: 0.3em 0.6em;+ text-align: start;+ }+}diff --git a/apps/client/src/widgets/react/ColorPicker.spec.tsx b/apps/client/src/widgets/react/ColorPicker.spec.tsxnew file mode 100644index 0000000000..951fa31c0a--- /dev/null+++ b/apps/client/src/widgets/react/ColorPicker.spec.tsx@@ -0,0 +1,63 @@+import { describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";++// ColorPicker's popover is a themed `Dropdown` whose children only exist in the DOM while open+// (Bootstrap-driven state that happy-dom can't flip). Stub it to render the trigger + menu content+// inline so we can exercise ColorPicker's own logic (swatches, native input, clear) directly.+vi.mock("./Dropdown", () => ({+ default: ({ text, children }: { text: unknown; children: unknown }) => (+ <div className="dropdown-stub">+ <div className="dropdown-stub-trigger">{text}</div>+ <div className="dropdown-stub-menu">{children}</div>+ </div>+ )+}));++import ColorPicker from "./ColorPicker";++describe("ColorPicker", () => {+ it("renders a preset swatch grid and marks the current value active", () => {+ const container = renderInto(<ColorPicker currentValue="#43a047" onChange={vi.fn()} />);+ const swatches = container.querySelectorAll(".tn-color-picker-swatch");+ expect(swatches.length).toBeGreaterThan(1);++ const active = container.querySelectorAll(".tn-color-picker-swatch.active");+ expect(active).toHaveLength(1);+ expect((active[0] as HTMLElement).getAttribute("title")).toBe("#43a047");+ });++ it("uses the provided presets and emits the picked color", () => {+ const onChange = vi.fn();+ const container = renderInto(<ColorPicker currentValue="" presets={[ "#111111", "#222222" ]} onChange={onChange} />);++ const swatches = container.querySelectorAll<HTMLButtonElement>(".tn-color-picker-swatch");+ expect(swatches).toHaveLength(2);++ swatches[1].click();+ expect(onChange).toHaveBeenCalledExactlyOnceWith("#222222");+ });++ it("offers the browser's native color input and emits its value", () => {+ const onChange = vi.fn();+ const container = renderInto(<ColorPicker currentValue="#ff8800" onChange={onChange} />);++ const nativeInput = container.querySelector<HTMLInputElement>(".tn-color-picker-custom input[type=\"color\"]");+ expect(nativeInput).not.toBeNull();+ if (!nativeInput) return;+ // A valid 6-digit hex is round-tripped into the native input's value.+ expect(nativeInput.value).toBe("#ff8800");++ nativeInput.value = "#00ccff";+ nativeInput.dispatchEvent(new Event("input", { bubbles: true }));+ expect(onChange).toHaveBeenLastCalledWith("#00ccff");+ });++ it("clears the value via the clear action", () => {+ const onChange = vi.fn();+ const container = renderInto(<ColorPicker currentValue="#ff8800" onChange={onChange} />);++ container.querySelector<HTMLButtonElement>(".tn-color-picker-clear")?.click();+ expect(onChange).toHaveBeenCalledExactlyOnceWith("");+ });+});diff --git a/apps/client/src/widgets/react/ColorPicker.tsx b/apps/client/src/widgets/react/ColorPicker.tsxnew file mode 100644index 0000000000..ca61a74645--- /dev/null+++ b/apps/client/src/widgets/react/ColorPicker.tsx@@ -0,0 +1,80 @@+import "./ColorPicker.css";++import clsx from "clsx";++import Dropdown from "./Dropdown";+import Icon from "./Icon";++/** Curated default preset palette, using Trilium note-color-friendly CSS colors. */+const DEFAULT_PRESETS = [+ "#e53935", "#fb8c00", "#fdd835", "#43a047", "#00897b",+ "#00acc1", "#1e88e5", "#3949ab", "#8e24aa", "#d81b60",+ "#6d4c41", "#757575", "#000000", "#ffffff"+];++interface ColorPickerProps {+ /** The current CSS color (e.g. `#ff8800`). Empty string means "no color". */+ currentValue: string;+ onChange(newValue: string): void;+ /** Preset swatches shown in the grid. Defaults to a curated palette. */+ presets?: string[];+ /** Tooltip / accessible label for the trigger. */+ title?: string;+ disabled?: boolean;+ className?: string;+}++/**+ * A color picker combining preset swatches with the browser's native color picker.+ *+ * The trigger is a swatch + label; the popover (a themed {@link Dropdown}) shows a grid of preset+ * swatches plus a native `<input type="color">` for arbitrary colors and a clear action. Value is a CSS+ * color string (`onChange("")` clears it). Theme-styled via `ColorPicker.css` / `--main-*` variables.+ */+export default function ColorPicker({ currentValue, onChange, presets = DEFAULT_PRESETS, title, disabled, className }: ColorPickerProps) {+ return (+ <Dropdown+ className={clsx("tn-color-picker", className)}+ noSelectButtonStyle+ hideToggleArrow+ disabled={disabled}+ title={title}+ text={+ <span className="tn-color-picker-trigger">+ <span className="tn-color-picker-trigger-swatch" style={{ background: currentValue || "transparent" }} />+ <span className="tn-color-picker-trigger-label">{currentValue || title || "Choose color"}</span>+ </span>+ }+ >+ <div className="tn-color-picker-grid">+ {presets.map((color) => (+ <button+ key={color}+ type="button"+ title={color}+ className={clsx("tn-color-picker-swatch", { "active": currentValue === color })}+ style={{ background: color }}+ onClick={() => onChange(color)}+ />+ ))}+ </div>++ <label className="tn-color-picker-custom">+ <input+ type="color"+ value={/^#[0-9a-f]{6}$/i.test(currentValue) ? currentValue : "#000000"}+ onInput={(e) => onChange(e.currentTarget.value)}+ />+ <span>Custom…</span>+ </label>++ <button+ type="button"+ className="tn-color-picker-clear tn-low-profile"+ onClick={() => onChange("")}+ >+ <Icon icon="bx bx-x" /> Clear+ </button>+ </Dropdown>+ );+}diff --git a/apps/client/src/widgets/react/FormDatetime.tsx b/apps/client/src/widgets/react/FormDatetime.tsxnew file mode 100644index 0000000000..e3d8a7d3ad--- /dev/null+++ b/apps/client/src/widgets/react/FormDatetime.tsx@@ -0,0 +1,13 @@+import FormTextBox, { type FormTextBoxProps } from "./FormTextBox";++/**+ * A date-time input rendering a native `<input type="datetime-local">`, so the browser's built-in+ * date/time picker is used. (HTML has no bare `type="datetime"`; `datetime-local` is the type browsers+ * render a native picker for.)+ *+ * Thin wrapper around {@link FormTextBox} that locks in `type="datetime-local"` — it inherits the same+ * controlled input handling, `onChange(newValue, validity)` / `onBlur` callbacks and `inputRef`.+ */+export default function FormDatetime(props: Omit<FormTextBoxProps, "type">) {+ return <FormTextBox type="datetime-local" placeholder="not set" {...props} />;+}diff --git a/apps/client/src/widgets/react/FormInputWrappers.spec.tsx b/apps/client/src/widgets/react/FormInputWrappers.spec.tsxnew file mode 100644index 0000000000..4070b16876--- /dev/null+++ b/apps/client/src/widgets/react/FormInputWrappers.spec.tsx@@ -0,0 +1,57 @@+import { describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";+import FormDatetime from "./FormDatetime";+import FormNumber from "./FormNumber";+import FormTime from "./FormTime";++function typeInto(input: HTMLInputElement, value: string) {+ input.value = value;+ input.dispatchEvent(new Event("input", { bubbles: true }));+}++describe("FormNumber / FormTime / FormDatetime wrappers", () => {+ it("render the correct native input type so the browser's picker is used", () => {+ const number = renderInto(<FormNumber currentValue="3" onChange={vi.fn()} />).querySelector("input");+ const time = renderInto(<FormTime currentValue="12:30" onChange={vi.fn()} />).querySelector("input");+ const datetime = renderInto(<FormDatetime currentValue="2026-07-16T12:30" onChange={vi.fn()} />).querySelector("input");++ expect(number?.getAttribute("type")).toBe("number");+ expect(time?.getAttribute("type")).toBe("time");+ expect(datetime?.getAttribute("type")).toBe("datetime-local");+ // Inherit FormTextBox's styling.+ expect(number?.className).toContain("form-control");+ });++ it("pass the current value through and emit changes with a validity state", () => {+ const onChange = vi.fn();+ const input = renderInto(<FormTime currentValue="09:00" onChange={onChange} />).querySelector("input");+ expect(input).not.toBeNull();+ if (!input) return;++ expect(input.value).toBe("09:00");+ typeInto(input, "17:45");+ expect(onChange).toHaveBeenLastCalledWith("17:45", expect.anything());+ });++ it("FormNumber inherits FormTextBox min/max clamping and forwards native attributes", () => {+ const onChange = vi.fn();+ const input = renderInto(<FormNumber currentValue="5" min={1} max={10} step={2} onChange={onChange} />).querySelector("input");+ expect(input).not.toBeNull();+ if (!input) return;++ expect(input.getAttribute("min")).toBe("1");+ expect(input.getAttribute("max")).toBe("10");+ expect(input.getAttribute("step")).toBe("2");++ typeInto(input, "999");+ expect(onChange).toHaveBeenLastCalledWith("10", expect.anything());+ });++ it("default the addon's \"not set\" placeholder for time and datetime", () => {+ const time = renderInto(<FormTime currentValue="" onChange={vi.fn()} />).querySelector("input");+ const datetime = renderInto(<FormDatetime currentValue="" onChange={vi.fn()} />).querySelector("input");+ expect(time?.getAttribute("placeholder")).toBe("not set");+ expect(datetime?.getAttribute("placeholder")).toBe("not set");+ });+});diff --git a/apps/client/src/widgets/react/FormNumber.tsx b/apps/client/src/widgets/react/FormNumber.tsxnew file mode 100644index 0000000000..6c716e721c--- /dev/null+++ b/apps/client/src/widgets/react/FormNumber.tsx@@ -0,0 +1,13 @@+import FormTextBox, { type FormTextBoxProps } from "./FormTextBox";++/**+ * A numeric input rendering a native `<input type="number">`, so the browser's number spinner is used.+ *+ * Thin wrapper around {@link FormTextBox} that locks in `type="number"` — it inherits the same controlled+ * input handling, `min`/`max` clamping, `onChange(newValue, validity)` / `onBlur` callbacks and `inputRef`.+ * `min`, `max` and `step` are forwarded as native attributes. The value is a string, consistent with the+ * other numeric inputs in the codebase (consumers parse it if a `number` is needed).+ */+export default function FormNumber(props: Omit<FormTextBoxProps, "type">) {+ return <FormTextBox type="number" {...props} />;+}diff --git a/apps/client/src/widgets/react/FormTextBox.tsx b/apps/client/src/widgets/react/FormTextBox.tsxindex c8672c515a..a5d5f773c6 100644--- a/apps/client/src/widgets/react/FormTextBox.tsx+++ b/apps/client/src/widgets/react/FormTextBox.tsx@@ -1,6 +1,6 @@import { useEffect, type InputHTMLAttributes, type RefObject } from "preact/compat";-interface FormTextBoxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "onChange" | "onBlur" | "value"> {+export interface FormTextBoxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "onChange" | "onBlur" | "value"> {id?: string;currentValue?: string;onChange?(newValue: string, validity: ValidityState): void;diff --git a/apps/client/src/widgets/react/FormTime.tsx b/apps/client/src/widgets/react/FormTime.tsxnew file mode 100644index 0000000000..d8e83d5c28--- /dev/null+++ b/apps/client/src/widgets/react/FormTime.tsx@@ -0,0 +1,12 @@+import FormTextBox, { type FormTextBoxProps } from "./FormTextBox";++/**+ * A time input rendering a native `<input type="time">`, so the browser's built-in time picker is used.+ *+ * Thin wrapper around {@link FormTextBox} that locks in `type="time"` — it inherits the same controlled+ * input handling, `onChange(newValue, validity)` / `onBlur` callbacks and `inputRef`. The value is a+ * `"HH:mm"` string.+ */+export default function FormTime(props: Omit<FormTextBoxProps, "type">) {+ return <FormTextBox type="time" placeholder="not set" {...props} />;+}diff --git a/apps/client/src/widgets/react/FormToggleButton.spec.tsx b/apps/client/src/widgets/react/FormToggleButton.spec.tsxnew file mode 100644index 0000000000..83820cb5eb--- /dev/null+++ b/apps/client/src/widgets/react/FormToggleButton.spec.tsx@@ -0,0 +1,43 @@+import { describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";+import FormToggleButton from "./FormToggleButton";++describe("FormToggleButton", () => {+ it("uses the theme's btn classes and reflects the on-state via active + aria-pressed", () => {+ const off = renderInto(<FormToggleButton label="Bold" currentValue={false} onChange={vi.fn()} />).querySelector("button");+ const on = renderInto(<FormToggleButton label="Bold" currentValue={true} onChange={vi.fn()} />).querySelector("button");++ expect(off?.className).toContain("btn");+ expect(off?.className).toContain("btn-primary");+ expect(off?.className).not.toContain("active");+ expect(off?.getAttribute("aria-pressed")).toBe("false");++ expect(on?.className).toContain("active");+ expect(on?.getAttribute("aria-pressed")).toBe("true");+ });++ it("toggles the value on click", () => {+ const onChange = vi.fn();+ renderInto(<FormToggleButton label="Bold" currentValue={false} onChange={onChange} />).querySelector("button")?.click();+ expect(onChange).toHaveBeenCalledExactlyOnceWith(true);+ });++ it("does not fire when disabled", () => {+ const onChange = vi.fn();+ renderInto(<FormToggleButton label="Bold" currentValue={false} disabled onChange={onChange} />).querySelector("button")?.click();+ expect(onChange).not.toHaveBeenCalled();+ });++ it("applies the secondary kind and size variants", () => {+ const secondary = renderInto(<FormToggleButton label="A" kind="secondary" size="small" currentValue={false} onChange={vi.fn()} />).querySelector("button");+ expect(secondary?.className).toContain("btn-secondary");+ expect(secondary?.className).not.toContain("btn-primary");+ expect(secondary?.className).toContain("btn-sm");+ });++ it("renders an icon before the label when given", () => {+ const button = renderInto(<FormToggleButton label="A" icon="bx-check" currentValue={false} onChange={vi.fn()} />).querySelector("button");+ expect(button?.querySelector(".bx.bx-check")).not.toBeNull();+ });+});diff --git a/apps/client/src/widgets/react/FormToggleButton.tsx b/apps/client/src/widgets/react/FormToggleButton.tsxnew file mode 100644index 0000000000..48e2c26829--- /dev/null+++ b/apps/client/src/widgets/react/FormToggleButton.tsx@@ -0,0 +1,46 @@+import clsx from "clsx";+import type { ComponentChildren } from "preact";++import Icon from "./Icon";++interface FormToggleButtonProps {+ /** Content shown inside the button. */+ label: string | ComponentChildren;+ /** Optional Boxicons icon name (e.g. `bx-check`) shown before the label. */+ icon?: string;+ currentValue: boolean;+ onChange(newValue: boolean): void;+ /** Button style, mirroring {@link Button}. Defaults to `primary`. */+ kind?: "primary" | "secondary";+ size?: "normal" | "small" | "micro";+ disabled?: boolean;+ title?: string;+ className?: string;+}++/**+ * A checkbox rendered as a pill button (pressed = on), consistent with Trilium's theme.+ *+ * Uses the same `btn`/`btn-primary`/`btn-secondary` + `active` classes as {@link Button} and the existing+ * in-repo toggle buttons (e.g. `ThemeModeSelector`) rather than Bootstrap's `btn-check`, which is not+ * styled in Trilium's theme. Accessibility is conveyed via `aria-pressed`.+ */+export default function FormToggleButton({ label, icon, currentValue, onChange, kind = "primary", size, disabled, title, className }: FormToggleButtonProps) {+ return (+ <button+ type="button"+ className={clsx("btn", kind === "secondary" ? "btn-secondary" : "btn-primary", {+ "active": currentValue,+ "btn-sm": size === "small",+ "btn-micro": size === "micro"+ }, className)}+ aria-pressed={currentValue}+ disabled={disabled}+ title={title}+ onClick={() => onChange(!currentValue)}+ >+ {icon && <Icon icon={`bx ${icon}`} />}+ {label}+ </button>+ );+}diff --git a/apps/client/src/widgets/react/Table.tsx b/apps/client/src/widgets/react/Table.tsxnew file mode 100644index 0000000000..98596d88fe--- /dev/null+++ b/apps/client/src/widgets/react/Table.tsx@@ -0,0 +1,9 @@+/**+ * Public re-export of the generic Tabulator-based table wrapper as a shared Preact widget.+ *+ * The implementation lives at `../collections/table/tabulator` for historical reasons; this module+ * exposes it from the reusable `widgets/react/` component folder so features outside the note+ * collection view can consume it without reaching into `collections/table`. It is decoupled from+ * Trilium's note model — it deals purely in columns, data and events.+ */+export { default, type TableProps } from "../collections/table/tabulator";diff --git a/apps/client/src/widgets/react/collection_reexports.spec.ts b/apps/client/src/widgets/react/collection_reexports.spec.tsnew file mode 100644index 0000000000..248f6ad6f2--- /dev/null+++ b/apps/client/src/widgets/react/collection_reexports.spec.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";++// These modules exist only to re-export the generic collection wrappers from the reusable+// `widgets/react/` folder. Instantiating Tabulator / FullCalendar needs real layout (out of scope for+// happy-dom), so we verify the one thing these files are responsible for: that they forward the exact+// same component (and its props type) as the underlying implementation.+import Calendar from "./Calendar";+import CalendarImpl from "../collections/calendar/calendar";+import Table from "./Table";+import TableImpl from "../collections/table/tabulator";++describe("collection widget re-exports", () => {+ it("Table re-exports the Tabulator wrapper", () => {+ expect(Table).toBe(TableImpl);+ });++ it("Calendar re-exports the FullCalendar wrapper", () => {+ expect(Calendar).toBe(CalendarImpl);+ });+});diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsx b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsxindex 6da0b9a5b4..0c30f8933f 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsx+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsx@@ -3,8 +3,10 @@ import {Admonition, Collapsible,FormCheckbox, FormDropdownList, FormFileUploadButton, FormGroup, FormRadioGroup, FormTextArea,FormTextBox, FormToggle, Slider, RawHtml, LoadingSpinner, Icon,+ FormNumber, FormTime, FormDatetime, FormToggleButton, ColorPicker,Dropdown, FormListItem, FormDropdownDivider, FormDropdownSubmenu,NoteAutocomplete, NoteLink, Modal,+ Table,CKEditor,useEffect, useState} from "trilium:preact";@@ -17,7 +19,7 @@ export default function() {const interval = setInterval(() => setTime(new Date().toLocaleString()), 1000);return () => clearInterval(interval);}, []);-+return (<div style={{ padding: 20, display: "flex", flexDirection: "column", gap: "1em" }}><h1>Widget showcase</h1>@@ -27,7 +29,7 @@ export default function() {<strong>Admonition</strong><br />{lorem}</Admonition>-+<Collapsible title="Collapsible" initiallyExpanded>{lorem}</Collapsible>@@ -36,20 +38,21 @@ export default function() {<NoteElements /><ModalSample /><DropdownSample />- </div>+ <CollectionViews />+ </div>);}function Buttons() {const onClick = () => showMessage("A button was pressed");-+return (<><h2>Buttons</h2><div style={{ display: "flex", gap: "1em", alignItems: "center" }}><ActionButton icon="bx bx-rocket" text="Action button" onClick={onClick} /><Button icon="bx bx-rocket" text="Simple button" onClick={onClick} />- <LinkButton text="Link button" onClick={onClick} />+ <LinkButton text="Link button" onClick={onClick} /></div></>)@@ -60,7 +63,12 @@ function FormElements() {const [ dropdownValue, setDropdownValue ] = useState("key-1");const [ radioGroupValue, setRadioGroupValue ] = useState("key-1");const [ sliderValue, setSliderValue ] = useState(50);-+ const [ numberValue, setNumberValue ] = useState("3");+ const [ timeValue, setTimeValue ] = useState("09:00");+ const [ datetimeValue, setDatetimeValue ] = useState("");+ const [ toggleButtonOn, setToggleButtonOn ] = useState(false);+ const [ color, setColor ] = useState("#43a047");+return (<><h2>Form elements</h2>@@ -91,19 +99,34 @@ function FormElements() {]}currentValue={radioGroupValue} onChange={setRadioGroupValue}/>- </FormGroup>+ </FormGroup><FormGroup name="text-box" label="Text box"><FormTextBoxplaceholder="Type something..."currentValue="" onChange={(newValue) => {}}- />- </FormGroup>+ />+ </FormGroup><FormGroup name="text-area" label="Text area"><FormTextAreaplaceholder="Type something bigger..."currentValue="" onChange={(newValue) => {}}/></FormGroup>+ <FormGroup name="number" label="Number">+ <FormNumber min={0} max={10} step={1} currentValue={numberValue} onChange={setNumberValue} />+ </FormGroup>+ <FormGroup name="time" label="Time">+ <FormTime currentValue={timeValue} onChange={setTimeValue} />+ </FormGroup>+ <FormGroup name="datetime" label="Date & time">+ <FormDatetime currentValue={datetimeValue} onChange={setDatetimeValue} />+ </FormGroup>+ <FormGroup name="toggle-button" label="Toggle button">+ <FormToggleButton label="Bold" icon="bx-bold" currentValue={toggleButtonOn} onChange={setToggleButtonOn} />+ </FormGroup>+ <FormGroup name="color-picker" label="Color picker">+ <ColorPicker currentValue={color} onChange={setColor} />+ </FormGroup><FormGroup name="slider" label="Slider"><Slidermin={1} max={100}@@ -118,8 +141,8 @@ function FormElements() {if (!file) return;showMessage(`Got file "${file.name}" of size ${file.size} B and type ${file.type}.`);}}- />- </FormGroup>+ />+ </FormGroup><FormGroup name="icon" label="Icon"><Icon icon="bx bx-smile" /></FormGroup>@@ -136,7 +159,7 @@ function FormElements() {function NoteElements() {const [ noteId, setNoteId ] = useState("");-+return (<div><h2>Note elements</h2>@@ -158,12 +181,12 @@ function NoteElements() {}function ModalSample() {- const [ shown, setShown ] = useState(false);-+ const [ shown, setShown ] = useState(false);+return (<><h2>Modal</h2>- <Button text="Open modal" onClick={() => setShown(true)} />+ <Button text="Open modal" onClick={() => setShown(true)} /><Modal title="Modal title" size="md" show={shown} onHidden={() => setShown(false)}>Modal goes here.</Modal>@@ -186,4 +209,28 @@ function DropdownSample() {</Dropdown></>)-}\ No newline at end of file+}++function CollectionViews() {+ return (+ <>+ <h2>Collection views</h2>+ <p>+ A generic <code>Table</code> (Tabulator) is available. A <code>Calendar</code>+ {" "}(FullCalendar) component is also exposed, but it requires you to pass a+ {" "}<code>plugins</code> array to render a view, so it is not demonstrated here.+ </p>+ <Table+ layout="fitColumns"+ columns={[+ { title: "Name", field: "name" },+ { title: "Progress", field: "progress" }+ ]}+ data={[+ { id: 1, name: "First task", progress: "80%" },+ { id: 2, name: "Second task", progress: "20%" }+ ]}+ />+ </>+ )+}diff --git a/docs/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsx b/docs/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsxindex 6da0b9a5b4..0c30f8933f 100644--- a/docs/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsx+++ b/docs/User Guide/User Guide/Scripting/Frontend Basics/Preact/Built-in components/Widget showcase.jsx@@ -3,8 +3,10 @@ import {Admonition, Collapsible,FormCheckbox, FormDropdownList, FormFileUploadButton, FormGroup, FormRadioGroup, FormTextArea,FormTextBox, FormToggle, Slider, RawHtml, LoadingSpinner, Icon,+ FormNumber, FormTime, FormDatetime, FormToggleButton, ColorPicker,Dropdown, FormListItem, FormDropdownDivider, FormDropdownSubmenu,NoteAutocomplete, NoteLink, Modal,+ Table,CKEditor,useEffect, useState} from "trilium:preact";@@ -17,7 +19,7 @@ export default function() {const interval = setInterval(() => setTime(new Date().toLocaleString()), 1000);return () => clearInterval(interval);}, []);-+return (<div style={{ padding: 20, display: "flex", flexDirection: "column", gap: "1em" }}><h1>Widget showcase</h1>@@ -27,7 +29,7 @@ export default function() {<strong>Admonition</strong><br />{lorem}</Admonition>-+<Collapsible title="Collapsible" initiallyExpanded>{lorem}</Collapsible>@@ -36,20 +38,21 @@ export default function() {<NoteElements /><ModalSample /><DropdownSample />- </div>+ <CollectionViews />+ </div>);}function Buttons() {const onClick = () => showMessage("A button was pressed");-+return (<><h2>Buttons</h2><div style={{ display: "flex", gap: "1em", alignItems: "center" }}><ActionButton icon="bx bx-rocket" text="Action button" onClick={onClick} /><Button icon="bx bx-rocket" text="Simple button" onClick={onClick} />- <LinkButton text="Link button" onClick={onClick} />+ <LinkButton text="Link button" onClick={onClick} /></div></>)@@ -60,7 +63,12 @@ function FormElements() {const [ dropdownValue, setDropdownValue ] = useState("key-1");const [ radioGroupValue, setRadioGroupValue ] = useState("key-1");const [ sliderValue, setSliderValue ] = useState(50);-+ const [ numberValue, setNumberValue ] = useState("3");+ const [ timeValue, setTimeValue ] = useState("09:00");+ const [ datetimeValue, setDatetimeValue ] = useState("");+ const [ toggleButtonOn, setToggleButtonOn ] = useState(false);+ const [ color, setColor ] = useState("#43a047");+return (<><h2>Form elements</h2>@@ -91,19 +99,34 @@ function FormElements() {]}currentValue={radioGroupValue} onChange={setRadioGroupValue}/>- </FormGroup>+ </FormGroup><FormGroup name="text-box" label="Text box"><FormTextBoxplaceholder="Type something..."currentValue="" onChange={(newValue) => {}}- />- </FormGroup>+ />+ </FormGroup><FormGroup name="text-area" label="Text area"><FormTextAreaplaceholder="Type something bigger..."currentValue="" onChange={(newValue) => {}}/></FormGroup>+ <FormGroup name="number" label="Number">+ <FormNumber min={0} max={10} step={1} currentValue={numberValue} onChange={setNumberValue} />+ </FormGroup>+ <FormGroup name="time" label="Time">+ <FormTime currentValue={timeValue} onChange={setTimeValue} />+ </FormGroup>+ <FormGroup name="datetime" label="Date & time">+ <FormDatetime currentValue={datetimeValue} onChange={setDatetimeValue} />+ </FormGroup>+ <FormGroup name="toggle-button" label="Toggle button">+ <FormToggleButton label="Bold" icon="bx-bold" currentValue={toggleButtonOn} onChange={setToggleButtonOn} />+ </FormGroup>+ <FormGroup name="color-picker" label="Color picker">+ <ColorPicker currentValue={color} onChange={setColor} />+ </FormGroup><FormGroup name="slider" label="Slider"><Slidermin={1} max={100}@@ -118,8 +141,8 @@ function FormElements() {if (!file) return;showMessage(`Got file "${file.name}" of size ${file.size} B and type ${file.type}.`);}}- />- </FormGroup>+ />+ </FormGroup><FormGroup name="icon" label="Icon"><Icon icon="bx bx-smile" /></FormGroup>@@ -136,7 +159,7 @@ function FormElements() {function NoteElements() {const [ noteId, setNoteId ] = useState("");-+return (<div><h2>Note elements</h2>@@ -158,12 +181,12 @@ function NoteElements() {}function ModalSample() {- const [ shown, setShown ] = useState(false);-+ const [ shown, setShown ] = useState(false);+return (<><h2>Modal</h2>- <Button text="Open modal" onClick={() => setShown(true)} />+ <Button text="Open modal" onClick={() => setShown(true)} /><Modal title="Modal title" size="md" show={shown} onHidden={() => setShown(false)}>Modal goes here.</Modal>@@ -186,4 +209,28 @@ function DropdownSample() {</Dropdown></>)-}\ No newline at end of file+}++function CollectionViews() {+ return (+ <>+ <h2>Collection views</h2>+ <p>+ A generic <code>Table</code> (Tabulator) is available. A <code>Calendar</code>+ {" "}(FullCalendar) component is also exposed, but it requires you to pass a+ {" "}<code>plugins</code> array to render a view, so it is not demonstrated here.+ </p>+ <Table+ layout="fitColumns"+ columns={[+ { title: "Name", field: "name" },+ { title: "Progress", field: "progress" }+ ]}+ data={[+ { id: 1, name: "First task", progress: "80%" },+ { id: 2, name: "Second task", progress: "20%" }+ ]}+ />+ </>+ )+}diff --git a/packages/commons/src/lib/script_api_preact.ts b/packages/commons/src/lib/script_api_preact.tsindex 99e305b97e..657d4e01d2 100644--- a/packages/commons/src/lib/script_api_preact.ts+++ b/packages/commons/src/lib/script_api_preact.ts@@ -76,6 +76,16 @@ interface ButtonProps {}export declare const Button: FunctionComponent<ButtonProps>;+/**+ * Generic FullCalendar wrapper. The full FullCalendar `CalendarOptions` surface is loosened here+ * (any option may be passed through); `calendarRef` receives the underlying calendar instance.+ */+interface CalendarProps {+ calendarRef?: RefObject<unknown>;+ [option: string]: unknown;+}+export declare const Calendar: FunctionComponent<CalendarProps>;+interface CKEditorApi {focus(): void;setText(text: string): void;@@ -105,6 +115,25 @@ interface CollapsibleProps {}export declare const Collapsible: FunctionComponent<CollapsibleProps>;+interface ExternallyControlledCollapsibleProps {+ title: string;+ children?: ComponentChildren;+ className?: string;+ expanded: boolean | undefined;+ setExpanded(expanded: boolean): void;+}+export declare const ExternallyControlledCollapsible: FunctionComponent<ExternallyControlledCollapsibleProps>;++interface ColorPickerProps {+ currentValue: string;+ onChange(newValue: string): void;+ presets?: string[];+ title?: string;+ disabled?: boolean;+ className?: string;+}+export declare const ColorPicker: FunctionComponent<ColorPickerProps>;+interface DropdownProps {id?: string;className?: string;@@ -144,6 +173,8 @@ interface FormCheckboxProps {}export declare const FormCheckbox: FunctionComponent<FormCheckboxProps>;+export declare const FormDatetime: FunctionComponent<Omit<FormTextBoxProps, "type">>;+interface FormDropdownListProps<T> extends Omit<DropdownProps, "children"> {values: T[];keyProperty: keyof T;@@ -205,6 +236,8 @@ interface FormDropdownSubmenuProps {}export declare const FormDropdownSubmenu: FunctionComponent<FormDropdownSubmenuProps>;+export declare const FormNumber: FunctionComponent<Omit<FormTextBoxProps, "type">>;+interface FormRadioGroupProps {name: string;currentValue?: string;@@ -245,6 +278,8 @@ interface FormTextBoxProps {}export declare const FormTextBox: FunctionComponent<FormTextBoxProps>;+export declare const FormTime: FunctionComponent<Omit<FormTextBoxProps, "type">>;+interface FormToggleProps {currentValue: boolean | null;onChange(newValue: boolean): void;@@ -259,6 +294,19 @@ interface FormToggleProps {}export declare const FormToggle: FunctionComponent<FormToggleProps>;+interface FormToggleButtonProps {+ label: ComponentChildren;+ icon?: string;+ currentValue: boolean;+ onChange(newValue: boolean): void;+ kind?: "primary" | "secondary";+ size?: "normal" | "small" | "micro";+ disabled?: boolean;+ title?: string;+ className?: string;+}+export declare const FormToggleButton: FunctionComponent<FormToggleButtonProps>;+interface IconProps {icon?: string;className?: string;@@ -362,6 +410,25 @@ interface SliderProps {}export declare const Slider: FunctionComponent<SliderProps>;+/**+ * Generic Tabulator-based data grid. The full Tabulator `Options` surface is loosened here (any option+ * may be passed through); `data` is the row array, `columns` the column definitions, `modules` the+ * Tabulator modules to register, `events` the event handlers and `tabulatorRef` receives the instance.+ */+interface TableProps {+ tabulatorRef?: RefObject<unknown>;+ className?: string;+ data?: unknown[];+ columns?: unknown[];+ modules?: unknown[];+ events?: Record<string, unknown>;+ index?: string;+ footerElement?: unknown;+ onReady?: () => void;+ [option: string]: unknown;+}+export declare const Table: FunctionComponent<TableProps>;+interface RightPanelWidgetProps {id: string;title: string;