From aa36587a53d2feace28efa452a08d7a57b5c773d Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Fri, 6 Aug 2021 14:24:35 +1000 Subject: [PATCH] Add better clipboard api support detection --- src/components/selection/SelectionMenu.tsx | 5 +++-- src/helpers/shared.ts | 25 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/components/selection/SelectionMenu.tsx b/src/components/selection/SelectionMenu.tsx index bd84e7c..aa1d372 100644 --- a/src/components/selection/SelectionMenu.tsx +++ b/src/components/selection/SelectionMenu.tsx @@ -34,6 +34,7 @@ import { isSelection } from "../../validators/Selection"; import { getRelativePointerPosition } from "../../helpers/konva"; import { useKeyboard } from "../../contexts/KeyboardContext"; import shortcuts from "../../shortcuts"; +import { clipboardSupported } from "../../helpers/shared"; type SelectionMenuProps = { isOpen: boolean; @@ -275,7 +276,7 @@ function SelectionMenu({ clipboard.data.notes[item.id] = mapState.notes[item.id]; } } - if (navigator.clipboard) { + if (await clipboardSupported()) { await navigator.clipboard.writeText(JSON.stringify(clipboard)); } else { localClipboardDataRef.current = JSON.stringify(clipboard); @@ -291,7 +292,7 @@ function SelectionMenu({ } try { let clipboardText; - if (navigator.clipboard) { + if (await clipboardSupported()) { clipboardText = await navigator.clipboard.readText(); } else { clipboardText = localClipboardDataRef.current; diff --git a/src/helpers/shared.ts b/src/helpers/shared.ts index d1a0773..152dcae 100644 --- a/src/helpers/shared.ts +++ b/src/helpers/shared.ts @@ -106,3 +106,28 @@ export function shuffle(array: Type[]) { 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 { + // @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; +}