repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
quickshell/nuguland/launch.js
RawFile outline
- GLYPH_APP line 8
- GLYPH_ACTION line 9
- GLYPH_CALCULATOR line 10
- GLYPH_CLIPBOARD line 11
- GLYPH_WINDOW line 12
- normalize line 15
- prefixIntent line 21
- isWordChar line 36
- subsequenceMatch line 43
- fuzzyScore line 75
- calculatorValue line 105
- rowVerb line 122
- rowIconRole line 134
- providerGlyph line 146
- shapeRow line 156
- pushResult line 169
- buildApps line 178
- rankResults line 213
// launch.js — pure launcher logic: normalize, prefix intents, subsequence fuzzy
// scoring, calculator eval, row shaping, app mapping, and the ranking core.
// NO I/O. Dual-mode: node `require` (tests) + QML import. Same pattern as clip.js.
// --- Provider Nerd Font glyphs (FA PUA, render in "Symbols Nerd Font Mono").
// Kept as \uXXXX escapes. App glyph is the FALLBACK shown only when a real
// desktop icon fails to resolve. ---
var GLYPH_APP = "\uF135"; // rocket (app fallback)
var GLYPH_ACTION = "\uF013"; // gear
var GLYPH_CALCULATOR = "\uF1EC"; // calculator
var GLYPH_CLIPBOARD = "\uF0EA"; // clipboard
var GLYPH_WINDOW = "\uF2D0"; // window
// --- lowercase + trim, null-safe (search/compare key) ---
function normalize(text) {
return String(text == null ? "" : text).trim().toLowerCase();
}
// --- prefix routing: `=`->calculator, `>`->action, `clip `->clipboard, else all.
// Strips the prefix into `query`. Returns {intent, query}. ---
function prefixIntent(raw) {
var text = String(raw == null ? "" : raw).trim();
if (text.indexOf("=") === 0)
return { intent: "calculator", query: text.slice(1).trim() };
if (text.indexOf(">") === 0)
return { intent: "action", query: text.slice(1).trim() };
// `.trim()` above strips the trailing space, so match "clip" exactly or the
// "clip <query>" form. (IPC also trims the arg, so a bare "clip " arrives as "clip".)
var low = text.toLowerCase();
if (low === "clip" || low.indexOf("clip ") === 0)
return { intent: "clipboard", query: text.slice(4).trim() };
return { intent: "all", query: text };
}
// --- a char is part of a word (vs. a boundary separator: space, -, _, ., /, :) ---
function isWordChar(ch) {
return /[a-z0-9]/.test(ch);
}
// --- greedy left-to-right subsequence match of q against t (both normalized).
// Returns {matched, firstIndex, contiguous, boundaryHits}. `contiguous` counts
// adjacent matched positions; `boundaryHits` counts matches at a word start. ---
function subsequenceMatch(q, t) {
var qi = 0;
var positions = [];
for (var ti = 0; ti < t.length && qi < q.length; ti++) {
if (t.charAt(ti) === q.charAt(qi)) {
positions.push(ti);
qi++;
}
}
if (qi < q.length)
return { matched: false, firstIndex: -1, contiguous: 0, boundaryHits: 0 };
var contiguous = 0;
var boundaryHits = 0;
for (var i = 0; i < positions.length; i++) {
var p = positions[i];
if (i > 0 && positions[i] === positions[i - 1] + 1)
contiguous++;
if (p === 0 || !isWordChar(t.charAt(p - 1)))
boundaryHits++;
}
return {
matched: true,
firstIndex: positions[0],
contiguous: contiguous,
boundaryHits: boundaryHits
};
}
// --- subsequence-aware ranking. Bands stay separated so categories can't cross:
// exact +1000, prefix +800-len, word-boundary subsequence (base 600), loose
// subsequence (base 350), substring fallback, else -1. `boost` is a per-provider
// weight; empty query returns boost so every row lists. ---
function fuzzyScore(query, title, boost) {
var b = Number(boost) || 0;
var q = normalize(query);
var t = normalize(title);
if (q.length === 0)
return b;
if (t === q)
return b + 1000;
if (t.indexOf(q) === 0)
return b + 800 - t.length;
var m = subsequenceMatch(q, t);
if (m.matched) {
// every matched char at a word start => acronym-grade (high band)
var allBoundary = m.boundaryHits === q.length;
var base = allBoundary ? 600 : 350;
var bonus = m.contiguous * 10 + m.boundaryHits * 15 - m.firstIndex;
return b + base + bonus;
}
// substring fallback (any contiguous substring is already a subsequence, so
// this is effectively unreachable — kept to document intent).
var idx = t.indexOf(q);
if (idx > 0)
return b + 300 - idx;
return -1;
}
// --- regex-guarded arithmetic eval. Returns a formatted string, or null on
// guard failure / non-finite / non-number. Integers print plain; otherwise
// rounded to 4 decimals. ---
function calculatorValue(expression) {
var expr = String(expression == null ? "" : expression).replace(/\s+/g, "");
if (expr.length === 0 || !/^[0-9.+\-*/()%]+$/.test(expr))
return null;
try {
var value = Function('"use strict"; return (' + expr + ')')();
if (typeof value !== "number" || !isFinite(value))
return null;
return value === Math.floor(value)
? String(value)
: String(Math.round(value * 10000) / 10000);
} catch (error) {
return null;
}
}
// --- primary verb per provider (row may override via row.verb) ---
function rowVerb(provider, row) {
if (row && row.verb)
return String(row.verb);
if (provider === "calculator") return "copy-result";
if (provider === "action") return "run-action";
if (provider === "app") return "launch-app";
if (provider === "clipboard") return "copy-clipboard";
if (provider === "window") return "focus-window";
return "activate";
}
// --- semantic icon role per provider (row may override via row.iconRole) ---
function rowIconRole(provider, row) {
if (row && row.iconRole)
return String(row.iconRole);
if (provider === "calculator") return "calculator";
if (provider === "action") return "shell-action";
if (provider === "app") return "desktop-entry";
if (provider === "clipboard") return "clipboard";
if (provider === "window") return "niri-window";
return "item";
}
// --- Nerd Font fallback glyph per provider (apps fall back to rocket) ---
function providerGlyph(provider) {
if (provider === "action") return GLYPH_ACTION;
if (provider === "calculator") return GLYPH_CALCULATOR;
if (provider === "clipboard") return GLYPH_CLIPBOARD;
if (provider === "window") return GLYPH_WINDOW;
return GLYPH_APP;
}
// --- clone + enrich a row for the result list. Preserves `icon` (desktop icon
// name) for apps so the view can render the real themed image. ---
function shapeRow(row, provider, score) {
var next = Object.assign({}, row || {});
next.provider = provider;
next.iconRole = rowIconRole(provider, next);
next.verb = rowVerb(provider, next);
next.glyph = providerGlyph(provider);
next.subtitle = next.subtitle || provider;
next.score = score;
next.keyboard = true;
return next;
}
// --- filter (score < 0 drops) + shape into the results list ---
function pushResult(results, row, provider, score) {
if (score < 0)
return;
results.push(shapeRow(row, provider, score));
}
// --- Map Quickshell DesktopEntry objects to launcher rows, sorted by title.
// Exec field codes (%f, %u, …) are already stripped from `command` by Quickshell.
// Keeps `icon` (desktop icon name) for real themed-icon rendering. ---
function buildApps(entries) {
var list = entries || [];
var rows = [];
for (var i = 0; i < list.length; i++) {
var e = list[i];
if (!e || !e.name)
continue;
var id = String(e.id || e.name);
var argv = [];
var command = e.command || [];
for (var j = 0; j < command.length; j++) argv.push(String(command[j]));
rows.push({
id: "app:" + id,
title: String(e.name),
subtitle: String(e.comment || e.genericName || id),
desktopId: id,
// uwsm resolves the desktop id (with .desktop suffix) for proper
// startup/env integration; argv is the fallback launch path.
desktopPath: id + ".desktop",
exec: String(e.execString || ""),
execArgv: argv,
icon: String(e.icon || ""),
terminal: !!e.runInTerminal,
route: "desktop-entry"
});
}
rows.sort(function (a, b) {
return String(a.title).localeCompare(String(b.title));
});
return rows;
}
// --- the pure ranking core. Takes the already-gathered source bundles (no I/O)
// and returns {results, selectedIndex, providerIntent, calc}. Applies prefix
// intent, scores each provider, filters non-matches, sorts by score then title. ---
function rankResults(rawQuery, sources) {
var src = sources || {};
var apps = src.apps || [];
var actions = src.actions || [];
var windows = src.windows || [];
var clipRows = src.clipRows || [];
var intent = prefixIntent(rawQuery);
var provider = intent.intent;
var query = intent.query;
var results = [];
var calcValue = calculatorValue(query);
var calc = null;
if ((provider === "calculator" || provider === "all") && calcValue !== null) {
calc = {
id: "calc:" + query,
title: calcValue,
subtitle: query,
value: calcValue,
route: "calculator"
};
pushResult(results, calc, "calculator", provider === "calculator" ? 2000 : 600);
}
if (provider === "action" || provider === "all") {
for (var a = 0; a < actions.length; a++)
pushResult(results, actions[a], "action",
fuzzyScore(query, actions[a].title, provider === "action" ? 1500 : 300));
}
if (provider === "app" || provider === "all") {
for (var p = 0; p < apps.length; p++)
pushResult(results, Object.assign({ route: "desktop-entry" }, apps[p]),
"app", fuzzyScore(query, apps[p].title, 900));
}
if (provider === "clipboard" || provider === "all") {
for (var c = 0; c < clipRows.length; c++)
pushResult(results, Object.assign({ route: "clipboard" }, clipRows[c]),
"clipboard", fuzzyScore(query, clipRows[c].title, provider === "clipboard" ? 1400 : 200));
}
// Windows have no prefix intent, so they list only in `all` (or an explicit
// `window` intent, kept for forward-compat). This intentionally differs from
// the old search() which added windows under every intent.
if (provider === "all" || provider === "window") {
for (var w = 0; w < windows.length; w++) {
var win = windows[w];
var title = win.title || win.app_id || win.appId || ("window " + win.id);
pushResult(results, {
id: String(win.id),
title: title,
subtitle: win.app_id || win.appId || "window",
route: "niri-window",
windowId: win.id
}, "window", fuzzyScore(query, title, provider === "window" ? 1300 : 250));
}
}
results.sort(function (x, y) {
return y.score - x.score || String(x.title).localeCompare(String(y.title));
});
return {
results: results,
selectedIndex: results.length > 0 ? 0 : -1,
providerIntent: provider,
calc: calc
};
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = { normalize: normalize, prefixIntent: prefixIntent,
subsequenceMatch: subsequenceMatch, fuzzyScore: fuzzyScore,
calculatorValue: calculatorValue, rowVerb: rowVerb,
rowIconRole: rowIconRole, providerGlyph: providerGlyph,
shapeRow: shapeRow, pushResult: pushResult, buildApps: buildApps,
rankResults: rankResults };
}