Merge pull request #206 from appwrite/fix-copy-not-working-on-http

Fix: copy not working on http
This commit is contained in:
Torsten Dittmann
2022-12-27 10:47:56 +01:00
committed by GitHub
3 changed files with 59 additions and 19 deletions
+15 -13
View File
@@ -2,6 +2,7 @@
import { trackEvent } from '$lib/actions/analytics';
import { tooltip } from '$lib/actions/tooltip';
import { clickOnEnter } from '$lib/helpers/a11y';
import { copy } from '$lib/helpers/copy';
import { addNotification } from '$lib/stores/notifications';
export let value: string;
@@ -9,27 +10,28 @@
let content = 'Click to copy';
const copy = async () => {
try {
await navigator.clipboard.writeText(value);
async function handleClick() {
const success = await copy(value);
if (success) {
content = 'Copied';
} catch (error) {
} else {
addNotification({
message: error.message,
message: 'Unable to copy to clipboard',
type: 'error'
});
} finally {
if (event) {
trackEvent('click_id_tag', {
name: event
});
}
}
};
if (event) {
trackEvent('click_id_tag', {
name: event
});
}
}
</script>
<span
on:click|preventDefault={copy}
on:click|preventDefault={handleClick}
on:keyup={clickOnEnter}
on:mouseenter={() => setTimeout(() => (content = 'Click to copy'))}
use:tooltip={{
+8 -6
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip';
import { copy } from '$lib/helpers/copy';
import { addNotification } from '$lib/stores/notifications';
@@ -9,13 +10,14 @@
let content = 'Click to copy';
const copy = async () => {
try {
await navigator.clipboard.writeText(value);
const handleCopy = async () => {
const success = await copy(value);
if (success) {
content = 'Copied';
} catch (error) {
} else {
addNotification({
message: error.message,
message: 'Unable to copy to clipboard',
type: 'error'
});
}
@@ -31,7 +33,7 @@
type="button"
class="input-button"
aria-label="Click to copy."
on:click={copy}
on:click={handleCopy}
on:mouseenter={() => setTimeout(() => (content = 'Click to copy'))}
use:tooltip={{
content,
+36
View File
@@ -0,0 +1,36 @@
async function securedCopy(value: string) {
try {
await navigator.clipboard.writeText(value);
} catch {
return false;
}
return true;
}
function unsecuredCopy(value: string) {
const textArea = document.createElement('textarea');
textArea.value = value;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
let success = true;
try {
document.execCommand('copy');
} catch {
success = false;
} finally {
document.body.removeChild(textArea);
}
return success;
}
export async function copy(value: string) {
// securedCopy works only in HTTPS environment.
// unsecuredCopy works in HTTP and only runs if securedCopy fails.
const success = (await securedCopy(value)) || unsecuredCopy(value);
return success;
}