Skip to content
Merged
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
14 changes: 11 additions & 3 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,21 @@ Plucking a URL that is already in your library. It brings the existing Item back
_Avoid_: Duplicate, re-save

**Item**:
One plucked thing. Link Items have a URL and a kept page; Notes, Todos and Things are Items with no URL.
One plucked thing. Link Items have a URL and a kept page, except an Image or PDF plucked as a file, which has neither; Notes, Todos and Things are Items with no URL.
_Avoid_: Save, bookmark, entry, card

**Kind**:
What an Item is: Read, Watch, PDF, Image, Note, Todo or Thing. "Links" is the group of Read, Watch, PDF and Image.
_Avoid_: Type, category

**Note**:
An Item of your own words, typed or dictated. Not the note on a link Item, a List entry or a Highlight, which is a short comment on something else.
_Avoid_: Memo, doc, page

**Found on**:
The web page an Image was plucked from, kept with it as the way back.
_Avoid_: Source, origin, referrer

**Kept page**:
What is worth keeping from a link Item's page, stored with it so it survives the original going away: an article's text and HTML, a post's words, a repo's README, a product's name and price. Never a login wall or an empty app shell.
_Avoid_: Snapshot, cache, archive copy
Expand All @@ -39,11 +47,11 @@ Where an Item sits in triage: Inbox (untriaged), Later (kept on purpose), Archiv
_Avoid_: State, folder

**Tag**:
A short label you made. A Tag your AI made carries a "by AI" mark until you touch it.
A short label you made, from a picker or by writing `#word` in a Note or a note. A Tag your AI made carries a "by AI" mark until you touch it.
_Avoid_: Label, category, smart tag

**List**:
A named, ordered group of Items with a purpose line. Each Item in a List has its own note and tick, which belong to the List, not the Item. Private or Public.
A named, ordered group of Items with a purpose line. Each Item in a List has its own note and tick, which belong to the List, not the Item. Private or Public. The first place a pluck can be put, ahead of Tags; an account starts with two, Favourites and Ideas.
_Avoid_: Collection, folder, board, playlist

**Tick**:
Expand Down
4 changes: 2 additions & 2 deletions apps/extension/entrypoints/background.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { finishSignIn } from "@/lib/auth";
import { drain, pluckForPopup, pluckTab, pluckUrl, refreshBadge, resume, type PluckOutcome } from "@/lib/pluck";
import { drain, pluckForPopup, pluckImage, pluckTab, pluckUrl, refreshBadge, resume, type PluckOutcome } from "@/lib/pluck";
import { settings } from "@/lib/store";
import { t } from "@/lib/t";

Expand Down Expand Up @@ -48,7 +48,7 @@ async function onMenu(info: MenuClick, tab?: { id?: number; url?: string; title?
case "pluck-link":
return info.linkUrl ? pluckUrl(info.linkUrl) : null;
case "pluck-image":
return info.srcUrl ? pluckUrl(info.srcUrl) : null;
return info.srcUrl ? pluckImage(info.srcUrl, tab) : null;
case "pluck-selection":
return tab ? pluckTab(tab, { asHighlight: true }) : null;
case "pluck-page":
Expand Down
84 changes: 67 additions & 17 deletions apps/extension/entrypoints/popup/Popup.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Item, Kind, List, PluckResponse, Status, Tag } from "@pluck/shared-schemas";
import type { Item, Kind, List, ListMembership, PluckResponse, Status, Tag } from "@pluck/shared-schemas";
import { KindGlyph, Logo } from "@pluck/ui";
import { useEffect, useState, type ReactNode } from "react";
import { useFormatter, useTranslations } from "use-intl";
Expand Down Expand Up @@ -173,7 +173,8 @@ function Shell({ children }: { children: ReactNode }) {
);
}

