Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: bridge safe clipboard shortcuts on linux and windows

Tw938229ce3ba64a
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index c9ff3a5e..256f250b 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -53,6 +53,78 @@ function handleShortcut(event) {
}
}
+function isNonMacDesktop() {
+ return /windows|linux/i.test(navigator.userAgent);
+}
+
+function isEditableElement(element) {
+ if (!element) return false;
+
+ const tagName = element.tagName;
+ return (
+ tagName === "INPUT" || tagName === "TEXTAREA" || element.isContentEditable
+ );
+}
+
+function hasSelectedText() {
+ return Boolean(window.getSelection?.()?.toString());
+}
+
+function selectEditableElement(element) {
+ if (typeof element.select === "function") {
+ element.select();
+ return true;
+ }
+
+ if (element.isContentEditable) {
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ const selection = window.getSelection?.();
+ if (!selection) return false;
+
+ selection.removeAllRanges();
+ selection.addRange(range);
+ return true;
+ }
+
+ return false;
+}
+
+function handleClipboardShortcut(event) {
+ if (
+ !isNonMacDesktop() ||
+ !event.ctrlKey ||
+ event.metaKey ||
+ event.altKey ||
+ event.shiftKey
+ ) {
+ return false;
+ }
+
+ const key = event.key?.toLowerCase();
+ const activeElement = document.activeElement;
+ const isEditable = isEditableElement(activeElement);
+
+ if (key === "c" && (isEditable || hasSelectedText())) {
+ document.execCommand("copy");
+ event.preventDefault();
+ return true;
+ }
+
+ if (key === "x" && isEditable) {
+ document.execCommand("cut");
+ event.preventDefault();
+ return true;
+ }
+
+ if (key === "a" && isEditable && selectEditableElement(activeElement)) {
+ event.preventDefault();
+ return true;
+ }
+
+ return false;
+}
+
const DOWNLOADABLE_FILE_EXTENSIONS = {
documents: [
"pdf",
@@ -345,6 +417,8 @@ document.addEventListener("DOMContentLoaded", () => {
});
}
+ document.addEventListener("keydown", handleClipboardShortcut, true);
+
document.addEventListener(
"paste",
(event) => {
diff --git a/tests/unit/event-clipboard-shortcuts.test.js b/tests/unit/event-clipboard-shortcuts.test.js
new file mode 100644
index 00000000..1622975d
--- /dev/null
+++ b/tests/unit/event-clipboard-shortcuts.test.js
@@ -0,0 +1,222 @@
+import fs from "fs";
+import path from "path";
+import { runInNewContext } from "node:vm";
+import { describe, expect, it, vi } from "vitest";
+
+function createElement(tagName = "div") {
+ return {
+ tagName: tagName.toUpperCase(),
+ style: {},
+ children: [],
+ isContentEditable: false,
+ addEventListener: () => {},
+ appendChild(child) {
+ this.children.push(child);
+ return child;
+ },
+ removeChild(child) {
+ this.children = this.children.filter((item) => item !== child);
+ },
+ set id(value) {
+ this._id = value;
+ },
+ get id() {
+ return this._id;
+ },
+ };
+}
+
+function loadEventHelpers({
+ activeElement = createElement("body"),
+ selectionText = "",
+ userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
+} = {}) {
+ const source = fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/inject/event.js"),
+ "utf-8",
+ );
+
+ const eventListeners = {};
+ const elementsById = new Map();
+ const execCommandCalls = [];
+ const invokeCalls = [];
+ const body = createElement("body");
+ body.scrollHeight = 0;
+ body.appendChild = (child) => {
+ body.children.push(child);
+ if (child.id) elementsById.set(child.id, child);
+ return child;
+ };
+ body.removeChild = (child) => {
+ body.children = body.children.filter((item) => item !== child);
+ if (child.id) elementsById.delete(child.id);
+ };
+
+ const registerListener = (type, handler, options) => {
+ eventListeners[type] = eventListeners[type] || [];
+ eventListeners[type].push({ handler, options });
+ };
+
+ const context = {
+ console,
+ URL,
+ Event: class {},
+ Notification: function Notification() {},
+ setTimeout,
+ clearTimeout,
+ scrollTo: () => {},
+ navigator: {
+ userAgent,
+ language: "en-US",
+ },
+ window: {
+ history: {
+ back: () => {},
+ forward: () => {},
+ },
+ location: {
+ href: "https://example.com/app",
+ origin: "https://example.com",
+ pathname: "/app",
+ reload: () => {},
+ },
+ localStorage: {
+ getItem: () => null,
+ setItem: () => {},
+ },
+ addEventListener: registerListener,
+ dispatchEvent: () => {},
+ getSelection: () => ({
+ toString: () => selectionText,
+ removeAllRanges: vi.fn(),
+ addRange: vi.fn(),
+ }),
+ open: () => ({}),
+ isAuthLink: () => false,
+ isAuthPopup: () => false,
+ pakeConfig: {},
+ __TAURI__: {
+ core: {
+ invoke: (command, payload) => {
+ invokeCalls.push([command, payload]);
+ return Promise.resolve();
+ },
+ },
+ window: {
+ getCurrentWindow: () => ({
+ startDragging: () => {},
+ isFullscreen: () => Promise.resolve(false),
+ setFullscreen: () => {},
+ }),
+ },
+ },
+ },
+ document: {
+ addEventListener: registerListener,
+ createElement: (tagName) => {
+ const element = createElement(tagName);
+ if (element.id) elementsById.set(element.id, element);
+ return element;
+ },
+ createRange: () => ({
+ selectNodeContents: vi.fn(),
+ }),
+ getElementById: (id) => elementsById.get(id) || null,
+ getElementsByTagName: () => [{ style: {} }],
+ body,
+ activeElement,
+ execCommand: (command, showUI, value) => {
+ execCommandCalls.push([command, showUI, value]);
+ return true;
+ },
+ },
+ };
+ context.window.navigator = context.navigator;
+
+ runInNewContext(source, context);
+ eventListeners.DOMContentLoaded[0].handler();
+
+ return { ...context, eventListeners, execCommandCalls, invokeCalls };
+}
+
+function getClipboardShortcutHandler(context) {
+ return context.eventListeners.keydown.find(
+ ({ handler }) => handler.name === "handleClipboardShortcut",
+ ).handler;
+}
+
+function createKeyEvent(key, overrides = {}) {
+ return {
+ key,
+ ctrlKey: true,
+ metaKey: false,
+ altKey: false,
+ shiftKey: false,
+ preventDefault: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe("event clipboard shortcuts", () => {
+ it("copies selected page text on Windows and Linux without Tauri clipboard IPC", () => {
+ const context = loadEventHelpers({ selectionText: "selected text" });
+ const handler = getClipboardShortcutHandler(context);
+ const event = createKeyEvent("c");
+
+ handler(event);
+
+ expect(context.execCommandCalls).toEqual([["copy", undefined, undefined]]);
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(context.invokeCalls).toEqual([]);
+ });
+
+ it("cuts and selects editable text", () => {
+ const input = createElement("input");
+ input.select = vi.fn();
+ const context = loadEventHelpers({ activeElement: input });
+ const handler = getClipboardShortcutHandler(context);
+ const cutEvent = createKeyEvent("x");
+ const selectAllEvent = createKeyEvent("a");
+
+ handler(cutEvent);
+ handler(selectAllEvent);
+
+ expect(context.execCommandCalls).toEqual([["cut", undefined, undefined]]);
+ expect(input.select).toHaveBeenCalled();
+ expect(cutEvent.preventDefault).toHaveBeenCalled();
+ expect(selectAllEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("leaves paste and macOS shortcuts untouched", () => {
+ const windowsContext = loadEventHelpers();
+ const windowsHandler = getClipboardShortcutHandler(windowsContext);
+ const pasteEvent = createKeyEvent("v");
+
+ windowsHandler(pasteEvent);
+
+ const macContext = loadEventHelpers({
+ selectionText: "selected text",
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
+ });
+ const macHandler = getClipboardShortcutHandler(macContext);
+ const copyEvent = createKeyEvent("c", { metaKey: true, ctrlKey: false });
+
+ macHandler(copyEvent);
+
+ expect(pasteEvent.preventDefault).not.toHaveBeenCalled();
+ expect(copyEvent.preventDefault).not.toHaveBeenCalled();
+ expect(windowsContext.execCommandCalls).toEqual([]);
+ expect(macContext.execCommandCalls).toEqual([]);
+ });
+
+ it("does not intercept copy when there is no editable target or selected text", () => {
+ const context = loadEventHelpers();
+ const handler = getClipboardShortcutHandler(context);
+ const event = createKeyEvent("c");
+
+ handler(event);
+
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(context.execCommandCalls).toEqual([]);
+ });
+});