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
import "./Card.css";
import { cloneElement, ComponentChildren, createContext, isValidElement } from "preact";
import { JSX, HTMLAttributes, type RefObject } from "preact";
import { useCallback, useContext, useLayoutEffect, useRef, useState } from "preact/hooks";
import clsx from "clsx";
import type { MenuItem } from "../../menus/context_menu";
import Button from "./Button";
import {
type FilterRole, FilterPassthrough, filterRoleClass, useFilterMatch, useIsFiltering
} from "./filter";
import { useUniqueName } from "./hooks";
import Icon from "./Icon";
// #region Card Frame
export interface CardFrameProps extends HTMLAttributes<HTMLDivElement> {
className?: string;
highlightOnHover?: boolean;
children: ComponentChildren;
}
export function CardFrame({className, highlightOnHover, children, ...rest}: CardFrameProps) {
return <div {...rest}
className={clsx("tn-card-frame", className, {
"tn-card-highlight-on-hover": highlightOnHover
})}>
{children}
</div>;
}
// #endregion
// #region Card
export interface CardProps {
className?: string;
heading?: string;
/** Sentence introducing the card, shown between the heading and the first section. */
description?: ComponentChildren;
/**
* Controls for the card as a whole, kept at the far end of its heading — a help mark, or a
* button that adds to what the card holds.
*
* Taken as children rather than named one by one, so that the card needs no import of its own
* for them: `Card` is in the login and setup bundles, which have no business pulling in the app
* a help mark would reach for.
*/
actions?: ComponentChildren;
/**
* Words the card is found by that are not written on it, for a card with no name of its own or
* one whose name says less than what it holds. Reuse a sentence the page already has rather
* than inventing words for it: every word in it becomes one the card can be found by.
*/
filterExtraKeywords?: string;
/**
* Shows the card only while a filter is running, for content that is there to be found rather
* than read: a page's own actions, which a search cannot otherwise reach, named and pointing at
* the page they are carried out on.
*/
filterOnly?: boolean;
}
/**
* A titled group of sections.
*
* Under a `FilterProvider`, a card matching by its heading or description shows everything it
* holds, since asking for the group is asking for its contents. One that does not match keeps only
* the sections that matched on their own, and disappears when none did (both through CSS, so
* nothing is torn down and rebuilt as the query changes).
*/
export function Card(props: {children: ComponentChildren} & CardProps) {
const matched = useFilterMatch(props.heading, props.description, props.filterExtraKeywords);
const filtering = useIsFiltering();
if (props.filterOnly && !filtering) return null;
return <div className={clsx("tn-card", props.className,
filterRoleClass(filtering && (matched ? "match" : "scope")))}>
{(props.heading || props.actions) && <h5 class="tn-card-heading">
{props.heading}
{props.actions && <span className="tn-card-heading-actions">{props.actions}</span>}
</h5>}
{props.description && <div className="tn-card-description">{props.description}</div>}
<div className="tn-card-body">
<FilterPassthrough when={matched}>{props.children}</FilterPassthrough>
</div>
</div>;
}
// #endregion
// #region Card Section
export interface CardSectionProps {
className?: string;
subSections?: JSX.Element | JSX.Element[];
subSectionsVisible?: boolean;
highlightOnHover?: boolean;
/** Called when the section is pressed. Handed the event, which a link's handler may need. */
onAction?: (event: MouseEvent) => void;
noPadding?: boolean;
/**
* Makes the section a segment that leads somewhere rather than one holding a control: it becomes
* an `<a>` carrying this address, highlights on hover, and reads a chevron on its trailing edge.
*
* A card of these is a card of anchors — do not mix them with ordinary segments, whose rounded
* first and last corners are matched by element type.
*/
href?: string;
/**
* Opts the link out of the options dialog's contained navigation, which would otherwise swallow
* the click before {@link CardSectionProps.onAction} ever saw it. Ignored without an `href`.
*/
noContainedNavigation?: boolean;
/**
* What this section is worth to a filter over the card, for a section that is not a setting.
* `companion` is the usual one: a preview of what the settings around it do, shown for as long
* as any of them is (see {@link FilterRole}).
*/
filterRole?: FilterRole;
/** Hands back the element the section is drawn as, for a caller that reads what it holds. */
elementRef?: (element: HTMLElement | null) => void;
}
interface CardSectionContextType {
nestingLevel: number;
}
const CardSectionContext = createContext<CardSectionContextType | undefined>(undefined);
export function CardSection(props: {children: ComponentChildren} & CardSectionProps) {
const parentContext = useContext(CardSectionContext);
const nestingLevel = (parentContext && parentContext.nestingLevel + 1) ?? 0;
const className = clsx("tn-card-section", props.className, filterRoleClass(props.filterRole), {
"tn-card-section-nested": nestingLevel > 0,
"tn-card-highlight-on-hover": props.highlightOnHover || props.onAction || props.href,
"tn-no-padding": props.noPadding
});
const style = {"--tn-card-section-nesting-level": (nestingLevel) ? nestingLevel : null};
return <>
{props.href
? <a className={clsx(className, "tn-card-section-link", "no-tooltip-preview")}
ref={props.elementRef}
style={style}
href={props.href}
data-no-contained-navigation={props.noContainedNavigation ? "" : undefined}
onClick={props.onAction}>
{props.children}
<span className="tn-card-section-chevron" />
</a>
: <section className={className}
ref={props.elementRef}
style={style}
onClick={props.onAction}>
{props.children}
</section>}
{props.subSectionsVisible && props.subSections &&
<CardSectionContext.Provider value={{nestingLevel}}>
{props.subSections}
</CardSectionContext.Provider>
}
</>;
}
// #endregion
// #region Option Card Section
export interface OptionCardSectionProps extends CardSectionProps {
label: ComponentChildren;
description?: ComponentChildren;
/** A validation message shown after the control, styled by `.form-field-error`. */
error?: ComponentChildren;
/**
* Binds the label to the control, so that clicking the text operates it. Only a single element
* child can be bound, which covers the usual case of one toggle or one input per option.
*/
name?: string;
/**
* Puts the control on the line below the label rather than beside it, for one that needs the
* whole width — a URL, a path, anything read as well as typed.
*/
stacked?: boolean;
/**
* Keeps the control beside the label on a narrow card too, for a control known to fit there,
* such as a segmented choice between two short words. The opposite of {@link stacked}.
*/
inline?: boolean;
/** The controls the option is operated with, placed on the trailing edge. */
children?: ComponentChildren;
/**
* Words the setting is found by that are not written on it.
* See {@link CardProps.filterExtraKeywords}.
*/
filterExtraKeywords?: string;
}
/**
* A card section built as one setting: what it is on the leading edge, what changes it on the
* trailing one, with the sentence explaining it below the label.
*
* Under a `FilterProvider`, the setting shows itself only while its label or description matches
* what is being looked for. A setting that matched brings its sub-sections with it, since they are
* details of it rather than settings of their own; one that did not stays only for as long as a
* sub-section of its own matched, so that the detail found is read under the setting it belongs to.
* That last part is settled in CSS, from whether any sub-section is still there.
*/
export function OptionCardSection(props: OptionCardSectionProps) {
const {
label, description, error, name, stacked, inline, children, className, subSections,
filterExtraKeywords, ...rest
} = props;
const matched = useFilterMatch(label, description, filterExtraKeywords);
const filtering = useIsFiltering();
const id = useUniqueName(name);
const bound = !!name && isValidElement(children);
const row = useRef<HTMLElement | null>(null);
const keepRow = useCallback((element: HTMLElement | null) => { row.current = element; }, []);
const [ wide, setWide ] = useState(false);
// Whether the control is one of the wide ones, which stack under the label on a narrow card.
// Read off the row rather than matched by a `:has()` rule: Chrome restyles the whole document
// on every structural change anywhere in it for as long as such a rule is loaded.
useLayoutEffect(() => {
const element = row.current;
setWide(!!element && !holdsSmallControl(element));
});
if (!matched && !subSections) return null;
return <CardSection elementRef={keepRow}
className={clsx("tn-card-option", className, {
"tn-card-option-stacked": stacked,
"tn-card-option-wide": wide && !inline
})}
// Kept for its details rather than itself, which is what a companion is.
filterRole={filtering ? (matched ? "match" : "companion") : undefined}
subSections={subSections && (
<FilterPassthrough when={matched}>{subSections}</FilterPassthrough>
)}
{...rest}>
<label className="tn-card-option-label" for={bound ? id : undefined}>
{/* Held together as one thing, because the label stacks the sentence under the name and
would otherwise stack whatever the name is made of too — a badge marking which
platforms a setting applies to belongs after the words, not under them. */}
<span className="tn-card-option-title">{label}</span>
{description && <small className="tn-card-option-description">{description}</small>}
</label>
{bound ? cloneElement(children, { id }) : children}
{error && <small className="form-field-error" role="alert">{error}</small>}
</CardSection>;
}
/**
* Controls small enough to stay beside their label on a narrow card.
*
* A switch moved below its label would cost a whole row and break the line the labels are read
* down. A bare figure is small enough to stay; one carrying a unit beside it is not. A chevron is
* no control at all but the mark of a row that leads somewhere, and keeps its place at every width.
*/
const SMALL_CONTROLS = ".switch-widget, .icon-action, .tn-card-option-actions, select, .dropdown,"
+ " .tn-card-section-chevron, input[type=\"number\"]";
function holdsSmallControl(element: HTMLElement) {
for (const child of element.children) {
if (child.matches(SMALL_CONTROLS)) {
return true;
}
}
return false;
}
// #endregion
// #region Choice Card Section
export interface ChoiceCardSectionProps {
isChecked: boolean;
onCheck: () => void;
/** An icon class, `bx` prefix included, shown before the label. */
icon?: string;
className?: string;
children: ComponentChildren;
/** The choices nested under this one, as more `ChoiceCardSection`s. */
subSections?: JSX.Element[];
/** Whether `subSections` are shown. Defaults to `true`. */
isExpanded?: boolean;
/**
* Adds an expander before the icon, which calls this with the new `isExpanded`. Pass it to
* every choice of a tree: a choice without `subSections` keeps the space of its hidden
* expander, so the labels line up.
*/
onExpandedChange?: (isExpanded: boolean) => void;
}
/**
* One segment of a card that lists exclusive choices. A click, Enter or Space checks it, and the
* checked segment shows a check mark.
*/
export function ChoiceCardSection({
isChecked, onCheck, icon, className, children, subSections, isExpanded = true,
onExpandedChange
}: ChoiceCardSectionProps) {
const parentContext = useContext(CardSectionContext);
const nestingLevel = parentContext ? parentContext.nestingLevel + 1 : 0;
const style = { "--tn-card-section-nesting-level": nestingLevel || null };
const isExpandable = !!subSections?.length;
return <>
<section
className={clsx(
"tn-card-section tn-card-highlight-on-hover tn-card-choice", className,
{ "tn-card-section-nested": nestingLevel > 0 }
)}
style={style}
role="radio"
aria-checked={isChecked}
aria-expanded={onExpandedChange && isExpandable ? isExpanded : undefined}
tabIndex={0}
onClick={onCheck}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
onCheck();
return;
}
// As in a tree, the arrow that the expander points to expands the choice.
const isArrow = event.key === "ArrowRight" || event.key === "ArrowLeft";
const shouldExpand = (event.key === "ArrowRight") !== !!glob.isRtl;
if (onExpandedChange && isExpandable && isArrow && shouldExpand !== isExpanded) {
event.preventDefault();
onExpandedChange(shouldExpand);
}
}}
>
{onExpandedChange && (
<Icon
icon={isExpanded ? "bx bx-chevron-down" : "bx bx-chevron-right"}
className={clsx("tn-card-choice-expander", {
"tn-card-choice-expander-empty": !isExpandable
})}
onClick={isExpandable ? (event) => {
// Expanding does not check the choice.
event.stopPropagation();
onExpandedChange(!isExpanded);
} : undefined}
/>
)}
{icon && <Icon icon={icon} className="tn-card-choice-icon" />}
<span className="tn-card-choice-label">{children}</span>
{isChecked && <Icon icon="bx bx-check" className="tn-card-choice-check" />}
</section>
{isExpandable && isExpanded && (
<CardSectionContext.Provider value={{ nestingLevel }}>
{subSections}
</CardSectionContext.Provider>
)}
</>;
}
// #endregion
// #region Item Creation Row
interface ItemCreationRowButtonBase {
label: string;
/** An icon class, `bx` prefix included. */
icon?: string;
/** Turns the button off, for a caller that cannot make an entry yet. */
disabled?: boolean;
/** The button's `name` attribute, which tests find it by. */
name?: string;
}
/**
* One button of an {@link ItemCreationRow}: one that creates the entry on a press, or one that
* opens a context menu of the entries it can create.
*/
export type ItemCreationRowButton = ItemCreationRowButtonBase & (
| { onClick: (event: MouseEvent) => void; menu?: undefined }
| { menu: MenuItem<string>[]; onClick?: undefined }
);
interface ItemCreationRowProps {
buttons: ItemCreationRowButton[];
elementRef?: RefObject<HTMLElement | null>;
onKeyDown?: (event: KeyboardEvent) => void;
}
/**
* The buttons that create an entry, as the last section of a card. Each is painted as a segment of
* the card rather than as a button, so the row reads as the foot of the list above it.
*/
export function ItemCreationRow({ buttons, elementRef, onKeyDown }: ItemCreationRowProps) {
// The position of the button whose menu is open.
const [ openMenuIndex, setOpenMenuIndex ] = useState<number>();
return (
// Transparent: each button paints itself, and the gaps show the card through.
<section ref={elementRef} className="tn-card-section tn-card-adders" onKeyDown={onKeyDown}>
{buttons.map((button, index) => {
const { menu } = button;
return (
<Button
// The position in the row: two buttons can share a label.
key={index}
name={button.name}
// Not a command button: the theme gives those a background, a shadow and a
// minimum width, none of which suit a segment.
kind="lowProfile"
className="tn-card-adder"
text={<>
{button.icon && <Icon icon={button.icon} />}
<span>{button.label}</span>
</>}
disabled={button.disabled}
aria-haspopup={menu ? "menu" : undefined}
aria-expanded={menu ? openMenuIndex === index : undefined}
onClick={menu
? (event) => void openItemCreationMenu(event.currentTarget, menu, {
onShow: () => setOpenMenuIndex(index),
onHide: () => setOpenMenuIndex(undefined)
})
: button.onClick}
/>
);
})}
</section>
);
}
/**
* Opens `items` as a context menu centered below `button`, or above it where there is no room
* below. The press that put the menu away opens nothing.
*/
async function openItemCreationMenu(
button: HTMLButtonElement,
items: MenuItem<string>[],
{ onShow, onHide }: { onShow: () => void; onHide: () => void }
) {
// Loaded on demand: the login and setup pages show cards but no menus.
const { default: contextMenu } = await import("../../menus/context_menu");
if (contextMenu.dismissedByLastPress) return;
await contextMenu.show({
anchor: button, centered: true, items, selectMenuItemHandler: () => {}, onShow, onHide
});
}
// #endregion