From 1622d7fd773390de565fc065c531244ce8cb0fde Mon Sep 17 00:00:00 2001 From: Jishan Date: Wed, 18 Nov 2026 19:40:02 +0600 Subject: [PATCH] feat(bookmarks): add browser bookmark search with 'b ' prefix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add Bookmarks core module to parse Chromium-based browser bookmarks - Auto-detect Brave, Chrome, Chromium, Vivaldi, and Edge bookmark stores - Add BookmarkSource QML service with live FileView file watching - Scope bookmarks search exclusively to 'b ' / 'B ' prefix in RootSearch - Keep bookmark candidates isolated from general search to ensure zero overhead - Fast-path searchAsync to bypass nativeSearch for bookmark queries - Add 'Open in Browser' (↵) and 'Copy URL' (Ctrl+Shift+C) actions - Support setQuery outcome in LauncherWindow - Add comprehensive unit tests in tests/bookmarks.test.js (192 passing) - Update README.md documentation --- Backend.qml | 27 ++++++- README.md | 3 + core/Bookmarks.js | 129 ++++++++++++++++++++++++++++++ core/RootSearch.js | 47 ++++++++++- services/BookmarkSource.qml | 76 ++++++++++++++++++ tests/bookmarks.test.js | 153 ++++++++++++++++++++++++++++++++++++ ui/LauncherWindow.qml | 1 + 7 files changed, 429 insertions(+), 7 deletions(-) create mode 100644 core/Bookmarks.js create mode 100644 services/BookmarkSource.qml create mode 100644 tests/bookmarks.test.js diff --git a/Backend.qml b/Backend.qml index 65eba4a..477d0bc 100644 --- a/Backend.qml +++ b/Backend.qml @@ -54,7 +54,8 @@ Item { function searchAsync(data, callback) { nativeSearch.cancel() - var query = String(data && data.query || "").trim() + var rawQuery = String(data && data.query || "") + var query = rawQuery.trim() var view = data && data.view if (query && view && view.kind === "emoji") { emojiSearch.search(Ranker.transliterate(query.toLowerCase()), "medium", function(matches) { @@ -62,6 +63,10 @@ Item { }) return } + if (/^[bB]\s+/.test(rawQuery)) { + callback(backend.callSync("rootSearch.search", data)) + return + } if (!query || (view && view.kind !== "root")) { callback(backend.callSync("rootSearch.search", data)) return @@ -146,7 +151,7 @@ Item { } function decorated(id) { - var c = backend.candidatesById[id] + var c = backend.candidatesById[id] || (id && id.indexOf("bookmark:") === 0 && bookmarkSource.candidatesById ? bookmarkSource.candidatesById[id] : null) return c ? RootSearch.decorate(c, backend.searchContext(), backend.deps) : null } @@ -512,6 +517,7 @@ Item { return { close: true } } backend.recordVisit(id, query) + if (candidate.run.setQuery) return { setQuery: candidate.run.setQuery } if (candidate.run.push && candidate.run.push.kind === "theme") themeSource.refresh() if (candidate.run.push) return { push: candidate.run.push } if (candidate.run.summon) backend.summonPlugin(candidate.run.summon, candidate.run.payload || "{}") @@ -519,6 +525,10 @@ Item { case "fallback": Util.execArgv(["omarchy-launch-browser", RootSearch.fallbackUrl(candidate, query)]) return { close: true } + case "bookmark": + backend.recordVisit(id, query) + Util.execArgv(["omarchy-launch-browser", candidate.url]) + return { close: true } case "script": var script = candidate.script var args = ScriptCommands.argv(script, (data && data.arguments) || {}) @@ -548,6 +558,9 @@ Item { case "copy-id": clipboard.copy(action === "copy-id" ? candidate.appId + ".desktop" : candidate.action) return { close: true, hud: "Copied to Clipboard" } + case "copy-url": + clipboard.copy(candidate.url) + return { close: true, hud: "Copied URL to Clipboard" } case "favorite-add": case "favorite-remove": case "favorite-up": @@ -669,7 +682,11 @@ Item { else if (view && view.kind === "calculator-history") sections = RootSearch.historySections(calculatorStore.doc.history, query, ctx.nowMs, Calculator.filterHistory) else { ctx.filter = String(data && data.filter || "all") - if (query.trim() && ctx.filter === "all") ctx.calculation = backend.calculate(query) + if (/^[bB]\s+/.test(query)) { + ctx.bookmarks = bookmarkSource.candidates + } else if (query.trim() && ctx.filter === "all") { + ctx.calculation = backend.calculate(query) + } sections = RootSearch.rootSections(backend.candidates, query, ctx, backend.deps) } if (view && view.kind === "emoji") return sections @@ -901,6 +918,10 @@ Item { onMessage: function(level, text, metadata) { backend.log(level, "script-commands", text, metadata) } } + BookmarkSource { + id: bookmarkSource + } + // Launcher.qml shows the result as a toast while the window is open, else a HUD. ScriptRunner { id: scriptRunner diff --git a/README.md b/README.md index d580440..f95b002 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,9 @@ web searches at the end. `Ctrl+P` filters the root to All, Applications or Comma **Omarchy Menu** opens the whole menu. - **Web search.** **Search Google** and **Search DuckDuckGo** (alias `ddg`) take a query in an argument pill: `Tab` into it, type, `↵`. +- **Browser bookmarks.** Type `b ` (or `b `) to search and open your browser bookmarks (Brave, Chrome, + Chromium, Vivaldi, Edge). Bookmarks update automatically as you add or edit them in your browser. `↵` opens + the bookmark in your browser, and `Ctrl+Shift+C` copies the URL. - **Confirmations.** Shut Down, Restart, Log Out and Delete All Entries ask first (`↵` confirms, `Esc` cancels). - **Feedback.** Results show toasts in the footer (`Ctrl+T` opens their actions, such as Undo after disabling a diff --git a/core/Bookmarks.js b/core/Bookmarks.js new file mode 100644 index 0000000..bf4d1e5 --- /dev/null +++ b/core/Bookmarks.js @@ -0,0 +1,129 @@ +// Browser Bookmarks provider for omacast (Chromium-family: Brave, Chrome, Chromium, Vivaldi, Edge) + +function cleanUrl(url) { + return String(url || "") + .replace(/^https?:\/\//i, "") + .replace(/^www\./i, "") + .replace(/\/$/, "") +} + +function extractDomain(url) { + try { + var match = String(url || "").match(/^https?:\/\/(?:www\.)?([^\/:]+)/i) + if (match && match[1]) { + var host = match[1].toLowerCase() + var parts = host.split(".") + if (parts.length >= 2) { + var sld = parts[parts.length - 2] + if (parts.length >= 3 && ["co", "com", "gov", "edu", "org", "net"].indexOf(sld) >= 0) { + return parts[parts.length - 3] + } + return sld + } + return host + } + } catch (e) {} + return "" +} + +function parseBookmarks(jsonText, browserName) { + if (!jsonText || typeof jsonText !== "string") return [] + var data + try { + data = JSON.parse(jsonText) + } catch (e) { + return [] + } + var list = [] + function walk(node, folderPath) { + if (!node) return + var currentFolder = folderPath + if (node.type === "folder" && node.name) { + currentFolder = folderPath ? folderPath + " › " + node.name : node.name + } + if (node.type === "url" && node.url && node.name) { + list.push({ + title: node.name, + url: node.url, + folder: currentFolder || "", + browser: browserName || "Browser" + }) + } + if (node.children && Array.isArray(node.children)) { + for (var i = 0; i < node.children.length; i++) { + walk(node.children[i], currentFolder) + } + } + } + if (data.roots) { + for (var key in data.roots) { + walk(data.roots[key], "") + } + } + return list +} + +function candidate(item) { + var title = String(item.title || item.url || "Untitled Bookmark").trim() + var url = String(item.url || "").trim() + var clean = cleanUrl(url) + var domain = extractDomain(url) + var browser = item.browser || "Browser" + var alternates = [] + if (domain && domain.toLowerCase() !== title.toLowerCase()) alternates.push(domain) + if (clean && clean !== title) alternates.push(clean) + + var subtitle = clean + if (item.folder) subtitle = item.folder + " · " + clean + + return { + id: "bookmark:" + url, + type: "quicklink", + kind: "bookmark", + title: title, + subtitle: subtitle, + url: url, + alternateTitles: alternates, + keywords: [], + typeLabel: "Bookmark", + glyph: "\uf02e", // nf-fa-bookmark  + glyphFont: "", + rootSearch: { when: "searching" } + } +} + +function candidates(jsonText, browserName) { + var items = parseBookmarks(jsonText, browserName) + var seen = {} + var out = [] + for (var i = 0; i < items.length; i++) { + var item = items[i] + if (!item.url || seen[item.url]) continue + seen[item.url] = true + out.push(candidate(item)) + } + return out +} + +function knownPaths(configDir) { + var base = String(configDir || "").replace(/\/$/, "") + return [ + { browser: "Brave", path: base + "/BraveSoftware/Brave-Browser/Default/Bookmarks" }, + { browser: "Chrome", path: base + "/google-chrome/Default/Bookmarks" }, + { browser: "Chromium", path: base + "/chromium/Default/Bookmarks" }, + { browser: "Vivaldi", path: base + "/vivaldi/Default/Bookmarks" }, + { browser: "Edge", path: base + "/microsoft-edge/Default/Bookmarks" }, + { browser: "Opera", path: base + "/opera/Bookmarks" } + ] +} + +if (typeof module !== "undefined" && module.exports) { + module.exports = { + cleanUrl: cleanUrl, + extractDomain: extractDomain, + parseBookmarks: parseBookmarks, + candidate: candidate, + candidates: candidates, + knownPaths: knownPaths + } +} diff --git a/core/RootSearch.js b/core/RootSearch.js index 3a2a78a..b30a618 100644 --- a/core/RootSearch.js +++ b/core/RootSearch.js @@ -23,6 +23,16 @@ function webSearch(fallback, keywords) { var BUILTINS = [ webSearch(FALLBACKS[0], []), webSearch(FALLBACKS[1], ["ddg"]), + { + id: "builtin:browser-bookmarks", + title: "Search Browser Bookmarks", + subtitle: "Type “b ” to search", + glyph: "", + keywords: ["b", "bookmark", "bookmarks", "browser", "brave", "chrome", "history"], + alias: "b", + run: { setQuery: "b " }, + rootSearch: { when: "searching" } + }, { id: "builtin:omarchy-menu", title: "Omarchy Menu", @@ -306,17 +316,43 @@ function passesFilter(candidate, filter) { } function rootSections(candidates, query, ctx, deps) { - var q = String(query || "").trim() + var rawQ = String(query || "") + var q = rawQ.trim() var filtered = ctx.filter && ctx.filter !== "all" + var opts = rankOptions(ctx) + + // Handle "b " or "B " prefix for Browser Bookmarks search + if (/^[bB]\s+/.test(rawQ)) { + var bQuery = rawQ.replace(/^[bB]\s+/, "").trim() + var rawBookmarks = (ctx && ctx.bookmarks) ? ctx.bookmarks : candidates.filter(function(c) { return c.kind === "bookmark" }) + var bResults = [] + if (bQuery) { + bResults = deps.Ranker.rank(rawBookmarks, bQuery, opts) + } else { + bResults = rawBookmarks.slice(0, 50).map(function(c) { return { candidate: c, record: null } }) + } + var bSections = [] + if (bResults.length > 0) { + bSections.push({ + id: "bookmarks", + title: "Browser Bookmarks" + (bQuery ? " · “" + bQuery + "”" : ""), + rows: bResults + }) + } + if (bQuery) { + bSections.push({ id: "fallback-commands", title: "Search web for “" + bQuery + "”…", rows: fallbackRows(bQuery) }) + } + return bSections + } + var decorated = [] for (var i = 0; i < candidates.length; i++) { - if (!isEnabled(candidates[i], ctx) || !passesFilter(candidates[i], ctx.filter)) continue + if (!isEnabled(candidates[i], ctx) || !passesFilter(candidates[i], ctx.filter) || candidates[i].kind === "bookmark") continue decorated.push(decorate(candidates[i], ctx, deps)) } - var opts = rankOptions(ctx) if (q) { - var searchable = decorated.filter(function(c) { return c.rootSearch.when !== "empty" }) + var searchable = decorated.filter(function(c) { return c.rootSearch.when !== "empty" && c.kind !== "bookmark" }) var results = deps.Ranker.rank(searchable, q, opts) var sections = [] if (ctx.calculation && !filtered) sections.push({ id: "calculator", title: "Calculator", rows: [{ candidate: calculatorCandidate(ctx.calculation), record: null }] }) @@ -389,12 +425,15 @@ function actionsFor(candidate) { case "omarchy-link": primary = { id: "open", title: "Open Menu", icon: "" }; break case "fallback": primary = { id: "open", title: candidate.title, icon: "" }; break case "script": primary = { id: "open", title: "Run Script", icon: "\uf120" }; break + case "bookmark": primary = { id: "open", title: "Open in Browser", icon: "" }; break default: primary = { id: "open", title: "Open Command", icon: "" } } primary.shortcut = "↵" primary.section = "primary" list.push(primary) + if (candidate.kind === "bookmark") list.push({ id: "copy-url", title: "Copy URL", shortcut: "Ctrl Shift C", section: "copy", icon: "" }) + if (candidate.kind && candidate.kind.indexOf("omarchy-") === 0) list.push({ id: "open-in-omarchy-menu", title: "Open in Omarchy Menu", shortcut: "Ctrl ↵", section: "primary", icon: "" }) if (candidate.kind === "fallback") return list diff --git a/services/BookmarkSource.qml b/services/BookmarkSource.qml new file mode 100644 index 0000000..be4404c --- /dev/null +++ b/services/BookmarkSource.qml @@ -0,0 +1,76 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import "../core/Bookmarks.js" as Bookmarks + +Item { + id: source + + property var candidates: [] + property var candidatesById: ({}) + property int revision: 0 + property string bookmarksPath: "" + property string configDir: (Quickshell.env("XDG_CONFIG_HOME") || (Quickshell.env("HOME") + "/.config")) + readonly property string effectivePath: bookmarksPath ? bookmarksPath : activePath + property string activePath: "" + property string activeBrowser: "" + + Component.onCompleted: { + if (!bookmarksPath) scanner.running = true + } + + Process { + id: scanner + command: ["bash", "-c", + 'cfg="' + source.configDir + '"; ' + + 'for p in ' + + '"$cfg/BraveSoftware/Brave-Browser/Default/Bookmarks:Brave" ' + + '"$cfg/google-chrome/Default/Bookmarks:Chrome" ' + + '"$cfg/chromium/Default/Bookmarks:Chromium" ' + + '"$cfg/vivaldi/Default/Bookmarks:Vivaldi" ' + + '"$cfg/microsoft-edge/Default/Bookmarks:Edge"; do ' + + ' f="${p%%:*}"; b="${p##*:}"; ' + + ' if [[ -f "$f" ]]; then printf "%s:%s\\n" "$f" "$b"; break; fi; ' + + 'done; :' + ] + stdout: StdioCollector { + onStreamFinished: { + var line = text.trim() + if (line) { + var idx = line.lastIndexOf(":") + if (idx > 0) { + source.activePath = line.slice(0, idx) + source.activeBrowser = line.slice(idx + 1) + } + } + } + } + } + + FileView { + id: fileView + path: source.effectivePath + watchChanges: true + printErrors: false + onFileChanged: reload() + onLoaded: { + try { + var raw = text() + var list = Bookmarks.candidates(raw, source.activeBrowser) + var map = ({}) + for (var i = 0; i < list.length; i++) { + map[list[i].id] = list[i] + } + source.candidates = list + source.candidatesById = map + source.revision++ + } catch (e) { + // Ignored unreadable bookmarks + } + } + onLoadFailed: function(error) { + source.candidates = [] + source.candidatesById = ({}) + } + } +} diff --git a/tests/bookmarks.test.js b/tests/bookmarks.test.js new file mode 100644 index 0000000..5d05e51 --- /dev/null +++ b/tests/bookmarks.test.js @@ -0,0 +1,153 @@ +const test = require("node:test") +const assert = require("node:assert/strict") +const Bookmarks = require("../core/Bookmarks.js") +const RootSearch = require("../core/RootSearch.js") +const Ranker = require("../core/Ranker.js") +const Frecency = require("../core/Frecency.js") + +const sampleJson = JSON.stringify({ + checksum: "abc123", + roots: { + bookmark_bar: { + type: "folder", + name: "Bookmarks bar", + children: [ + { + type: "url", + name: "GitHub", + url: "https://github.com/" + }, + { + type: "folder", + name: "Development", + children: [ + { + type: "url", + name: "LeetCode", + url: "https://leetcode.com/u/wsjishan/" + }, + { + type: "url", + name: "YouTube Music", + url: "https://music.youtube.com/" + } + ] + } + ] + }, + other: { + type: "folder", + name: "Other bookmarks", + children: [ + { + type: "url", + name: "Grok", + url: "https://grok.com/" + } + ] + } + }, + version: 1 +}) + +test("cleanUrl removes protocol, www, and trailing slashes", () => { + assert.equal(Bookmarks.cleanUrl("https://www.youtube.com/"), "youtube.com") + assert.equal(Bookmarks.cleanUrl("http://github.com/wahidsadik/"), "github.com/wahidsadik") + assert.equal(Bookmarks.cleanUrl("https://leetcode.com"), "leetcode.com") +}) + +test("extractDomain extracts domain names from various URLs", () => { + assert.equal(Bookmarks.extractDomain("https://www.youtube.com/"), "youtube") + assert.equal(Bookmarks.extractDomain("https://music.youtube.com/"), "youtube") + assert.equal(Bookmarks.extractDomain("https://github.com/foo/bar"), "github") + assert.equal(Bookmarks.extractDomain("https://sub.domain.co.uk/"), "domain") + assert.equal(Bookmarks.extractDomain(""), "") +}) + +test("parseBookmarks parses nested Chromium bookmark JSON", () => { + const items = Bookmarks.parseBookmarks(sampleJson, "Brave") + assert.equal(items.length, 4) + assert.equal(items[0].title, "GitHub") + assert.equal(items[0].url, "https://github.com/") + assert.equal(items[1].title, "LeetCode") + assert.equal(items[1].folder, "Bookmarks bar › Development") + assert.equal(items[1].browser, "Brave") +}) + +test("parseBookmarks handles invalid and empty JSON safely", () => { + assert.deepEqual(Bookmarks.parseBookmarks("", "Brave"), []) + assert.deepEqual(Bookmarks.parseBookmarks("invalid json", "Brave"), []) + assert.deepEqual(Bookmarks.parseBookmarks("{}", "Brave"), []) +}) + +test("candidates creates properly formatted search candidates with deduplication", () => { + const duplicatedJson = JSON.stringify({ + roots: { + bar: { + children: [ + { type: "url", name: "GitHub 1", url: "https://github.com/" }, + { type: "url", name: "GitHub 2", url: "https://github.com/" } + ] + } + } + }) + const candidates = Bookmarks.candidates(duplicatedJson, "Brave") + assert.equal(candidates.length, 1) + assert.equal(candidates[0].id, "bookmark:https://github.com/") + assert.equal(candidates[0].type, "quicklink") + assert.equal(candidates[0].kind, "bookmark") + assert.equal(candidates[0].typeLabel, "Bookmark") + assert.equal(candidates[0].glyph, "\uf02e") + assert.ok(candidates[0].alternateTitles.includes("github")) + assert.equal(candidates[0].keywords.length, 0) +}) + +test("knownPaths returns paths for major Linux browsers", () => { + const paths = Bookmarks.knownPaths("/home/user/.config") + assert.ok(paths.some((p) => p.browser === "Brave" && p.path.includes("Brave-Browser"))) + assert.ok(paths.some((p) => p.browser === "Chrome" && p.path.includes("google-chrome"))) + assert.ok(paths.some((p) => p.browser === "Chromium" && p.path.includes("chromium"))) +}) + +test("rootSections isolates bookmarks to 'b ' prefix only", () => { + const bookmarks = Bookmarks.candidates(sampleJson, "Brave") + const deps = { Ranker, Frecency } + const ctx = { nowMs: 1_800_000_000_000, commands: {}, frecency: {} } + + // Normal query without "b " prefix must NEVER return bookmarks + const normalSections = RootSearch.rootSections(bookmarks, "git", ctx, deps) + const hasBookmark = normalSections.some((s) => s.rows && s.rows.some((r) => r.candidate && r.candidate.kind === "bookmark")) + assert.equal(hasBookmark, false) + + // Query "b " shows all bookmarks in dedicated section + const emptySections = RootSearch.rootSections(bookmarks, "b ", ctx, deps) + assert.equal(emptySections.length, 1) + assert.equal(emptySections[0].id, "bookmarks") + assert.equal(emptySections[0].title, "Browser Bookmarks") + assert.equal(emptySections[0].rows.length, 4) + + // Query "b leet" filters and ranks bookmarks + const leetSections = RootSearch.rootSections(bookmarks, "b leet", ctx, deps) + assert.equal(leetSections.length, 2) // bookmarks + fallback + assert.equal(leetSections[0].id, "bookmarks") + assert.ok(leetSections[0].title.includes("leet")) + assert.equal(leetSections[0].rows[0].candidate.title, "LeetCode") + + // Query "B git" case insensitive prefix + const gitSections = RootSearch.rootSections(bookmarks, "B git", ctx, deps) + assert.equal(gitSections[0].rows[0].candidate.title, "GitHub") + + // Bookmarks supplied via ctx.bookmarks (when candidates list does not have bookmarks) + const ctxWithBookmarks = Object.assign({}, ctx, { bookmarks: bookmarks }) + const separatedSections = RootSearch.rootSections([], "b leet", ctxWithBookmarks, deps) + assert.equal(separatedSections[0].id, "bookmarks") + assert.equal(separatedSections[0].rows[0].candidate.title, "LeetCode") +}) + +test("actionsFor offers Open in Browser and Copy URL for bookmarks", () => { + const candidate = Bookmarks.candidate({ title: "GitHub", url: "https://github.com/" }) + const actions = RootSearch.actionsFor(candidate) + assert.equal(actions[0].id, "open") + assert.equal(actions[0].title, "Open in Browser") + assert.ok(actions.some((a) => a.id === "copy-url" && a.shortcut === "Ctrl Shift C")) +}) diff --git a/ui/LauncherWindow.qml b/ui/LauncherWindow.qml index 1071842..c8a1f46 100644 --- a/ui/LauncherWindow.qml +++ b/ui/LauncherWindow.qml @@ -500,6 +500,7 @@ PanelWindow { var r = window.backend.callSync("rootSearch.performAction", payload) if (!r.ok) { window.showToast("failure", r.error); return } var outcome = r.data || {} + if (outcome.setQuery !== undefined) { window.setQuery(outcome.setQuery); return } if (outcome.confirm) { window.alert = { spec: outcome.confirm, payload: payload }; return } if (outcome.push) { window.push(outcome.push); return } if (outcome.close) {