Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#7324: Automatically use the focused document to copy to the clipboard #7635

Merged
merged 14 commits into from
Feb 19, 2024
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
2 changes: 0 additions & 2 deletions knip.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,6 @@ const knipConfig = {
"@types/gapi.client.oauth2-v2",
// Used by Code Editor so format on save matches pre-commit behavior
"prettier",
// Used by eslint-local-rules/noCrossBoundaryImports.js
"multimatch",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No longer needed somehow

],
rules: {
// Issue Type reference: https://knip.dev/reference/issue-types/
Expand Down
4 changes: 2 additions & 2 deletions src/activation/ActivationLink.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { Form, InputGroup } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCopy } from "@fortawesome/free-solid-svg-icons";
import AsyncButton from "@/components/AsyncButton";
import { writeTextToClipboard } from "@/utils/clipboardUtils";
import { writeToClipboard } from "@/utils/clipboardUtils";
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no need for a dedicated method. Content detection can be done in one place. Before this change, text was being passed around as string or as ClipboardItem indiscriminately. This change just makes the conversion at the last moment so that text can be serialized easily.

import { createActivationUrl } from "@/activation/activationLinkUtils";

type ActivationLinkProps = {
Expand All @@ -44,7 +44,7 @@ const ActivationLink: React.FunctionComponent<ActivationLinkProps> = ({
<AsyncButton
variant="info"
onClick={async () => {
await writeTextToClipboard({ text: activationLink });
await writeToClipboard({ text: activationLink });
// Don't close the modal - that allows the user to re-copy the link and verify the link works
notify.success("Copied activation link to clipboard");
}}
Expand Down
84 changes: 84 additions & 0 deletions src/background/clipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright (C) 2024 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { lastFocusedTarget } from "@/utils/focusTracker";
import {
type Sender,
type Target,
type PageTarget,
getMethod,
} from "webext-messenger";
import { type ClipboardText } from "@/utils/clipboardUtils";

// `WRITE_TO_CLIPBOARD` can be handled by multiple contexts, that's why it's here and not in their /api.ts files
const writeToClipboardInTarget = getMethod("WRITE_TO_CLIPBOARD");

/**
* Given a `Sender` as defined by the native Chrome Messaging API,
* return a uniquely-idenfying Target usable by the Messenger.
* It returns `undefined` for tab-less HTTP senders; they must be either in tabs or chrome-extension:// pages.
*/
function extractTargetFromSender(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sender: Sender,
): Target | PageTarget | undefined {
const tabId = sender.tab?.id;
const { frameId, url } = sender;
if (tabId != null && frameId != null) {
return {
tabId,
frameId,
};
}

const rootExtensionUrl = chrome.runtime.getURL("");
if (url?.startsWith(rootExtensionUrl)) {
// Tab-less contexts like the sidePanel and dev tools
return {
page: url.replace(rootExtensionUrl, ""),
};
}

// Untargetable sender (e.g. an iframe in the sidebar, page editor, etc.)
// https://github.com/pixiebrix/pixiebrix-extension/issues/7565
}

// TODO: After the MV3 migration, just use chrome.offscreen instead
// https://developer.chrome.com/blog/Offscreen-Documents-in-Manifest-v3
// https://github.com/GoogleChrome/chrome-extensions-samples/tree/73265836c40426c004ac699a6e19b9d56590cdca/functional-samples/cookbook.offscreen-clipboard-write
export default async function writeToClipboardInFocusedContext(
Comment on lines +59 to +62
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Future API alert 🙌

The current code already works in MV3, but presumably that API will avoid the need to track focus and other guesswork.

item: ClipboardText,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the base64-to-blob parsing/validation is done a bit too early, this currently only supports copying text. Image copying will still use the modal if necessary

): Promise<boolean> {
const lastFocusedDocument = await lastFocusedTarget.get();
if (lastFocusedDocument) {
const target = extractTargetFromSender(lastFocusedDocument);
if (target) {
// The target might be any context that calls `markDocumentAsFocusableByUser`.
// Also, just because they were the lastFocusedDocument, it doesn't mean that
// they are still focused at a OS level, so this might return false.
return writeToClipboardInTarget(target, item);
}
}

// Try just getting the frontmost tab
const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
if (tab?.id != null) {
return writeToClipboardInTarget({ tabId: tab.id }, item);
}

// Dead code, there's always at least one tab, but not worth throwing
return false;
}
6 changes: 6 additions & 0 deletions src/background/messenger/strict/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ export const captureTab = getMethod("CAPTURE_TAB", bg);
export const deleteCachedAuthData = getMethod("DELETE_CACHED_AUTH", bg);
export const getCachedAuthData = getMethod("GET_CACHED_AUTH", bg);
export const setToolbarBadge = getMethod("SET_TOOLBAR_BADGE", bg);
export const documentReceivedFocus = getNotifier("DOCUMENT_RECEIVED_FOCUS", bg);

export const writeToClipboardInFocusedDocument = getMethod(
"WRITE_TO_CLIPBOARD_IN_FOCUSED_DOCUMENT",
bg,
);

export const registry = {
syncRemote: getMethod("REGISTRY_SYNC", bg),
Expand Down
6 changes: 6 additions & 0 deletions src/background/messenger/strict/registration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ import {
getCachedAuthData,
} from "@/background/auth/authStorage";
import { setToolbarBadge } from "@/background/toolbarBadge";
import { rememberFocus } from "@/utils/focusTracker";
import writeToClipboardInFocusedContext from "@/background/clipboard";
import * as registry from "@/registry/packageRegistry";

expectContext("background");
Expand All @@ -54,6 +56,8 @@ declare global {
DELETE_CACHED_AUTH: typeof deleteCachedAuthData;
GET_CACHED_AUTH: typeof getCachedAuthData;
SET_TOOLBAR_BADGE: typeof setToolbarBadge;
DOCUMENT_RECEIVED_FOCUS: typeof rememberFocus;
WRITE_TO_CLIPBOARD_IN_FOCUSED_DOCUMENT: typeof writeToClipboardInFocusedContext;
REGISTRY_SYNC: typeof registry.syncPackages;
REGISTRY_CLEAR: typeof registry.clear;
REGISTRY_GET_BY_KINDS: typeof registry.getByKinds;
Expand All @@ -77,6 +81,8 @@ export default function registerMessenger(): void {
DELETE_CACHED_AUTH: deleteCachedAuthData,
GET_CACHED_AUTH: getCachedAuthData,
SET_TOOLBAR_BADGE: setToolbarBadge,
DOCUMENT_RECEIVED_FOCUS: rememberFocus,
WRITE_TO_CLIPBOARD_IN_FOCUSED_DOCUMENT: writeToClipboardInFocusedContext,
REGISTRY_SYNC: registry.syncPackages,
REGISTRY_CLEAR: registry.clear,
REGISTRY_GET_BY_KINDS: registry.getByKinds,
Expand Down
22 changes: 9 additions & 13 deletions src/bricks/effects/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ import { BusinessError, PropError } from "@/errors/businessErrors";
import {
type ContentType,
detectContentType,
writeTextToClipboard,
writeItemsToClipboard,
writeToClipboard,
} from "@/utils/clipboardUtils";
import { convertDataUrl } from "@/utils/parseDataUrl";

Expand Down Expand Up @@ -106,6 +105,12 @@ export class CopyToClipboard extends EffectABC {
throw new BusinessError("Invalid image content", { cause: error });
}

if (blob.type !== "image/png") {
throw new BusinessError(
"Only PNG images are supported by the browser clipboard API",
);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every browser only supports image/text, image/html and image/png at the moment.


if (!("write" in navigator.clipboard)) {
throw new BusinessError(
"Your browser does not support writing images to the clipboard",
Expand All @@ -116,22 +121,13 @@ export class CopyToClipboard extends EffectABC {
logger.warn("Ignoring HTML content for image content");
}

await writeItemsToClipboard(
[
new ClipboardItem({
[blob.type]: blob,
}),
],
{
type: "image",
},
);
await writeToClipboard({ image: blob });

break;
}

case "text": {
await writeTextToClipboard({
await writeToClipboard({
text: String(text),
html,
});
Expand Down
4 changes: 2 additions & 2 deletions src/components/jsonTree/JsonTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import notify from "@/utils/notify";
import safeJsonStringify from "json-stringify-safe";
import styles from "./JsonTree.module.scss";
import AsyncButton from "@/components/AsyncButton";
import { writeTextToClipboard } from "@/utils/clipboardUtils";
import { writeToClipboard } from "@/utils/clipboardUtils";

const SEARCH_DEBOUNCE_MS = 100;

Expand Down Expand Up @@ -164,7 +164,7 @@ const CopyDataButton: React.FunctionComponent<{ data: unknown }> = ({
aria-label="copy data"
href="#"
onClick={async (event) => {
await writeTextToClipboard({ text: safeJsonStringify(data, null, 2) });
await writeToClipboard({ text: safeJsonStringify(data, null, 2) });
event.preventDefault();
event.stopPropagation();
notify.info("Copied data to the clipboard");
Expand Down
4 changes: 2 additions & 2 deletions src/components/jsonTree/treeHooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import styles from "./JsonTree.module.scss";
import cx from "classnames";
import { getPathFromArray } from "@/runtime/pathHelpers";
import AsyncButton from "@/components/AsyncButton";
import { writeTextToClipboard } from "@/utils/clipboardUtils";
import { writeToClipboard } from "@/utils/clipboardUtils";

export function useLabelRenderer() {
// https://github.com/reduxjs/redux-devtools/blob/85b4b0fb04b1d6d95054d5073fa17fa61efc0df3/packages/redux-devtools-inspector-monitor/src/ActionPreview.tsx
Expand All @@ -41,7 +41,7 @@ export function useLabelRenderer() {
aria-label="Copy path"
href="#"
onClick={async (event) => {
await writeTextToClipboard({
await writeToClipboard({
text: getPathFromArray(keyPath.reverse()),
});
event.preventDefault();
Expand Down
2 changes: 1 addition & 1 deletion src/contentScript/contentScript.scss
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,6 @@
@keyframes pixiebrix-fade-in-dialog {
from {
opacity: 0;
transform: translate3d(0, -50px, 0) scale(0.6);
transform: translate3d(0, -10px, 0) scale(0.6);
}
}
2 changes: 2 additions & 0 deletions src/contentScript/contentScriptCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
} from "./sidebarDomControllerLite";
import { isMV3 } from "@/mv3/api";
import { onContextInvalidated } from "webext-events";
import { markDocumentAsFocusableByUser } from "@/utils/focusTracker";

// Must come before the default handler for ignoring errors. Otherwise, this handler might not be run
onUncaughtError((error) => {
Expand All @@ -68,6 +69,7 @@ export async function init(): Promise<void> {
registerExternalMessenger();
registerBuiltinBricks();
registerContribBlocks();
markDocumentAsFocusableByUser();
// Since 1.8.2, the brick registry was de-coupled from the runtime to avoid circular dependencies
initRuntime(brickRegistry);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import DetailSection from "./DetailSection";
import { type Schema } from "@/types/schemaTypes";
import { useGetMarketplaceListingsQuery } from "@/services/api";
import BrickIcon from "@/components/BrickIcon";
import { writeTextToClipboard } from "@/utils/clipboardUtils";
import { writeToClipboard } from "@/utils/clipboardUtils";
import { type Metadata } from "@/types/registryTypes";
import { MARKETPLACE_URL } from "@/urlConstants";

Expand Down Expand Up @@ -94,7 +94,7 @@ const BrickDetail = <T extends Metadata>({

const copyHandler = useUserAction(
async () => {
await writeTextToClipboard({ text: makeArgumentYaml(schema) });
await writeToClipboard({ text: makeArgumentYaml(schema) });
},
{
successMessage: "Copied input argument YAML to clipboard",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { faCopy } from "@fortawesome/free-solid-svg-icons";
import notify from "@/utils/notify";
import reportEvent from "@/telemetry/reportEvent";
import { Events } from "@/telemetry/events";
import { writeTextToClipboard } from "@/utils/clipboardUtils";
import { writeToClipboard } from "@/utils/clipboardUtils";
import { useGetZapierKeyQuery } from "@/services/api";

interface OwnProps {
Expand All @@ -38,7 +38,7 @@ const ZapierIntegrationModal: React.FunctionComponent<OwnProps> = ({
const { data } = useGetZapierKeyQuery(undefined, { skip: !show });

const handleCopy = useCallback(async () => {
await writeTextToClipboard({ text: String(data?.api_key) });
await writeToClipboard({ text: String(data?.api_key) });
notify.success("Copied API Key to clipboard");
reportEvent(Events.ZAPIER_KEY_COPY);
}, [data?.api_key]);
Expand Down
28 changes: 20 additions & 8 deletions src/mv3/SessionStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,22 @@
*/

import { expectContext } from "@/utils/expectContext";
import { type JsonValue } from "type-fest";
import { type OmitIndexSignature, type JsonValue } from "type-fest";
import { type ManualStorageKey } from "@/utils/storageUtils";
import { once } from "lodash";

// Just like chrome.storage.session, this must be "global"
// eslint-disable-next-line local-rules/persistBackgroundData -- MV2-only
const storage = new Map<ManualStorageKey, JsonValue>();

// eslint-disable-next-line local-rules/persistBackgroundData -- Static
const hasSession = "session" in chrome.storage;
function validateContext(): void {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

expectContext(
"background",
"This polyfill doesn’t share data across contexts; only use it in the background page",
);
}

/**
* MV3-compatible Map-like storage, this helps transition to chrome.storage.session
Expand All @@ -41,18 +48,18 @@ export class SessionMap<Value extends JsonValue> {
constructor(
private readonly key: string,
private readonly url: ImportMeta["url"],
) {
expectContext(
"background",
"This polyfill doesn’t share data across contexts; only use it in the background page",
);
}
) {}

// Do not call `expectContext` in the constructor so that `SessionMap` can be
// instantiated at the top level and still be imported (but unused) in other contexts.
private readonly validateContext = once(validateContext);

private getRawStorageKey(secondaryKey: string): ManualStorageKey {
return `${this.key}::${this.url}::${secondaryKey}` as ManualStorageKey;
}

async get(secondaryKey: string): Promise<Value | undefined> {
this.validateContext();
const rawStorageKey = this.getRawStorageKey(secondaryKey);
if (!hasSession) {
return storage.get(rawStorageKey) as Value | undefined;
Expand All @@ -64,6 +71,8 @@ export class SessionMap<Value extends JsonValue> {
}

async set(secondaryKey: string, value: Value): Promise<void> {
this.validateContext();

const rawStorageKey = this.getRawStorageKey(secondaryKey);
if (hasSession) {
await browser.storage.session.set({ [rawStorageKey]: value });
Expand All @@ -73,6 +82,8 @@ export class SessionMap<Value extends JsonValue> {
}

async delete(secondaryKey: string): Promise<void> {
this.validateContext();

const rawStorageKey = this.getRawStorageKey(secondaryKey);
if (hasSession) {
await browser.storage.session.remove(rawStorageKey);
Expand All @@ -86,7 +97,8 @@ export class SessionMap<Value extends JsonValue> {
* MV3-compatible single-value storage.
* This helps transition to chrome.storage.session and provide some type safety.
*/
export class SessionValue<Value extends JsonValue> {
// "OmitIndexSignature" is because of https://github.com/sindresorhus/type-fest/issues/815
export class SessionValue<Value extends OmitIndexSignature<JsonValue>> {
private readonly map: SessionMap<Value>;

constructor(key: string, url: ImportMeta["url"]) {
Expand Down
2 changes: 2 additions & 0 deletions src/sidebar/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { initPerformanceMonitoring } from "@/telemetry/performance";
import { initSidePanel } from "./sidePanel";
import { getConnectedTarget } from "@/sidebar/connectedTarget";
import { sidebarWasLoaded } from "@/contentScript/messenger/strict/api";
import { markDocumentAsFocusableByUser } from "@/utils/focusTracker";

async function init(): Promise<void> {
ReactDOM.render(<App />, document.querySelector("#container"));
Expand All @@ -53,6 +54,7 @@ registerBuiltinBricks();
initToaster();
void init();
initSidePanel();
markDocumentAsFocusableByUser();

// Handle an embedded AA business copilot frame
void initCopilotMessenger();
Loading
Loading