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 { AttributeType } from "@triliumnext/commons";
import clsx from "clsx";
import { ComponentChildren, RefObject, VNode } from "preact";
import { useCallback, useEffect, useMemo, useRef } from "preact/hooks";
import appContext from "../../components/app_context";
import FNote from "../../entities/fnote";
import attributes, { removeOwnedAttributesByNameOrType } from "../../services/attributes";
import { t } from "../../services/i18n";
import server from "../../services/server";
import SpacedUpdate from "../../services/spaced_update";
import { openInAppHelpFromUrl } from "../../services/utils";
import { ExtendedAdmonition } from "../react/Admonition";
import { CardSection } from "../react/Card";
import FormSelect from "../react/FormSelect";
import FormTextBox from "../react/FormTextBox";
import HelpRemoveButtons from "../react/HelpRemoveButtons";
import { useNoteLabel, useNoteRelation, useTooltip } from "../react/hooks";
import Icon from "../react/Icon";
import NoteAutocomplete from "../react/NoteAutocomplete";
import SearchStringEditor from "./SearchStringEditor";
export interface SearchOption {
attributeName: string;
attributeType: "label" | "relation";
icon: string;
label: string;
tooltip?: string;
component: (props: SearchOptionProps) => VNode;
defaultValue?: string;
additionalAttributesToDelete?: { type: "label" | "relation", name: string }[];
}
interface SearchOptionProps {
note: FNote;
refreshResults: () => void;
/** Set by an option that saves its value with a delay, to a function that saves it at once. */
flushRef: RefObject<(() => Promise<void>) | null>;
attributeName: string;
attributeType: "label" | "relation";
additionalAttributesToDelete?: { type: "label" | "relation", name: string }[];
defaultValue?: string;
error?: { message: string };
}
export const SEARCH_OPTIONS: SearchOption[] = [
{
attributeName: "searchString",
attributeType: "label",
icon: "bx bx-text",
label: t("search_string.title_column"),
component: SearchStringOption
},
{
attributeName: "searchScript",
attributeType: "relation",
defaultValue: "root",
icon: "bx bx-code",
label: t("search_script.title"),
component: SearchScriptOption
},
{
attributeName: "ancestor",
attributeType: "relation",
defaultValue: "root",
icon: "bx bx-filter-alt",
label: t("ancestor.label"),
component: AncestorOption,
additionalAttributesToDelete: [ { type: "label", name: "ancestorDepth" } ]
},
{
attributeName: "fastSearch",
attributeType: "label",
icon: "bx bx-run",
label: t("fast_search.fast_search"),
tooltip: t("fast_search.description"),
component: FastSearchOption
},
{
attributeName: "includeArchivedNotes",
attributeType: "label",
icon: "bx bx-archive",
label: t("include_archived_notes.include_archived_notes"),
tooltip: t("search_definition.include_archived_notes_description"),
component: IncludeArchivedNotesOption
},
{
attributeName: "orderBy",
attributeType: "label",
defaultValue: "relevancy",
icon: "bx bx-arrow-from-top",
label: t("order_by.order_by"),
component: OrderByOption,
additionalAttributesToDelete: [ { type: "label", name: "orderDirection" } ]
},
{
attributeName: "limit",
attributeType: "label",
defaultValue: "10",
icon: "bx bx-stop",
label: t("limit.limit"),
tooltip: t("search_definition.limit_description"),
component: LimitOption
},
{
attributeName: "debug",
attributeType: "label",
icon: "bx bx-bug",
label: t("debug.debug"),
tooltip: t("debug.debug_info"),
component: DebugOption
}
];
function SearchOption({ note, className, title, titleIcon, children, description, help, attributeName, attributeType, additionalAttributesToDelete }: {
note: FNote;
className?: string;
title: string,
titleIcon?: string,
children?: ComponentChildren,
/** Shown in place of `children` for an option that configures nothing. */
description?: ComponentChildren,
help?: ComponentChildren,
attributeName: string,
attributeType: AttributeType,
additionalAttributesToDelete?: { type: "label" | "relation", name: string }[]
}) {
return (
<CardSection className={clsx("search-option", attributeName, className)}>
<span className="search-option-label">
{titleIcon && <Icon icon={titleIcon} />}
{title}
</span>
<div className="search-option-fields">
{description && <span className="search-option-description">{description}</span>}
{children}
</div>
<HelpRemoveButtons
className="search-option-actions"
help={help}
removeText={t("abstract_search_option.remove_this_search_option")}
onRemove={() => {
removeOwnedAttributesByNameOrType(note, attributeType, attributeName);
if (additionalAttributesToDelete) {
for (const { type, name } of additionalAttributesToDelete) {
removeOwnedAttributesByNameOrType(note, type, name);
}
}
}}
/>
</CardSection>
);
}
function SearchStringOption({ note, refreshResults, flushRef, error, ...restProps }: SearchOptionProps) {
const [ searchString ] = useNoteLabel(note, "searchString");
const currentValue = useRef(searchString ?? "");
const prepare = useCallback(() => currentValue.current, []);
const commit = useCallback(async (text: string) => {
appContext.lastSearchString = text;
// Awaited, so a search run after the flush reads the saved label.
await attributes.setLabel(note.noteId, "searchString", text);
if (note.title.startsWith(t("search_string.search_prefix"))) {
await server.put(`notes/${note.noteId}/title`, {
title: `${t("search_string.search_prefix")} ${text.length < 30 ? text : `${text.substr(0, 30)}…`}`
});
}
}, [ note ]);
const spacedUpdateRef = useRef<SpacedUpdate<string> | undefined>(undefined);
if (!spacedUpdateRef.current) {
spacedUpdateRef.current = new SpacedUpdate<string>({ key: note.noteId, prepare, commit }, 1000);
}
const spacedUpdate = spacedUpdateRef.current;
// `SearchDefinition` stays mounted across note switches, so rebind on every render: `rebind`
// snapshots a still-pending change against the previous note rather than the new one (#9614).
useEffect(() => {
spacedUpdate.rebind(note.noteId, prepare, commit);
});
// Runs after the rebind above, so the previous note's text has already been snapshotted.
useEffect(() => {
currentValue.current = searchString ?? "";
// A `searchString` that changed on its own is the save echoing back, and must not drop
// what is being typed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ note ]);
useEffect(() => {
flushRef.current = () => spacedUpdate.updateNowIfNecessary();
return () => {
flushRef.current = null;
};
}, [ flushRef, spacedUpdate ]);
return <>
<SearchOption
titleIcon="bx bx-text"
title={t("search_string.title_column")}
className={clsx({ "has-error": !!error })}
help={<>
<strong>{t("search_string.search_syntax")}</strong> - {t("search_string.also_see")} <a href="#" onClick={(e) => {
e.preventDefault();
openInAppHelpFromUrl("eIg8jdvaoNNd");
}}>{t("search_string.complete_help")}</a>
<ul style="marigin-bottom: 0;">
<li>{t("search_string.full_text_search")}</li>
<li><code>#abc</code> - {t("search_string.label_abc")}</li>
<li><code>#year = 2019</code> - {t("search_string.label_year")}</li>
<li><code>#rock #pop</code> - {t("search_string.label_rock_pop")}</li>
<li><code>#rock or #pop</code> - {t("search_string.label_rock_or_pop")}</li>
<li><code>#year <= 2000</code> - {t("search_string.label_year_comparison")}</li>
<li><code>note.dateCreated >= MONTH-1</code> - {t("search_string.label_date_created")}</li>
</ul>
</>}
note={note} {...restProps}
>
<SearchStringEditor
className="search-string"
autoFocus
placeholder={t("search_string.placeholder")}
noteId={note.noteId}
currentValue={searchString ?? ""}
onChange={text => {
currentValue.current = text;
spacedUpdate.scheduleUpdate();
}}
onEnter={refreshResults}
/>
</SearchOption>
{error?.message && (
<CardSection className="search-definition-error">
<ExtendedAdmonition
type="caution"
icon="bx bx-error-circle"
title={t("search_string.error_title")}
>
{error.message}
</ExtendedAdmonition>
</CardSection>
)}
</>;
}
function SearchScriptOption({ note, ...restProps }: SearchOptionProps) {
const [ searchScript, setSearchScript ] = useNoteRelation(note, "searchScript");
return <SearchOption
titleIcon="bx bx-code"
title={t("search_script.title")}
help={<>
<p>{t("search_script.description1")}</p>
<p>{t("search_script.description2")}</p>
<p>{t("search_script.example_title")}</p>
<pre>{t("search_script.example_code")}</pre>
{t("search_script.note")}
</>}
note={note} {...restProps}
>
<NoteAutocomplete
noteId={searchScript !== "root" ? searchScript ?? undefined : undefined}
noteIdChanged={noteId => setSearchScript(noteId ?? "root")}
placeholder={t("search_script.placeholder")}
/>
</SearchOption>;
}
function AncestorOption({ note, ...restProps}: SearchOptionProps) {
const [ ancestor, setAncestor ] = useNoteRelation(note, "ancestor");
const [ depth, setDepth ] = useNoteLabel(note, "ancestorDepth");
const options = useMemo(() => {
const options: { value: string | undefined; label: string }[] = [
{ value: "", label: t("ancestor.depth_doesnt_matter") },
{ value: "eq1", label: t("ancestor.direct_children") }
];
for (let i=2; i<=9; i++) options.push({ value: `eq${ i}`, label: t("ancestor.depth_eq", { count: i }) });
for (let i=0; i<=9; i++) options.push({ value: `gt${ i}`, label: t("ancestor.depth_gt", { count: i }) });
for (let i=2; i<=9; i++) options.push({ value: `lt${ i}`, label: t("ancestor.depth_lt", { count: i }) });
return options;
}, []);
return <SearchOption
titleIcon="bx bx-filter-alt"
title={t("ancestor.label")}
note={note} {...restProps}
>
<NoteAutocomplete
noteId={ancestor !== "root" ? ancestor ?? undefined : undefined}
noteIdChanged={noteId => setAncestor(noteId ?? "root")}
placeholder={t("ancestor.placeholder")}
/>
<span className="search-option-field-label">{t("ancestor.depth_label")}</span>
<FormSelect
className="w-auto"
values={options}
keyProperty="value" titleProperty="label"
currentValue={depth ?? ""} onChange={(value) => setDepth(value ? value : null)}
/>
</SearchOption>;
}
function FastSearchOption({ ...restProps }: SearchOptionProps) {
return <SearchOption
titleIcon="bx bx-run" title={t("fast_search.fast_search")}
description={t("fast_search.description")}
{...restProps}
/>;
}
function DebugOption({ ...restProps }: SearchOptionProps) {
return <SearchOption
titleIcon="bx bx-bug" title={t("debug.debug")}
description={<>{t("debug.debug_info")} {t("debug.access_info")}</>}
{...restProps}
/>;
}
function IncludeArchivedNotesOption({ ...restProps }: SearchOptionProps) {
return <SearchOption
titleIcon="bx bx-archive" title={t("include_archived_notes.include_archived_notes")}
{...restProps}
/>;
}
function OrderByOption({ note, ...restProps }: SearchOptionProps) {
const [ orderBy, setOrderBy ] = useNoteLabel(note, "orderBy");
const [ orderDirection, setOrderDirection ] = useNoteLabel(note, "orderDirection");
return <SearchOption
titleIcon="bx bx-arrow-from-top"
title={t("order_by.order_by")}
note={note} {...restProps}
>
<FormSelect
className="w-auto d-inline"
currentValue={orderBy ?? "relevancy"} onChange={setOrderBy}
keyProperty="value" titleProperty="title"
values={[
{ value: "relevancy", title: t("order_by.relevancy") },
{ value: "title", title: t("order_by.title") },
{ value: "dateCreated", title: t("order_by.date_created") },
{ value: "dateModified", title: t("order_by.date_modified") },
{ value: "contentSize", title: t("order_by.content_size") },
{ value: "contentAndAttachmentsSize", title: t("order_by.content_and_attachments_size") },
{ value: "contentAndAttachmentsAndRevisionsSize", title: t("order_by.content_and_attachments_and_revisions_size") },
{ value: "revisionCount", title: t("order_by.revision_count") },
{ value: "childrenCount", title: t("order_by.children_count") },
{ value: "parentCount", title: t("order_by.parent_count") },
{ value: "ownedLabelCount", title: t("order_by.owned_label_count") },
{ value: "ownedRelationCount", title: t("order_by.owned_relation_count") },
{ value: "targetRelationCount", title: t("order_by.target_relation_count") },
{ value: "random", title: t("order_by.random") }
]}
/>
{" "}
<FormSelect
className="w-auto d-inline"
currentValue={orderDirection ?? "asc"} onChange={setOrderDirection}
keyProperty="value" titleProperty="title"
values={[
{ value: "asc", title: t("order_by.asc") },
{ value: "desc", title: t("order_by.desc") }
]}
/>
</SearchOption>;
}
function LimitOption({ note, defaultValue, ...restProps }: SearchOptionProps) {
const [ limit, setLimit ] = useNoteLabel(note, "limit");
return <SearchOption
titleIcon="bx bx-stop"
title={t("limit.limit")}
note={note} {...restProps}
>
<FormTextBox
type="number" min="1" step="1"
currentValue={limit ?? defaultValue} onChange={setLimit}
/>
<span className="search-option-field-label">{t("limit.max_results")}</span>
</SearchOption>;
}