utils.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * <<
  3. * Davinci
  4. * ==
  5. * Copyright (C) 2016 - 2017 EDP
  6. * ==
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * >>
  19. */
  20. function createInput (text: string) {
  21. const body = document.body
  22. const input = document.createElement('input')
  23. input.style.height = '0px'
  24. input.value = text
  25. return {
  26. init: () => {
  27. body.appendChild(input)
  28. return input
  29. },
  30. destory: () => body.removeChild(input)
  31. }
  32. }
  33. function selectCopy(text: string, resolve, reject) {
  34. const { init, destory } = createInput(text)
  35. const input = init()
  36. try {
  37. input.select()
  38. const selected = document.execCommand('copy')
  39. return selected ? resolve() : reject()
  40. } catch (error) {
  41. reject(error)
  42. }
  43. destory()
  44. }
  45. export function copyTextToClipboard (text: string, resolve, reject) {
  46. if (!navigator.clipboard) {
  47. return selectCopy(text, resolve, reject)
  48. }
  49. return navigator.clipboard.writeText(text).then(resolve, reject)
  50. }