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
feat(options): pick the search engine from a dropdown
Elian Dorand71b6ed0640e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 6853976a3f..c2f506711f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2097,13 +2097,14 @@},"search_engine": {"title": "Search Engine",- "custom_search_engine_info": "Used when searching the web for selected text. If not configured, DuckDuckGo will be used. Choose None to remove the web search from the context menu.",- "predefined_templates_label": "Presets",+ "custom_search_engine_info": "Used to search the web for text selected in a note.",+ "engine_label": "Engine","bing": "Bing","baidu": "Baidu","duckduckgo": "DuckDuckGo","google": "Google","none": "None",+ "custom": "Custom","custom_name_label": "Name","custom_name_placeholder": "Search engine name","custom_url_label": "URL",diff --git a/apps/client/src/widgets/type_widgets/options/other.css b/apps/client/src/widgets/type_widgets/options/other.cssindex 4c52e2c743..e871b2b603 100644--- a/apps/client/src/widgets/type_widgets/options/other.css+++ b/apps/client/src/widgets/type_widgets/options/other.css@@ -11,33 +11,6 @@font-family: var(--monospace-font-family);}-/* Overrides the card option's no-shrink rule: a wrapping set of chips gives way instead. */-.tn-card-option > .search-engine-templates {- flex-shrink: 1;- min-width: 0;-}--.search-engine-templates {- --badge-radius: 12px;- display: flex;- flex-wrap: wrap;- justify-content: end;- align-items: center;- gap: 8px;-}--.search-engine-templates .ext-badge {- --color: var(--input-background-color);- color: var(--main-text-color);- font-size: 0.85em;-}--.search-engine-templates .ext-badge.selected {- --color: var(--accented-background-color);- outline: 2px solid var(--accent-color);- outline-offset: -2px;-}-/* A name is a word or two. Not said of the URL below it, which is stacked and uses its whole line. */.search-engine-name input {width: auto;diff --git a/apps/client/src/widgets/type_widgets/options/other.spec.tsx b/apps/client/src/widgets/type_widgets/options/other.spec.tsxindex 28370aec79..4f0d17595d 100644--- a/apps/client/src/widgets/type_widgets/options/other.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/other.spec.tsx@@ -52,7 +52,7 @@ vi.mock("../../react/hooks", async (importOriginal) => ({vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));-import OtherSettings from "./other";+import OtherSettings, { getSearchEngineChoice } from "./other";let host: HTMLElement;@@ -86,25 +86,70 @@ function open() {const button = (name: string) => host.querySelector<HTMLButtonElement>(`button[name='${name}']`);describe("the search engine settings", () => {- it("marks the engine currently in use, and takes both its name and its address when one is picked", () => {- mocks.stored = { ...mocks.stored, customSearchEngineUrl: "https://www.google.com/search?q={keyword}" };+ const engine = () => host.querySelector<HTMLSelectElement>(".search-engine-choice select");+ const urlBox = () => host.querySelector<HTMLInputElement>("input[type='url']");+ function choose(value: string) {+ const select = engine();+ expect(select).not.toBeNull();+ act(() => {+ if (!select) return;+ select.value = value;+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });+ }++ it("offers none, the presets and custom, picking the entry from the stored URL", () => {open();+ expect([ ...engine()?.options ?? [] ].map((option) => option.text)).toEqual([+ "search_engine.none", "search_engine.duckduckgo", "search_engine.bing",+ "search_engine.baidu", "search_engine.google", "search_engine.custom"+ ]);+ expect(urlBox()).toBeNull();++ // An empty URL is DuckDuckGo, as the context menu falls back to it.+ expect(getSearchEngineChoice("")).toBe("https://duckduckgo.com/?q={keyword}");+ expect(getSearchEngineChoice("none")).toBe("none");+ expect(getSearchEngineChoice("https://www.bing.com/search?q={keyword}"))+ .toBe("https://www.bing.com/search?q={keyword}");+ expect(getSearchEngineChoice("https://example.com/?s={keyword}")).toBe("custom");+ });- const chips = [ ...host.querySelectorAll(".search-engine-templates .ext-badge") ];- expect(chips).toHaveLength(5);- expect(chips.filter((chip) => chip.className.includes("selected"))).toHaveLength(1);+ it("stores the name and address of a preset, and the sentinel for none", () => {+ open();- act(() => (chips[0] as HTMLElement).click());- expect(mocks.saved.map(([ name ]) => name)).toEqual([ "customSearchEngineName", "customSearchEngineUrl" ]);+ choose("https://www.google.com/search?q={keyword}");+ choose("none");+ expect(mocks.saved).toEqual([+ [ "customSearchEngineName", "search_engine.google" ],+ [ "customSearchEngineUrl", "https://www.google.com/search?q={keyword}" ],+ [ "customSearchEngineName", "" ],+ [ "customSearchEngineUrl", "none" ]+ ]);});- it("turns the web search off with the none preset", () => {+ it("shows the name and URL fields only for a custom engine", () => {+ const store = (url: string) => {+ mocks.stored = { ...mocks.stored, customSearchEngineUrl: url };+ };+ store("https://example.com/?s={keyword}");+ open();+ expect(urlBox()?.type).toBe("url");+ expect(urlBox()?.value).toBe("https://example.com/?s={keyword}");++ // Switching from a preset keeps its values to edit; from none, it clears the sentinel.+ store("https://www.bing.com/search?q={keyword}");open();- const none = host.querySelector(".search-engine-templates .ext-badge:last-child");- expect(none?.textContent).toBe("search_engine.none");+ choose("custom");+ expect(urlBox()).not.toBeNull();+ expect(mocks.saved).toEqual([]);- act(() => (none as HTMLElement).click());- expect(mocks.saved).toEqual([ [ "customSearchEngineName", "" ], [ "customSearchEngineUrl", "none" ] ]);+ store("none");+ open();+ choose("custom");+ expect(mocks.saved).toEqual([+ [ "customSearchEngineName", "" ],+ [ "customSearchEngineUrl", "" ]+ ]);});});diff --git a/apps/client/src/widgets/type_widgets/options/other.tsx b/apps/client/src/widgets/type_widgets/options/other.tsxindex 89dc87346a..5de33f45b9 100644--- a/apps/client/src/widgets/type_widgets/options/other.tsx+++ b/apps/client/src/widgets/type_widgets/options/other.tsx@@ -1,16 +1,16 @@import "./other.css";import { SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";-import { useMemo } from "preact/hooks";+import { useMemo, useState } from "preact/hooks";import { NO_SEARCH_ENGINE } from "../../../menus/note_context_menu";import { t } from "../../../services/i18n";import search from "../../../services/search";import server from "../../../services/server";import toast from "../../../services/toast";-import { Badge } from "../../react/Badge";import Button from "../../react/Button";import { Card, CardSection, OptionCardSection } from "../../react/Card";+import FormSelect from "../../react/FormSelect";import FormTextBox, { FormTextBoxWithUnit } from "../../react/FormTextBox";import FormToggle from "../../react/FormToggle";import { useTriliumOption, useTriliumOptionBool, useTriliumOptionJson } from "../../react/hooks";@@ -59,67 +59,96 @@ function SearchSettings() {}function SearchEngineSettings() {- const [ customSearchEngineName, setCustomSearchEngineName ] = useTriliumOption("customSearchEngineName");- const [ customSearchEngineUrl, setCustomSearchEngineUrl ] = useTriliumOption("customSearchEngineUrl");-- const searchEngines = useMemo(() => {- return [- { url: "https://duckduckgo.com/?q={keyword}", name: t("search_engine.duckduckgo") },- { url: "https://www.bing.com/search?q={keyword}", name: t("search_engine.bing"), icon: "bx bxl-bing" },- { url: "https://www.baidu.com/s?wd={keyword}", name: t("search_engine.baidu"), icon: "bx bxl-baidu" },- { url: "https://www.google.com/search?q={keyword}", name: t("search_engine.google"), icon: "bx bxl-google" },- { url: NO_SEARCH_ENGINE, name: "", label: t("search_engine.none"), icon: "bx bx-block" }- ];- }, []);+ const [ name, setName ] = useTriliumOption("customSearchEngineName");+ const [ url, setUrl ] = useTriliumOption("customSearchEngineUrl");+ const [ customChosen, setCustomChosen ] = useState(false);+ const choice = customChosen ? CUSTOM_SEARCH_ENGINE : getSearchEngineChoice(url);++ const choices = useMemo(() => [+ { value: NO_SEARCH_ENGINE, title: t("search_engine.none") },+ ...SEARCH_ENGINE_PRESETS.map(({ url, nameKey }) => ({ value: url, title: t(nameKey) })),+ { value: CUSTOM_SEARCH_ENGINE, title: t("search_engine.custom") }+ ], []);++ function choose(value: string) {+ if (value === CUSTOM_SEARCH_ENGINE) {+ setCustomChosen(true);+ if (url === NO_SEARCH_ENGINE) {+ setName("");+ setUrl("");+ }+ return;+ }++ setCustomChosen(false);+ const preset = SEARCH_ENGINE_PRESETS.find((preset) => preset.url === value);+ setName(preset ? t(preset.nameKey) : "");+ setUrl(value);+ }return (<Cardheading={t("search_engine.title")}description={t("search_engine.custom_search_engine_info")}>- <OptionCardSection label={t("search_engine.predefined_templates_label")}>- <div className="search-engine-templates">- {searchEngines.map(engine => (- <Badge- key={engine.url}- icon={engine.icon}- text={engine.label ?? engine.name}- className={customSearchEngineUrl === engine.url ? "selected" : ""}- onClick={() => {- setCustomSearchEngineName(engine.name);- setCustomSearchEngineUrl(engine.url);- }}- />- ))}- </div>- </OptionCardSection>-- <OptionCardSection- className="search-engine-name"- name="custom-name"- label={t("search_engine.custom_name_label")}- >- <FormTextBox- currentValue={customSearchEngineName} onBlur={setCustomSearchEngineName}- placeholder={t("search_engine.custom_name_placeholder")}- />- </OptionCardSection>-<OptionCardSection- name="custom-url"- label={t("search_engine.custom_url_label")}- description={t("search_engine.custom_url_description")}- stacked+ className="search-engine-choice"+ name="search-engine"+ label={t("search_engine.engine_label")}+ subSectionsVisible={choice === CUSTOM_SEARCH_ENGINE}+ subSections={[+ <OptionCardSection+ key="name"+ className="search-engine-name"+ name="custom-name"+ label={t("search_engine.custom_name_label")}+ >+ <FormTextBox+ currentValue={name} onBlur={setName}+ placeholder={t("search_engine.custom_name_placeholder")}+ />+ </OptionCardSection>,+ <OptionCardSection+ key="url"+ name="custom-url"+ label={t("search_engine.custom_url_label")}+ description={t("search_engine.custom_url_description")}+ stacked+ >+ <FormTextBox+ type="url"+ currentValue={url} onBlur={setUrl}+ placeholder={t("search_engine.custom_url_placeholder")}+ />+ </OptionCardSection>+ ]}>- <FormTextBox- currentValue={customSearchEngineUrl} onBlur={setCustomSearchEngineUrl}- placeholder={t("search_engine.custom_url_placeholder")}+ <FormSelect+ values={choices} keyProperty="value" titleProperty="title"+ currentValue={choice} onChange={choose}/></OptionCardSection></Card>);}+const CUSTOM_SEARCH_ENGINE = "custom";++const SEARCH_ENGINE_PRESETS = [+ { url: "https://duckduckgo.com/?q={keyword}", nameKey: "search_engine.duckduckgo" },+ { url: "https://www.bing.com/search?q={keyword}", nameKey: "search_engine.bing" },+ { url: "https://www.baidu.com/s?wd={keyword}", nameKey: "search_engine.baidu" },+ { url: "https://www.google.com/search?q={keyword}", nameKey: "search_engine.google" }+] as const;++/** The dropdown entry for a stored URL. An empty one is DuckDuckGo, as in the context menu. */+export function getSearchEngineChoice(url: string) {+ if (url === NO_SEARCH_ENGINE) return NO_SEARCH_ENGINE;+ if (!url) return SEARCH_ENGINE_PRESETS[0].url;+ const isPreset = SEARCH_ENGINE_PRESETS.some((preset) => preset.url === url);+ return isPreset ? url : CUSTOM_SEARCH_ENGINE;+}+function NoteErasureTimeout() {return (<Card