220 lines
9.4 KiB
JavaScript
220 lines
9.4 KiB
JavaScript
var A = (typeof window !== "undefined" && window.aiAgentPlugin) || null;
|
|
var INIT = (A && A.init) || {};
|
|
var LANG = INIT.lang === "fr" ? "fr" : "en";
|
|
|
|
/* ── French (was the core's i18n/fr/keyboard.ts) — the labels of the
|
|
actions, pages and conversations come from the app, in its language ── */
|
|
var FR = {
|
|
"Command palette": "Palette de commandes",
|
|
"Run an action, open a page or a conversation…": "Lance une action, ouvre une page ou une conversation…",
|
|
"No matches.": "Aucun résultat.",
|
|
"then": "puis",
|
|
"This app can't list its commands yet — update it.": "Cette version de l'application ne liste pas encore ses commandes — mets-la à jour.",
|
|
"Turn {name} off": "Désactiver {name}",
|
|
"Turn {name} on": "Activer {name}",
|
|
"This page runs inside ai-agent.": "Cette page ne s'ouvre que dans ai-agent."
|
|
};
|
|
function tr(s, vars) {
|
|
var out = LANG === "fr" && FR[s] ? FR[s] : s;
|
|
if (vars) for (var k in vars) out = out.split("{" + k + "}").join(String(vars[k]));
|
|
return out;
|
|
}
|
|
|
|
function esc(s) {
|
|
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
|
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
|
});
|
|
}
|
|
|
|
/* \u2500\u2500 key caps (the core's lib/keyboard/keys.ts chordCaps, display only) \u2500\u2500 */
|
|
var MAC = typeof navigator !== "undefined" &&
|
|
/mac|iphone|ipad|ipod/i.test((navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || navigator.userAgent || "");
|
|
var MODS = ["mod", "ctrl", "alt", "shift"];
|
|
var MAC_GLYPH = { mod: "\u2318", ctrl: "\u2303", alt: "\u2325", shift: "\u21e7" };
|
|
var PC_WORD = { mod: "Ctrl", ctrl: "Ctrl", alt: "Alt", shift: "Shift" };
|
|
var KEY_LABEL = {
|
|
space: "Space", escape: "Esc", enter: "\u21b5", tab: "Tab", backspace: "\u232b", "delete": "Del",
|
|
arrowup: "\u2191", arrowdown: "\u2193", arrowleft: "\u2190", arrowright: "\u2192",
|
|
home: "Home", end: "End", pageup: "PgUp", pagedown: "PgDn"
|
|
};
|
|
function splitChord(chord) {
|
|
var mods = {}; var rest = chord;
|
|
for (;;) {
|
|
var i = rest.indexOf("+");
|
|
if (i <= 0) break;
|
|
var head = rest.slice(0, i);
|
|
if (MODS.indexOf(head) < 0) break;
|
|
mods[head] = true;
|
|
rest = rest.slice(i + 1);
|
|
}
|
|
return { mods: mods, key: rest };
|
|
}
|
|
function chords(binding) { return String(binding || "").trim().split(/\s+/).filter(Boolean); }
|
|
function chordCaps(chord) {
|
|
var s = splitChord(chord);
|
|
var caps = MODS.filter(function (m) { return s.mods[m]; }).map(function (m) { return MAC ? MAC_GLYPH[m] : PC_WORD[m]; });
|
|
caps.push(KEY_LABEL[s.key] || s.key.toUpperCase());
|
|
return caps;
|
|
}
|
|
function capsHtml(binding) {
|
|
return '<span class="caps">' + chords(binding).map(function (c, i) {
|
|
return (i ? '<span class="then">' + esc(tr("then")) + "</span>" : "") +
|
|
'<span class="chord">' + chordCaps(c).map(function (cap) { return "<kbd>" + esc(cap) + "</kbd>"; }).join("") + "</span>";
|
|
}).join("") + "</span>";
|
|
}
|
|
|
|
/* \u2500\u2500 the fuzzy search \u2014 close to the Fuse.js setup the core's palette had
|
|
(keys: label \u00d73, hint \u00d71, keywords \u00d70.5; threshold 0.4; ignoreLocation),
|
|
with no library: a sandboxed frame has no network.
|
|
|
|
A field's score is the fewest edits that turn the query into some stretch
|
|
of it (Sellers' approximate substring match), over the query's length:
|
|
0 = it's in there as is, 1 = nothing alike. A field counts when its score
|
|
is \u2264 THRESHOLD; an item matches when one of its fields does. Its total, as
|
|
Fuse computes it, is the product over the matching fields of
|
|
score ^ (weight \u00d7 norm) (a perfect field counts as EPSILON), norm being
|
|
1/\u221a(words in the field) \u2014 so a match in a short label beats one in a long
|
|
hint. Lowest total first; ties keep the list's order. Case and accents
|
|
don't matter. \u2500\u2500 */
|
|
var THRESHOLD = 0.4;
|
|
var MAX_RESULTS = 40;
|
|
var RECENT = 8;
|
|
var EPSILON = 2.220446049250313e-16;
|
|
var WEIGHTS = { label: 3, hint: 1, keywords: 0.5 };
|
|
var MAX_PATTERN = 64;
|
|
|
|
function fold(s) {
|
|
s = String(s == null ? "" : s).toLowerCase();
|
|
return s.normalize ? s.normalize("NFD").replace(/[\u0300-\u036f]/g, "") : s;
|
|
}
|
|
|
|
/** The edits (insert, delete, change) that turn `p` into the closest stretch
|
|
* of `t`, over p's length — 0 when p is in t. */
|
|
function fieldScore(p, t) {
|
|
if (!p) return 0;
|
|
if (!t) return 1;
|
|
if (t.indexOf(p) >= 0) return 0;
|
|
var m = p.length, n = t.length;
|
|
var prev = new Array(n + 1), cur = new Array(n + 1);
|
|
for (var j = 0; j <= n; j++) prev[j] = 0; // a match may start anywhere
|
|
for (var i = 1; i <= m; i++) {
|
|
cur[0] = i;
|
|
var pc = p.charCodeAt(i - 1);
|
|
for (j = 1; j <= n; j++) {
|
|
var sub = prev[j - 1] + (pc === t.charCodeAt(j - 1) ? 0 : 1);
|
|
var del = prev[j] + 1;
|
|
var ins = cur[j - 1] + 1;
|
|
cur[j] = sub < del ? (sub < ins ? sub : ins) : (del < ins ? del : ins);
|
|
}
|
|
var tmp = prev; prev = cur; cur = tmp;
|
|
}
|
|
var best = m;
|
|
for (j = 0; j <= n; j++) if (prev[j] < best) best = prev[j];
|
|
return Math.min(1, best / m);
|
|
}
|
|
|
|
function norm(text) {
|
|
var n = String(text).trim().split(/\s+/).filter(Boolean).length || 1;
|
|
return Math.round(1000 / Math.sqrt(n)) / 1000;
|
|
}
|
|
|
|
/** An item's total (lower is better), or -1 when no field matches. */
|
|
function itemScore(p, item) {
|
|
var total = 1, hit = false;
|
|
var one = function (text, weight) {
|
|
if (!text) return;
|
|
var s = fieldScore(p, fold(text));
|
|
if (s > THRESHOLD) return;
|
|
hit = true;
|
|
total *= Math.pow(s === 0 ? EPSILON : s, weight * norm(text));
|
|
};
|
|
one(item.label, WEIGHTS.label);
|
|
one(item.hint, WEIGHTS.hint);
|
|
// a list of keywords: its best one
|
|
var best = null;
|
|
(item.keywords || []).forEach(function (k) {
|
|
if (!k) return;
|
|
var s = fieldScore(p, fold(k));
|
|
if (s <= THRESHOLD && (best === null || s < best.s)) best = { s: s, k: k };
|
|
});
|
|
if (best) {
|
|
hit = true;
|
|
total *= Math.pow(best.s === 0 ? EPSILON : best.s, WEIGHTS.keywords * norm(best.k));
|
|
}
|
|
return hit ? total : -1;
|
|
}
|
|
|
|
function search(items, query, limit) {
|
|
var p = fold(query).trim().slice(0, MAX_PATTERN);
|
|
if (!p) return items.slice();
|
|
var scored = [];
|
|
items.forEach(function (item, idx) {
|
|
var s = itemScore(p, item);
|
|
if (s >= 0) scored.push({ s: s, i: idx, item: item });
|
|
});
|
|
scored.sort(function (a, b) { return a.s - b.s || a.i - b.i; });
|
|
return scored.slice(0, limit || MAX_RESULTS).map(function (x) { return x.item; });
|
|
}
|
|
|
|
/* ── the list — what the core's CommandPalette listed, plus the plugins ──
|
|
cmds = aiAgentPlugin.commands(), places = places().places,
|
|
convs = conversations().conversations, switches =
|
|
pluginSwitches().switches (an older app has none). Each item: {key, kind,
|
|
label, hint?, keywords?, binding?, icon?, run: {command} | {to} |
|
|
{plugin, on}}. A place with `plugin` is a plugin's page (kind "plugin",
|
|
drawn with its glyph — `icon`, a base64 SVG data: URI, nothing else). */
|
|
var ICON_URI = /^data:image\/svg\+xml;base64,[A-Za-z0-9+/=]+$/;
|
|
|
|
function buildItems(cmds, places, convs, switches) {
|
|
var out = [];
|
|
((cmds && cmds.commands) || []).forEach(function (c) {
|
|
if (!c || !c.available) return; // nothing answers it right now
|
|
if (c.id === "palette" || c.id === "profile.cycle") return;
|
|
if (c.id.indexOf("modal:command-palette:") === 0) return; // itself
|
|
// a plugin's modal the keymap binds (the cheat sheet) is listed by its name
|
|
var slot = /^profile\.\d+$/.test(c.id);
|
|
if (/\.\d+$/.test(c.id) && !slot) return; // the chips by position
|
|
if (slot && c.current) return; // the profile on screen
|
|
out.push({ key: "a:" + c.id, kind: "action", label: c.label, binding: (c.keys || [])[0] || "",
|
|
run: { command: c.id } });
|
|
});
|
|
var seen = {};
|
|
(places || []).forEach(function (p) {
|
|
if (!p || !p.to || !p.label) return;
|
|
var key = "p:" + p.to + "\u0000" + p.label;
|
|
if (seen[key]) return;
|
|
seen[key] = true;
|
|
var item = { key: key, kind: p.plugin ? "plugin" : "page", label: p.label, hint: p.hint || "",
|
|
keywords: p.keywords || [], run: { to: p.to } };
|
|
if (p.plugin && typeof p.icon === "string" && ICON_URI.test(p.icon)) item.icon = p.icon;
|
|
out.push(item);
|
|
});
|
|
(convs || []).forEach(function (c) {
|
|
if (!c || !c.id) return;
|
|
out.push({ key: "c:" + c.id, kind: "conversation", label: c.title || "", hint: c.hint || "",
|
|
run: { to: "/conversation/" + encodeURIComponent(c.id) } });
|
|
});
|
|
// Turn … off / on: only when typed (never in the empty list), after the rest
|
|
(switches || []).forEach(function (s) {
|
|
if (!s || !s.id || typeof s.on !== "boolean") return;
|
|
var name = s.name || s.id;
|
|
out.push({ key: "s:" + s.id, kind: "switch", label: tr(s.on ? "Turn {name} off" : "Turn {name} on", { name: name }),
|
|
hint: "", keywords: [s.id], run: { plugin: s.id, on: !s.on } });
|
|
});
|
|
return out;
|
|
}
|
|
|
|
/** What shows for a query: with none, the RECENT newest conversations then
|
|
* the actions; else the search's best MAX_RESULTS. */
|
|
function shown(items, query) {
|
|
if (!String(query || "").trim()) {
|
|
var convs = items.filter(function (i) { return i.kind === "conversation"; }).slice(0, RECENT);
|
|
return convs.concat(items.filter(function (i) { return i.kind === "action"; }));
|
|
}
|
|
return search(items, query, MAX_RESULTS);
|
|
}
|
|
|
|
if (typeof module !== "undefined" && module.exports)
|
|
module.exports = { fieldScore: fieldScore, itemScore: itemScore, search: search, buildItems: buildItems,
|
|
shown: shown, fold: fold, capsHtml: capsHtml, chordCaps: chordCaps, tr: tr };
|