Implement plugin search functionality

This commit is contained in:
Andrew
2026-07-06 13:01:21 +08:00
parent a11e442f1d
commit bc21551185
4 changed files with 368 additions and 10 deletions

View File

@@ -6,6 +6,7 @@
<title>Plugins</title>
<link rel="stylesheet" href="./styles.css" />
<link rel="stylesheet" href="./plugin-sort.css" />
<link rel="stylesheet" href="./plugin-search.css" />
<link rel="stylesheet" type="text/css" href="../../include/global.css" />
<link rel="stylesheet" type="text/css" href="../css/common.css" />
<link rel="stylesheet" type="text/css" href="../css/theme.css" />
@@ -16,10 +17,32 @@
<script type="text/javascript" src="../js/common.js"></script>
<script src="./index.js"></script>
<script src="./plugin-sort.js"></script>
<script src="./plugin-search.js"></script>
</head>
<body onLoad="OnInit()">
<div class="app">
<div class="toolbar">
<div id="pluginSearch" class="plugin-search">
<span class="plugin-search-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.4">
<circle cx="6.5" cy="6.5" r="4.5" />
<line x1="10" y1="10" x2="14" y2="14" />
</svg>
</span>
<input id="plugin_search_input" class="plugin-search-input" type="text"
placeholder="Search plugins" autocomplete="off" spellcheck="false" aria-label="Search plugins" />
<button id="plugin_search_clear" class="plugin-search-clear" type="button" title="Clear" aria-label="Clear search">
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor"
stroke-width="1.6" stroke-linecap="round" aria-hidden="true">
<line x1="5" y1="5" x2="11" y2="11" />
<line x1="11" y1="5" x2="5" y2="11" />
</svg>
</button>
<button id="plugin_search_cc" class="plugin-search-toggle" type="button"
aria-pressed="false" title="Match case">Cc</button>
<button id="plugin_search_w" class="plugin-search-toggle" type="button"
aria-pressed="false" title="Match whole word">W</button>
</div>
<!-- <button id="open_terminal" class="ButtonStyleRegular ButtonTypeChoice left-btn">-->
<!-- Open Terminal-->
<!-- </button>-->

View File

