summaryrefslogtreecommitdiff
path: root/demo/asset/script/shared.js
blob: 73ea5c273a5e0edaeda4f86364b255651cd361cb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function copyTextToClipboard(text, { target = document.body } = {}) {
  if (typeof text !== "string")
    throw new TypeError(`Expected parameter \`text\` to be a \`string\`, got \`${typeof text}\`.`);

  const element = document.createElement("textarea");
  const previouslyFocusedElement = document.activeElement;
  let isSuccess = false;

  element.value = text;
  element.setAttribute("readonly", "");
  element.style.contain = "strict";
  element.style.position = "absolute";
  element.style.left = "-9999px";
  element.style.fontSize = "12pt";

  const selection = document.getSelection();
  const originalRange = selection.rangeCount > 0 && selection.getRangeAt(0);

  target.append(element);

  element.select();
  element.selectionStart = 0;
  element.selectionEnd = text.length;

  try {
    isSuccess = document.execCommand("copy");
  } catch(_) {
    //
  }

  element.remove();

  if (originalRange) {
    selection.removeAllRanges();
    selection.addRange(originalRange);
  }

  if (previouslyFocusedElement)
    previouslyFocusedElement.focus();
  return isSuccess;

  /// via https://github.com/sindresorhus/copy-text-to-clipboard
}

function playAudio() {
  const audio = document.getElementById("speak");
  audio.play();
}