Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ To verify a download on Linux, run `sha256sum --ignore-missing -c SHA256SUMS` in
## Features

- Capture a page’s main content as Markdown, with its title, URL, and readable description.
- Save selected text with the Memos button next to the end of the selection.
- Convert selected text, links, lists, code, and tables to Markdown.
- Upload selected images as Memos attachments.
- Review and edit every clip before saving.
Expand Down Expand Up @@ -69,6 +70,8 @@ For a direct connection, create a PAT in your Memos user settings at `/setting#a

You can also right-click selected text or an image and choose **Save selection to Memos**. Context-menu saves are always private.

Select text on a webpage to show a Memos button next to the end of the selection. Click it to save the excerpt with its source link. The button uses the same template, attachments, and save feedback as the context menu. It hides when the selection clears and stays hidden in text editors and input fields.

Browser-owned pages, such as extension stores and internal browser URLs, may block page capture. The clipper falls back to the page title and URL when available.

## Local history
Expand Down
18 changes: 18 additions & 0 deletions src/__tests__/background.dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,24 @@ describe("background — onInstalled", () => {
});

describe("background — context menu quick save", () => {
it("saves a captured selection from a content button through the quick-save flow", async () => {
ready();
seedStorage({ [CLIP_TEMPLATE_KEY]: "{{content}}\n\nSource: {{url}}" });
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ name: "memos/7", uid: "xy" }));
vi.stubGlobal("fetch", fetchMock);
await browserMock.runtime.onMessage.emitFirst(
{ type: "SAVE_SELECTION", clip: { markdown: "**Captured text**", images: [] } },
{ id: "test-id", url: "https://example.com/post", tab: { id: 5, title: "Post" }, frameId: 0 },
);
expect(JSON.parse(fetchMock.mock.calls[0]![1].body)).toMatchObject({
content: "**Captured text**\n\nSource: https://example.com/post",
visibility: "PRIVATE",
});
expect(browserMock.tabs.sendMessage).not.toHaveBeenCalledWith(5, { type: "GET_SELECTION" });
expect(browserMock.tabs.sendMessage).toHaveBeenCalledWith(5, { type: "CLEAR_SELECTION" });
expect(browserMock.action.setBadgeText).toHaveBeenCalledWith({ text: "✓" });
});

const click = () =>
browserMock.contextMenus.onClicked.emit(
{ menuItemId: "save-selection", selectionText: "clip me", pageUrl: "https://example.com/post" },
Expand Down
18 changes: 18 additions & 0 deletions src/__tests__/content.dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import frenchMessages from "../../public/_locales/fr/messages.json" with { type:
// Content script registers its message listeners on the shared browser mock at import.
beforeEach(async () => {
await import("@/content");
window.getSelection()?.removeAllRanges();
document.title = "Test Article";
document.body.innerHTML = "<article><h1>Headline</h1><p>Some body copy here.</p></article>";
});
Expand Down Expand Up @@ -88,6 +89,23 @@ describe("content script — CLEAR_SELECTION", () => {
});

describe("content script — GET_SELECTION", () => {
it("caps long page metadata before it enters a selection save request", async () => {
const meta = document.createElement("meta");
meta.name = "description";
meta.content = "x".repeat(9_000);
document.head.append(meta);
const range = document.createRange();
range.selectNodeContents(document.querySelector("p")!);
window.getSelection()?.removeAllRanges();
window.getSelection()?.addRange(range);
try {
const result = (await browserMock.runtime.onMessage.emitFirst({ type: "GET_SELECTION" })) as { description: string };
expect(result.description).toHaveLength(500);
} finally {
meta.remove();
}
});

it("parses selected markup inertly and resolves relative image attachments", async () => {
document.body.innerHTML = '<p>Hello<script>window.bad = true</script><img src="/clip.png" alt="clip"></p>';
const range = document.createRange();
Expand Down
11 changes: 10 additions & 1 deletion src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ async function activateConnection(verify: () => Promise<VerifiedConnection>) {
browser.runtime.onMessage.addListener((message: unknown, sender: RuntimeSender) => {
const req = parseBackgroundRequest(message);
if (!req || !isTrustedBackgroundRequest(req, sender, browser.runtime.id)) return undefined;
if (req.type === "SAVE_SELECTION") return quickSaveSelection(Promise.resolve(req.clip), sender.tab, { pageUrl: sender.url });
if (req.type === "GET_POPUP_STATE") return reconcilePopupState();
if (req.type === "LIST_SPACES") {
return (async (): Promise<SpacesResult> => {
Expand Down Expand Up @@ -316,6 +317,14 @@ browser.contextMenus.onClicked.addListener(async (info, tab) => {
? Promise.resolve({ markdown: "", images: [info.srcUrl] }) // a bare image is just a clip with one image
: getSelectionClip(tab?.id, selectionText ?? "");

await quickSaveSelection(clipPromise, tab, info);
});

async function quickSaveSelection(
clipPromise: Promise<SelectionClip>,
tab: { id?: number; title?: string; url?: string } | undefined,
info: { pageUrl?: string },
): Promise<void> {
// The item follows the same gate as the popup. When a setup gate isn't met we open the place
// that resolves it (opening the tab is the feedback).
let result: SaveResult;
Expand Down Expand Up @@ -356,7 +365,7 @@ browser.contextMenus.onClicked.addListener(async (info, tab) => {
result.ok ? flashBadge("✓", BADGE_SUCCESS) : flashBadge("!", BADGE_DANGER),
showSaveResultInTab(tab?.id, result, source),
]);
});
}

/** Maps a throw from the quick-save gate to user-facing copy; unknown errors are the extension's own fault, not the instance's. */
function quickSaveErrorKind(error: unknown): SaveErrorKind {
Expand Down
33 changes: 31 additions & 2 deletions src/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ async function clipSelection(): Promise<SelectionClip> {
for (const img of imgs) img.remove();
// Turndown is loaded lazily: this script runs on every page, but markdown conversion is only
// needed on the rare context-menu save — keep the per-page cost to this thin shell.
const { htmlToMarkdown } = await import("@/lib/format");
const { htmlToMarkdown, DESCRIPTION_MAX_CHARS } = await import("@/lib/format");
// Same {{description}} source as the popup capture, so both paths compose identically.
const normalized = (value: string | null | undefined) => value?.replace(/\s+/g, " ").trim() || undefined;
const meta = (s: string) => normalized(document.querySelector<HTMLMetaElement>(s)?.content);
Expand All @@ -55,7 +55,7 @@ async function clipSelection(): Promise<SelectionClip> {
return undefined;
};
const description = meta('meta[property="og:description"]') ?? meta('meta[name="description"]') ?? firstReadableParagraph();
return { markdown: htmlToMarkdown(container.innerHTML), images, description };
return { markdown: htmlToMarkdown(container.innerHTML), images, description: description?.slice(0, DESCRIPTION_MAX_CHARS) };
}

let toastHost: HTMLElement | null = null;
Expand Down Expand Up @@ -144,8 +144,37 @@ browser.runtime.onMessage.addListener((message: unknown) => {
if (req?.type === "CLEAR_SELECTION") {
// Drop the highlight and unfocus after a save so the page returns to a clean state.
window.getSelection()?.removeAllRanges();
void selectionButton?.then((button) => button.update()).catch(() => {});
(document.activeElement as HTMLElement | null)?.blur?.();
return undefined;
}
return undefined;
});

let selectionButton: Promise<ReturnType<typeof import("@/content/selection-save").createSelectionSaveButton>> | undefined;

function updateSelectionButton(): void {
if (!selectionButton && !window.getSelection()?.toString().trim()) return;
selectionButton ??= import("@/content/selection-save")
.then(({ createSelectionSaveButton }) =>
createSelectionSaveButton(async () => {
try {
const clip = await clipSelection();
if (!clip.markdown.trim()) return;
const request: Request = { type: "SAVE_SELECTION", clip };
await browser.runtime.sendMessage(request);
} catch {
showSaveToast({ ok: false, title: browser.i18n.getMessage("errorExtensionTitle") });
}
}),
)
.catch((error) => {
selectionButton = undefined;
throw error;
});
void selectionButton.then((button) => button.update()).catch(() => {});
}

document.addEventListener("selectionchange", updateSelectionButton);
document.addEventListener("pointerup", updateSelectionButton);
document.addEventListener("keyup", updateSelectionButton);
93 changes: 93 additions & 0 deletions src/content/__tests__/selection-save.dom.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { act, fireEvent, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createSelectionSaveButton } from "@/content/selection-save";

describe("selection save button", () => {
let control: ReturnType<typeof createSelectionSaveButton>;
let save: ReturnType<typeof vi.fn<() => Promise<void>>>;

beforeEach(() => {
document.body.innerHTML = "<p>An excerpt to save.</p><textarea>Draft</textarea>";
window.getSelection()?.removeAllRanges();
if (!Range.prototype.getClientRects) Range.prototype.getClientRects = vi.fn();
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({ width: 24, height: 24 } as DOMRect);
vi.spyOn(Range.prototype, "getClientRects").mockReturnValue([
{ left: 100, right: 180, top: 80, bottom: 100, width: 80, height: 20 },
] as unknown as DOMRectList);
save = vi.fn().mockResolvedValue(undefined);
control = createSelectionSaveButton(save);
});

afterEach(() => {
act(() => control?.destroy());
vi.restoreAllMocks();
});

const select = () => {
const range = document.createRange();
range.selectNodeContents(document.querySelector("p")!);
window.getSelection()?.addRange(range);
act(() => control.update());
};
const button = () => document.querySelector("[data-memos-selection-save]")?.shadowRoot?.querySelector("button");

it("shows a named Memos button next to selected text", async () => {
expect(button()).toBeFalsy();
select();
await waitFor(() => expect(button()?.getAttribute("aria-label")).toBe("Save selection to Memos"));
const host = document.querySelector<HTMLElement>("[data-memos-selection-save]")!;
expect(host.style.left).toBe("188px");
expect(host.style.top).toBe("80px");
});

it("preserves the selection on pointer press and rejects page-generated clicks", async () => {
select();
await waitFor(() => expect(button()).toBeTruthy());
expect(fireEvent.pointerDown(button()!)).toBe(false);
expect(fireEvent.mouseDown(button()!)).toBe(false);
expect(window.getSelection()?.toString()).toBe("An excerpt to save.");
await act(async () => {
fireEvent.click(button()!);
fireEvent.click(button()!);
});
expect(save).not.toHaveBeenCalled();
});

it("hides the button when the selection clears", async () => {
select();
await waitFor(() => expect(button()).toBeTruthy());
window.getSelection()?.removeAllRanges();
act(() => control.update());
expect(document.querySelector("[data-memos-selection-save]")).toBeNull();
});

it("does not show a button while the user edits text", () => {
document.querySelector("p")!.setAttribute("contenteditable", "true");
select();
expect(button()).toBeFalsy();
});

it("hides a selection outside the viewport", () => {
vi.spyOn(Range.prototype, "getClientRects").mockReturnValue([
{ left: 100, right: 180, top: -100, bottom: -80, width: 80, height: 20 },
] as unknown as DOMRectList);
select();
expect(button()).toBeFalsy();
});

it("places the button after an RTL selection", () => {
document.querySelector("p")!.style.direction = "rtl";
select();
expect(document.querySelector<HTMLElement>("[data-memos-selection-save]")!.style.left).toBe("68px");
});

it("keeps the button within the viewport at the right edge", () => {
vi.spyOn(Range.prototype, "getClientRects").mockReturnValue([
{ left: 1000, right: 1020, top: 80, bottom: 100, width: 20, height: 20 },
] as unknown as DOMRectList);
select();
const host = document.querySelector<HTMLElement>("[data-memos-selection-save]")!;
expect(host.style.left).toBe("992px");
expect(host.style.top).toBe("108px");
});
});
123 changes: 123 additions & 0 deletions src/content/selection-save.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { Button, Tooltip } from "@usememos/ui";
import styles from "@usememos/ui/styles.css?inline";
import tokens from "@usememos/ui/tokens.css?inline";
import { createRoot } from "react-dom/client";
import browser from "webextension-polyfill";
import markUrl from "../../assets/brand/mark-small.svg";

const EDITABLE_SELECTOR = 'input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role="textbox"]';

function selectionEnd(): DOMRect | null {
const selection = window.getSelection();
if (!selection || selection.isCollapsed || !selection.rangeCount || !selection.toString().trim()) return null;
if (document.activeElement?.closest(EDITABLE_SELECTOR)) return null;
const range = selection.getRangeAt(selection.rangeCount - 1);
for (const node of [range.startContainer, range.endContainer]) {
const element = node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
if (element?.closest(EDITABLE_SELECTOR)) return null;
}
const endpoint = range.cloneRange();
endpoint.collapse(false);
const rect = Array.from(endpoint.getClientRects()).find((item) => item.height > 0) ?? Array.from(range.getClientRects()).at(-1);
if (!rect || rect.height <= 0 || rect.bottom < 0 || rect.top > window.innerHeight || rect.right < 0 || rect.left > window.innerWidth) {
return null;
}
return rect;
}

/** https://developer.mozilla.org/en-US/docs/Web/API/Range/getClientRects */
export function createSelectionSaveButton(onSave: () => Promise<void>) {
const host = document.createElement("div");
host.dataset.memosSelectionSave = "";
host.style.cssText = "all:initial;position:fixed;z-index:2147483647;";
const shadow = host.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = `${tokens}\n${styles}`;
const mount = document.createElement("div");
mount.className = "mu-root";
shadow.append(style, mount);
const root = createRoot(mount);
let saving = false;
let destroyed = false;

const render = () => {
const label = browser.i18n.getMessage("contextMenuSaveSelection");
mount.dataset.theme = window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
root.render(
<Tooltip.Provider>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
size="sm"
aria-label={label}
loading={saving}
loadingLabel={label}
icon={
<span
aria-hidden="true"
style={{
display: "block",
width: "var(--mu-row-icon)",
height: "var(--mu-row-icon)",
background: "currentColor",
mask: `url("${markUrl}") center / contain no-repeat`,
}}
/>
}
onPointerDown={(event) => event.preventDefault()}
onMouseDown={(event) => event.preventDefault()}
onClick={(event) => {
event.stopPropagation();
if (!event.isTrusted || saving) return;
saving = true;
render();
const finish = () => {
saving = false;
if (!destroyed) render();
};
void onSave().then(finish, finish);
}}
/>
}
/>
<Tooltip.Popup container={mount}>{label}</Tooltip.Popup>
</Tooltip.Root>
</Tooltip.Provider>,
);
};

const update = () => {
if (destroyed) return;
const rect = selectionEnd();
if (!rect) {
host.remove();
return;
}
if (!host.isConnected) document.documentElement.append(host);
const css = getComputedStyle(mount);
const size = Number.parseFloat(css.getPropertyValue("--mu-control-sm")) || host.getBoundingClientRect().width;
const gap = Number.parseFloat(css.getPropertyValue("--mu-space-2")) || 8;
const range = window.getSelection()!.getRangeAt(0);
const parent = range.endContainer.nodeType === Node.ELEMENT_NODE ? (range.endContainer as Element) : range.endContainer.parentElement;
const rtl = parent && getComputedStyle(parent).direction === "rtl";
const left = rtl ? rect.left - size - gap : rect.right + gap;
const top = left < gap || left + size + gap > window.innerWidth ? rect.bottom + gap : rect.top;
host.style.left = `${Math.max(gap, Math.min(left, window.innerWidth - size - gap))}px`;
host.style.top = `${Math.max(gap, Math.min(top, window.innerHeight - size - gap))}px`;
render();
};

window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return {
update,
destroy() {
destroyed = true;
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
root.unmount();
host.remove();
},
};
}
Loading