@@ -11,6 +11,12 @@ const pluginInstallActions = {
};
let expandedPluginIds = new Set();
// why: transient per-search override on top of expandedPluginIds. A search
// auto-expands rows whose capabilities match, display-only. This lets a
// triangle click during search collapse/reopen such a row without touching
// the base (id -> bool).
let searchExpandOverride = new Map();
let selectedPluginId = "";
let contextPluginId = "";
let activeDetailTab = "plugin-info";
@@ -299,6 +305,27 @@ function SyncPluginListHeaderGutter() {
listPane.style.setProperty("--plugin-list-scrollbar-width", `${scrollbarWidth}px`);
}
// why: paint matched-character ranges as <mark> without an innerHTML build
// note: if no ranges -> return the plain text node
function ApplyHighlight(container, text, ranges) {
if (!ranges || !ranges.length) {
container.appendChild(document.createTextNode(text));
return;
}
let pos = 0;
for (const [start, end] of ranges) {
if (start > pos)
container.appendChild(document.createTextNode(text.slice(pos, start)));
const mark = document.createElement("mark");
mark.className = "plugin-search-hit";
mark.textContent = text.slice(start, end);
container.appendChild(mark);
pos = end;
}
if (pos < text.length)
container.appendChild(document.createTextNode(text.slice(pos)));
}
function RenderPlugins() {
if (!pluginList)
return;
@@ -313,10 +340,28 @@ function RenderPlugins() {
return;
}
// why: stable filter over the existing C++ sort order - no scoring, no reorder. The empty query
// short-circuits (searching=false), leaving every existing render path untouched.
const searching = typeof PluginSearchActive === "function" && PluginSearchActive();
let shown = 0;
for (const plugin of pluginsById.values()) {
const pluginKey = String(plugin.plugin_key || "");
const capabilities = GetCapabilities(plugin);
const isExpanded = expandedPluginIds.has(pluginKey) && capabilities.length > 0;
const match = searching ? ComputePluginMatch(plugin) : null;
if (searching && !match.matched)
continue;
shown++;
// why: transient override wins. Otherwise while searching start collapsed and auto-expand only
// capability matches (the persistent expand state is ignored so unrelated caps don't clutter
// results); when not searching use the persistent state. The base is never written while
// searching, so clearing the search restores exactly what the user had.
const open = searchExpandOverride.has(pluginKey)
? searchExpandOverride.get(pluginKey)
: (searching ? match.hasCapMatch : expandedPluginIds.has(pluginKey));
const isExpanded = open && capabilities.length > 0;
const block = document.createElement("div");
block.className = "plugin-block";
block.dataset.pluginKey = pluginKey;
@@ -331,16 +376,28 @@ function RenderPlugins() {
row.classList.add("selected");
row.appendChild(CheckCell(row, plugin));
row.appendChild(LabelCell(plugin, isExpanded, capabilities.length));
row.appendChild(LabelCell(plugin, isExpanded, capabilities.length, match?.nameRanges));
row.appendChild(VersionCell(plugin));
row.appendChild(SourceCell(plugin));
row.appendChild(StatusCell(plugin));
block.appendChild(row);
if (isExpanded)
block.appendChild(RenderCapabilityTree(plugin, capabilities));
block.appendChild(RenderCapabilityTree(plugin, capabilities, match?.capRanges));
pluginList.appendChild(block);
}
// why: distinct from the size===0 "no plugins" state - here plugins exist but none match the query.
if (searching && shown === 0) {
const empty = document.createElement("div");
empty.className = "empty-state";
empty.appendChild(document.createTextNode('No plugins match "'));
const term = document.createElement("b");
term.textContent = pluginSearch.query;
empty.appendChild(term);
empty.appendChild(document.createTextNode('"'));
pluginList.appendChild(empty);
}
}
function GetErrorText(plugin) {
@@ -479,7 +536,7 @@ function CheckCell(row, plugin) {
return checkCell;
}
function LabelCell(plugin, isExpanded = false, capabilityCount = 0) {
function LabelCell(plugin, isExpanded = false, capabilityCount = 0, nameRanges = null) {
const labelCell = document.createElement("span");
labelCell.className = "label-cell";
@@ -510,7 +567,7 @@ function LabelCell(plugin, isExpanded = false, capabilityCount = 0) {
nameWrap.className = "plugin-name-wrap";
const labelElement = document.createElement(hasCloudLink ? "a" : "span");
labelElement.textContent = pluginLabelText;
ApplyHighlight(labelElement, pluginLabelText, nameRanges);
labelElement.className = "plugin-name-text";
if (hasCloudLink) {
@@ -546,20 +603,20 @@ function SourceCell(plugin) {
return cell;
}
function RenderCapabilityTree(plugin, capabilities) {
function RenderCapabilityTree(plugin, capabilities, capRanges = null) {
const tree = document.createElement("div");
tree.className = "capabilities-tree";
tree.setAttribute("role", "group");
tree.setAttribute("aria-label", "Capabilities");
capabilities.forEach((capability, index) => {
tree.appendChild(RenderCapabilityRow(plugin, capability, index === capabilities.length - 1));
tree.appendChild(RenderCapabilityRow(plugin, capability, index === capabilities.length - 1, capRanges));
});
return tree;
}
function RenderCapabilityRow(plugin, capability, isLast) {
function RenderCapabilityRow(plugin, capability, isLast, capRanges = null) {
const row = document.createElement("div");
row.className = "capability-row plugin-cols";
row.classList.toggle("is-last", isLast);
@@ -574,7 +631,8 @@ function RenderCapabilityRow(plugin, capability, isLast) {
branch.setAttribute("aria-hidden", "true");
const name = document.createElement("span");
name.className = "capability-name";
name.textContent = String(capability?.name || "") || "-";
const capabilityLabel = String(capability?.name || "");
ApplyHighlight(name, capabilityLabel || "-", capRanges?.get(capabilityLabel));
nameCell.appendChild(branch);
nameCell.appendChild(name);
row.appendChild(nameCell);
@@ -921,7 +979,12 @@ function OnPluginListClick(event) {
const pluginKey = String(block.dataset.pluginKey || "");
selectedPluginId = pluginKey;
if (expandedPluginIds.has(pluginKey))
// why: during a search the triangle writes to the transient override (read from the on-screen open
// state), so an auto-expanded row collapses without touching the saved layout. With no search
// active, toggle the persistent base exactly as before.
if (typeof PluginSearchActive === "function" && PluginSearchActive())
searchExpandOverride.set(pluginKey, !block.classList.contains("expanded"));
else if (expandedPluginIds.has(pluginKey))
expandedPluginIds.delete(pluginKey);
else
expandedPluginIds.add(pluginKey);

View File

@@ -0,0 +1,116 @@
.plugin-search {
--search-width: 300px;
flex: 0 0 auto;
width: var(--search-width);
/* why: the search bar takes the auto margin (pinned far left); sort + Refresh + Install cluster right. */
margin-right: auto;
display: flex;
align-items: center;
gap: 2px;
/* why: match the compact toolbar buttons (.toolbar .ButtonTypeChoice is 26px) so the row aligns. */
height: 26px;
padding: 0 6px;
box-sizing: border-box;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 6px;
}
.plugin-search:focus-within {
border-color: var(--main-color);
box-shadow: 0 0 0 2px rgba(0, 150, 136, 0.25);
}
.plugin-search-icon {
display: inline-flex;
color: var(--muted);
}
.plugin-search-input {
flex: 1;
min-width: 0;
background: transparent;
border: 0;
outline: 0;
color: var(--text);
font: inherit;
}
.plugin-search-input::placeholder {
color: var(--muted);
}
/* why: compact squarish toggles - min-width keeps single-char W from collapsing while two-char Cc
grows just enough to fit; tight horizontal padding keeps them from reading as wide pills. */
.plugin-search-toggle {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 22px;
height: 22px;
padding: 0 1px;
border: 1px solid transparent;
border-radius: 4px;
background: transparent;
color: var(--muted);
font-size: 12px;
font-weight: 600;
line-height: 1;
cursor: pointer;
box-sizing: border-box;
}
/* why: set the clear x apart from the Cc/W pair while keeping the pair itself tight - margins on the
toggles only, so the icon-to-text gap is left as-is. clear+toggle = Cc, toggle+toggle = W. */
.plugin-search-clear + .plugin-search-toggle {
margin-left: 4px;
}
.plugin-search-toggle + .plugin-search-toggle {
margin-left: -1px;
}
/* why: subtle round clear affordance - a small muted disc, not a square button. The x is an inline SVG
(not a text glyph) so it centers pixel-perfectly regardless of the platform font. JS flips its
visibility (not display) so its reserved slot never reflows Cc/W. */
.plugin-search-clear {
display: inline-flex;
align-items: center;
justify-content: center;
width: 10px;
height: 10px;
padding: 0;
border: 0;
border-radius: 50%;
color: var(--muted);
cursor: pointer;
visibility: hidden;
background: rgba(127, 127, 127, 0.20);
}
.plugin-search-clear svg {
display: block;
}
.plugin-search-clear:hover {
color: var(--text);
background: rgba(127, 127, 127, 0.45);
}
.plugin-search-toggle:hover {
color: var(--text);
background: var(--row-hover);
}
.plugin-search-toggle.on {
color: var(--button-fg-light, #fff);
background: var(--main-color);
border-color: var(--main-color-hover);
}
/* why: reuse the themed warn tokens so matched-char marks track light and dark automatically.
note: no padding/margin/border - a highlight must not change text width, else rows reflow. */
mark.plugin-search-hit {
border-radius: 2px;
background: var(--plugin-status-warn-bg);
color: var(--plugin-status-warn);
}

View File

@@ -0,0 +1,156 @@
const pluginSearch = { query: "", caseSensitive: false, wholeWord: false };
function PluginSearchActive() {
return pluginSearch.query.length > 0;
}
// --- matcher: fold per-character on the fly so matched offsets stay in ORIGINAL coordinates ---
// why: highlighting marks slices of the original string; a separate folded string would desync offsets.
function FoldChar(ch) {
return ch.normalize("NFD").replace(/\p{Diacritic}/gu, ""); // accents always folded (both Cc states)
}
function Norm(ch, caseSensitive) {
const folded = FoldChar(ch);
return caseSensitive ? folded : folded.toLowerCase(); // Cc controls case only
}
function EscapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function MatchText(text, query) {
if (!query)
return [];
return pluginSearch.wholeWord ? WholeWordRanges(text, query) : FuzzyRanges(text, query);
}
// Fuzzy: ordered subsequence. Builds ranges in original coordinates, merging adjacent runs on the fly.
function FuzzyRanges(text, query) {
const caseSensitive = pluginSearch.caseSensitive;
const needle = Array.from(query).map((ch) => Norm(ch, caseSensitive)).join("");
const ranges = [];
let qi = 0;
for (let i = 0; i < text.length && qi < needle.length; i++) {
if (Norm(text[i], caseSensitive) === needle[qi]) {
const last = ranges[ranges.length - 1];
if (last && last[1] === i)
last[1] = i + 1;
else
ranges.push([i, i + 1]);
qi++;
}
}
return qi === needle.length ? ranges : null;
}
// Whole word: literal \b-bounded match that bypasses fuzzy; Cc still applies. The per-char fold keeps the
// haystack length-aligned to the original text, so regex indices map straight back to original offsets.
// note: one-to-many folds (ligatures, eszett) shift offsets by a char; rare in plugin names, cosmetic only.
function WholeWordRanges(text, query) {
const caseSensitive = pluginSearch.caseSensitive;
const haystack = Array.from(text).map((ch) => Norm(ch, caseSensitive)).join("");
const needle = Array.from(query).map((ch) => Norm(ch, caseSensitive)).join("");
if (!needle)
return null;
const re = new RegExp(`\\b${EscapeRegExp(needle)}\\b`, "g");
const ranges = [];
let match;
// why: needle is non-empty, so \b-bounded matches are never zero-length - no empty-match guard needed.
while ((match = re.exec(haystack)) !== null)
ranges.push([match.index, match.index + match[0].length]);
return ranges.length > 0 ? ranges : null;
}
// Per-plugin evaluator consumed by RenderPlugins. The name text mirrors LabelCell's pluginLabelText so
// highlight offsets line up with what is rendered. Capability names exist for loaded plugins only.
function ComputePluginMatch(plugin) {
const name = plugin.label || plugin.name || plugin.plugin_id || "";
const nameRanges = MatchText(name, pluginSearch.query);
const capabilities = Array.isArray(plugin?.capabilities) ? plugin.capabilities : [];
const capRanges = new Map();
for (const capability of capabilities) {
const key = String(capability?.name || "");
const ranges = MatchText(key, pluginSearch.query);
if (ranges)
capRanges.set(key, ranges);
}
return {
matched: !!nameRanges || capRanges.size > 0,
nameRanges,
capRanges,
hasCapMatch: capRanges.size > 0,
};
}
// --- widget wiring ---
let pluginSearchInput = null;
let pluginSearchClear = null;
let pluginSearchCc = null;
let pluginSearchW = null;
function InitPluginSearch() {
pluginSearchInput = document.getElementById("plugin_search_input");
pluginSearchClear = document.getElementById("plugin_search_clear");
pluginSearchCc = document.getElementById("plugin_search_cc");
pluginSearchW = document.getElementById("plugin_search_w");
if (!pluginSearchInput)
return;
// why: common.js installs a document-level onkeydown that cancels the default action of every key
// (returnValue=false) to block webview shortcuts; on the way up it also swallows typing. Stop the
// field's keydowns from bubbling to it so the input stays editable, leaving the global guard intact.
pluginSearchInput.addEventListener("keydown", (event) => event.stopPropagation());
pluginSearchInput.addEventListener("input", OnPluginSearchInput);
pluginSearchClear?.addEventListener("click", ClearPluginSearch);
pluginSearchCc?.addEventListener("click", () => TogglePluginSearchFlag(pluginSearchCc, "caseSensitive"));
pluginSearchW?.addEventListener("click", () => TogglePluginSearchFlag(pluginSearchW, "wholeWord"));
SyncPluginSearchClear();
}
function OnPluginSearchInput() {
pluginSearch.query = pluginSearchInput.value;
// why: emptying the box by editing (not just the x) also ends the search - drop the transient vetoes.
if (!pluginSearch.query)
ClearSearchExpandOverride();
SyncPluginSearchClear();
RenderPluginsIfReady();
}
function ClearPluginSearch() {
pluginSearch.query = "";
if (pluginSearchInput)
pluginSearchInput.value = "";
ClearSearchExpandOverride();
SyncPluginSearchClear();
RenderPluginsIfReady();
pluginSearchInput?.focus();
}
function TogglePluginSearchFlag(button, key) {
pluginSearch[key] = !pluginSearch[key];
button.classList.toggle("on", pluginSearch[key]);
button.setAttribute("aria-pressed", String(pluginSearch[key]));
RenderPluginsIfReady();
}
// why: toggle visibility (not display / the hidden attribute) so the x keeps its reserved slot and
// showing or hiding it never reflows the Cc / W buttons.
function SyncPluginSearchClear() {
if (pluginSearchClear)
pluginSearchClear.style.visibility = pluginSearch.query.length ? "visible" : "hidden";
}
// why: searchExpandOverride lives in index.js; guard so this module stays loadable on its own.
function ClearSearchExpandOverride() {
if (typeof searchExpandOverride !== "undefined")
searchExpandOverride.clear();
}
function RenderPluginsIfReady() {
if (typeof RenderPlugins === "function")
RenderPlugins();
}
// why: guarded so the module can be loaded in headless syntax checks; mirrors plugin-sort.js.
if (typeof document !== "undefined")
document.addEventListener("DOMContentLoaded", InitPluginSearch);