// One panel for a page in the library, plucked just now or weeks ago: tags, Kind, a List, a note, where it goes next.
// One panel for a page in the library, plucked just now or weeks ago: its Lists first (the place it goes), then tags,
// Kind, a note, where it goes next.
function ItemPanel({ initial, fresh, tips, remove }: { initial: Item; fresh: boolean; tips: boolean; remove: (item: Item) => void }) {
const t = useTranslations("extension");
const format = useFormatter();
Expand All @@ -183,7 +184,9 @@ function ItemPanel({ initial, fresh, tips, remove }: { initial: Item; fresh: boo
const [lastListId, setLastListId] = useState<string | null>(null);
const [filter, setFilter] = useState("");
const [note, setNote] = useState(initial.note ?? "");
const [listId, setListId] = useState("");
const [inLists, setInLists] = useState<Set<string>>(new Set());
const [naming, setNaming] = useState<string | null>(null); // the name of a List being made; null: not making one
const [allLists, setAllLists] = useState(false);
const [tabCount, setTabCount] = useState(0);
const [footer, setFooter] = useState<string | null>(null);
const [keys, setKeys] = useState("");
Expand All @@ -193,10 +196,17 @@ function ItemPanel({ initial, fresh, tips, remove }: { initial: Item; fresh: boo
api<{ tags: Tag[] }>("/api/v1/tags").then((r) => setTags(r.tags)).catch(() => {});
api<{ lists: List[] }>("/api/v1/lists").then((r) => setLists(r.lists)).catch(() => {});
get("lastListId").then(setLastListId);
// A page plucked just now is in no List yet; one from before shows the Lists it is in.
if (!fresh) api<{ lists: ListMembership[] }>(`/api/v1/items/${initial.id}?include=lists`).then((r) => setInLists(new Set(r.lists.map((m) => m.list.id)))).catch(() => {});
browser.tabs.query({ currentWindow: true }).then((t) => setTabCount(t.length));
}, []);

const patch = async (body: Record<string, unknown>) => setItem((await api<{ item: Item }>(`/api/v1/items/${item.id}`, { method: "PATCH", json: body })).item);
const patch = async (body: Record<string, unknown>) => {
const { item: saved } = await api<{ item: Item }>(`/api/v1/items/${item.id}`, { method: "PATCH", json: body });
setItem(saved);
// A #tag in the note may have made a tag this popup has not heard of: read them again so its chip shows.
if (saved.tagIds.some((id) => !tags.some((t) => t.id === id))) api<{ tags: Tag[] }>("/api/v1/tags").then((r) => setTags(r.tags)).catch(() => {});
};
const move = async (status: Status) => {
await patch({ status });
window.close();
Expand All @@ -220,14 +230,35 @@ function ItemPanel({ initial, fresh, tips, remove }: { initial: Item; fresh: boo
...tags.filter((t) => item.tagIds.includes(t.id)),
...tags.filter((t) => !item.tagIds.includes(t.id) && t.name.toLowerCase().includes(typed.toLowerCase())),
].slice(0, 8);
const orderedLists = [...lists].sort((a, b) => Number(b.id === lastListId) - Number(a.id === lastListId));
// The Lists it is in, then the one used last, then the rest as the server orders them (last touched first).
const rank = (l: List) => (inLists.has(l.id) ? 2 : l.id === lastListId ? 1 : 0);
// Every List it is in always shows (so it can be taken out); the rest fill up to six, and "More" shows them all.
const ranked = [...lists].sort((a, b) => rank(b) - rank(a));
const shownLists = allLists ? ranked : ranked.slice(0, Math.max(6, inLists.size));
const listName = t("popup.tabs.listName", { date: format.dateTime(new Date(), DAY_MONTH) });

const addToList = async (id: string) => {
setListId(id);
if (!id) return;
await api(`/api/v1/lists/${id}/items`, { json: { itemId: item.id } });
await set({ lastListId: id });
// On and off again, like a tag. The chip changes at once and goes back if the server says no.
const toggleList = async (id: string) => {
const on = !inLists.has(id);
const flip = (to: boolean) => setInLists((cur) => { const next = new Set(cur); if (to) next.add(id); else next.delete(id); return next; });
flip(on);
try {
if (on) await api(`/api/v1/lists/${id}/items`, { json: { itemId: item.id } });
else await api(`/api/v1/lists/${id}/items/${item.id}`, { method: "DELETE" });
if (on) await set({ lastListId: id });
} catch {
flip(!on);
}
};
// Enter, or leaving the field: a name makes the List with this Item in it; no name goes back to the chips.
const makeList = async () => {
const name = naming?.trim();
setNaming(null);
if (!name) return;
const { list } = await api<{ list: List }>("/api/v1/lists", { json: { name, items: [{ itemId: item.id }] } });
setLists((all) => [list, ...all]);
setInLists((cur) => new Set(cur).add(list.id));
await set({ lastListId: list.id });
};

const pluckAllTabs = async () => {
Expand Down Expand Up @@ -277,6 +308,32 @@ function ItemPanel({ initial, fresh, tips, remove }: { initial: Item; fresh: boo
) : (
<>
<div className="body">
<div className="field" role="group" aria-label={t("popup.plucked.lists")}>
<span className="label">{t("popup.plucked.lists")}</span>
{naming === null ? (
<div className="chips">
{shownLists.map((l) => (
<button key={l.id} type="button" className="chip" aria-pressed={inLists.has(l.id)} onClick={() => void toggleList(l.id)}>{l.name}</button>
))}
{ranked.length > shownLists.length && (
<button type="button" className="chip new" onClick={() => setAllLists(true)}>{t("popup.plucked.moreLists", { count: ranked.length - shownLists.length })}</button>
)}
<button type="button" className="chip new" onClick={() => setNaming("")}>{t("popup.plucked.newList")}</button>
</div>
) : (
<input
type="text"
autoFocus
aria-label={t("popup.plucked.newList")}
placeholder={t("popup.plucked.newListPlaceholder")}
value={naming}
maxLength={120}
onChange={(e) => setNaming(e.target.value)}
onBlur={() => void makeList().catch(() => {})}
onKeyDown={(e) => e.key === "Enter" && (e.currentTarget as HTMLInputElement).blur()}
/>
)}
</div>
<label className="field">
<span className="label">{t("popup.plucked.tags")}</span>
<input
Expand Down Expand Up @@ -312,13 +369,6 @@ function ItemPanel({ initial, fresh, tips, remove }: { initial: Item; fresh: boo
</button>
))}
</div>
<label className="inline-field">
<span className="label list-label">{t("popup.plucked.toList")}</span>
<select value={listId} onChange={(e) => void addToList(e.target.value)}>
<option value="">{t("popup.plucked.noList")}</option>
{orderedLists.map((l) => <option key={l.id} value={l.id}>{l.id === lastListId ? t("popup.plucked.lastUsed", { name: l.name }) : l.name}</option>)}
</select>
</label>
<label className="note">
<span className="visually-hidden">{t("popup.plucked.note")}</span>
<input
Expand Down
4 changes: 1 addition & 3 deletions apps/extension/entrypoints/popup/popup.css
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,13 @@ body { width: 360px; }
input[type="text"], select { height: 36px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--line-strong); background: var(--surface); font-size: 13px; }
select { padding: 0 8px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: -4px; }
.field > .chips { margin-top: 0; } /* the Lists: chips under their own label, with no field between */
.chip { height: 28px; padding: 0 10px; border-radius: 14px; border: 0; background: var(--chip); font-size: 12px; }
.chip[aria-pressed="true"] { background: var(--brand); color: var(--on-brand); }
.chip.new { background: none; border: 1px dashed var(--line-strong); color: var(--ink2); }
.kinds { display: flex; gap: 4px; }
.kind { width: 32px; height: 36px; border-radius: 8px; border: 1px solid var(--line-strong); background: var(--surface); display: flex; align-items: center; justify-content: center; padding: 0; color: var(--ink); }
.kind[aria-pressed="true"] { background: var(--ink); border-color: var(--ink); color: var(--ground); }
.inline-field { display: flex; align-items: center; gap: 8px; }
.inline-field select { flex: 1; min-width: 0; }
.list-label { width: 44px; flex: none; }
.note { display: flex; }
.note input { flex: 1; }
.actions { display: flex; gap: 6px; }
Expand Down
48 changes: 48 additions & 0 deletions apps/extension/lib/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,51 @@ export async function screenshot(windowId: number): Promise<Blob | null> {
return null;
}
}

// The picture from the tab, for an image the server cannot fetch (it sits behind your sign-in). First its own bytes,
// fetched by the page with your session, which works where the image's server lets its page fetch it. Else what the
// tab shows: where the image is on screen, a capture of the tab, and the one cut to the other. Null when neither
// can be had: the image is out of view or in a frame, or the page may not be read.
const COVER_TYPES = ["image/jpeg", "image/png", "image/webp"]; // what PUT /items/:id/cover takes, up to 2 MB
export async function pictureInTab(tabId: number, windowId: number, src: string): Promise<Blob | null> {
try {
const [found] = await browser.scripting.executeScript({
target: { tabId },
args: [src, COVER_TYPES],
func: async (src: string, types: string[]) => {
try {
const res = await fetch(src, { credentials: "include" });
const bytes = res.ok ? await res.blob() : null;
if (bytes && types.includes(bytes.type) && bytes.size <= 2_000_000) {
const url = await new Promise<string>((done, failed) => {
const reader = new FileReader();
reader.onload = () => done(String(reader.result));
reader.onerror = () => failed(reader.error);
reader.readAsDataURL(bytes);
});
return { url };
}
} catch {
// not ours to fetch from here: the capture below
}
const img = [...document.images].find((i) => i.currentSrc === src || i.src === src);
if (!img) return null;
const r = img.getBoundingClientRect();
const x = Math.max(0, r.left);
const y = Math.max(0, r.top);
const w = Math.min(innerWidth, r.right) - x;
const h = Math.min(innerHeight, r.bottom) - y;
return w > 8 && h > 8 ? { x, y, w, h, scale: devicePixelRatio } : null;
},
});
const at = found?.result as { url: string } | { x: number; y: number; w: number; h: number; scale: number } | null | undefined;
if (!at) return null;
if ("url" in at) return await (await fetch(at.url)).blob();
const shot = await createImageBitmap(await (await fetch(await browser.tabs.captureVisibleTab(windowId, { format: "png" }))).blob());
const canvas = new OffscreenCanvas(Math.round(at.w * at.scale), Math.round(at.h * at.scale));
canvas.getContext("2d")!.drawImage(shot, Math.round(at.x * at.scale), Math.round(at.y * at.scale), canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
return await canvas.convertToBlob({ type: "image/jpeg", quality: 0.9 });
} catch {
return null;
}
}
19 changes: 17 additions & 2 deletions apps/extension/lib/pluck.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { CreateItemBody, Item, PluckResponse } from "@pluck/shared-schemas";
import { api, Refused, Unreachable } from "./api";
import { isSignedIn } from "./auth";
import { capture, screenshot } from "./capture";
import { capture, pictureInTab, screenshot } from "./capture";
import { createQueue } from "@pluck/client";
import { get, set, settings } from "./store";
import { t } from "./t";
Expand Down Expand Up @@ -52,9 +52,24 @@ export function pluckForPopup(message: unknown, _sender: unknown, respond: (outc
return true;
}

// A link, an image or a URL: no page to read, the server fetches it.
// A link or a URL: no page to read, the server fetches it.
export const pluckUrl = (url: string) => send({ url, source: "extension" });

// An image from the right-click menu: by its address, with the page it was found on. One the server cannot fetch (a
// feed behind your sign-in refuses it, or answers with its sign-in page) comes back unread, or as something that is
// no Image: then the picture goes up from the tab (pictureInTab), and the Item is an Image all the same.
// shortcut: up to 2 MB, and a capture is the size the picture is on screen; a bigger original stays unread, send it through the file upload when feeds serve such.
export async function pluckImage(src: string, tab?: { id?: number; url?: string; windowId?: number }): Promise<PluckOutcome> {
const outcome = await send({ url: src, source: "extension", ...(isWeb(tab?.url) ? { foundOn: tab!.url } : {}) });
if (outcome.state !== "plucked" || tab?.id === undefined || tab.windowId === undefined) return outcome;
const { kind, extraction } = outcome.item;
if (!(extraction.state === "failed" || (extraction.state === "done" && kind !== "image"))) return outcome;
const picture = await pictureInTab(tab.id, tab.windowId, src);
if (!picture || picture.size > 2_000_000) return outcome;
const kept = await api<{ item: Item }>(`/api/v1/items/${outcome.item.id}/cover?as=picture`, { method: "PUT", body: picture, contentType: picture.type }).catch(() => null);
return kept ? { ...outcome, item: kept.item } : outcome;
}

export async function send(body: CreateItemBody): Promise<PluckOutcome> {
try {
const res = await api<PluckResponse>("/api/v1/items", { json: body });
Expand Down
2 changes: 1 addition & 1 deletion apps/extension/store/listing.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Pluck saves the web page, link, image or text selection you choose into your own
| Permission | Justification |
|---|---|
| `activeTab` | When you click Pluck or press its shortcut, it reads the address, title and text of the tab you are on, so the item is kept as you see it. |
| `scripting` | Runs once in the tab you pluck, after you click, to read the rendered page, your selected text and, on YouTube, the transcript. |
| `scripting` | Runs once in the tab you pluck, after you click, to read the rendered page, your selected text and, on YouTube, the transcript. For "Pluck image" on a picture Pluck's server cannot open (one behind your sign-in), it reads that picture from the page. |
| `tabs` | Reads the address of your open tabs, so the Pluck icon fills in on pages already in your library and "Pluck all tabs" can list them. Only the address is read, never the page. |
| `contextMenus` | Adds "Pluck link", "Pluck image", "Pluck page" and "Pluck selection as highlight" to the right-click menu. |
| `storage` | Keeps your sign-in, your settings and any plucks waiting for a connection on your computer. |
Expand Down
Loading
Loading