Add better clipboard api support detection

This commit is contained in:
Mitchell McCaffrey 2021-08-06 14:24:35 +10:00
parent d691105fcb
commit aa36587a53
2 changed files with 28 additions and 2 deletions

View File

@ -34,6 +34,7 @@ import { isSelection } from "../../validators/Selection";
import { getRelativePointerPosition } from "../../helpers/konva"; import { getRelativePointerPosition } from "../../helpers/konva";
import { useKeyboard } from "../../contexts/KeyboardContext"; import { useKeyboard } from "../../contexts/KeyboardContext";
import shortcuts from "../../shortcuts"; import shortcuts from "../../shortcuts";
import { clipboardSupported } from "../../helpers/shared";
type SelectionMenuProps = { type SelectionMenuProps = {
isOpen: boolean; isOpen: boolean;
@ -275,7 +276,7 @@ function SelectionMenu({
clipboard.data.notes[item.id] = mapState.notes[item.id]; clipboard.data.notes[item.id] = mapState.notes[item.id];
} }
} }
if (navigator.clipboard) { if (await clipboardSupported()) {
await navigator.clipboard.writeText(JSON.stringify(clipboard)); await navigator.clipboard.writeText(JSON.stringify(clipboard));
} else { } else {
localClipboardDataRef.current = JSON.stringify(clipboard); localClipboardDataRef.current = JSON.stringify(clipboard);
@ -291,7 +292,7 @@ function SelectionMenu({
} }
try { try {
let clipboardText; let clipboardText;
if (navigator.clipboard) { if (await clipboardSupported()) {
clipboardText = await navigator.clipboard.readText(); clipboardText = await navigator.clipboard.readText();
} else { } else {
clipboardText = localClipboardDataRef.current; clipboardText = localClipboardDataRef.current;

View File

@ -106,3 +106,28 @@ export function shuffle<Type>(array: Type[]) {
return temp; return temp;
} }
/**
* Check that read and write permission is granted for clipboard.
* If permission has yet to be granted or denied request it.
* This will also return false if the browser does not support reading
* and writing to the clipboard e.g. for Safari or Firefox
*/
export async function clipboardSupported(): Promise<boolean> {
// @ts-ignore
if (navigator.clipboard?.readText && navigator.clipboard?.writeText) {
if (navigator.permissions) {
let query = await navigator.permissions.query({ name: "clipboard-read" });
if (query.state === "prompt") {
try {
await navigator.clipboard.readText();
query = await navigator.permissions.query({ name: "clipboard-read" });
} catch {
return false;
}
}
return query.state === "granted";
}
}
return false;
}