CopyToClipboardInput.vue 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <template>
  2. <div class="CopyToClipboardInput" v-bind="$attrs">
  3. <input
  4. type="text"
  5. class="CopyToClipboardInput-input"
  6. :value="value"
  7. @focus="selectText"
  8. readonly
  9. />
  10. <button
  11. type="button"
  12. class="CopyToClipboardInput-button"
  13. @click="copyToClipboard"
  14. title="Copy to Clipboard"
  15. >
  16. Copy
  17. </button>
  18. </div>
  19. </template>
  20. <script setup>
  21. defineProps({
  22. value: {
  23. type: String,
  24. required: true,
  25. },
  26. });
  27. const selectText = (event) => {
  28. const inputElement = event.target;
  29. inputElement.select();
  30. inputElement.removeEventListener("focus", selectText);
  31. };
  32. const copyToClipboard = (event) => {
  33. const inputValue = event.target.previousSibling.value;
  34. navigator.clipboard.writeText(inputValue).then(
  35. () => {
  36. event.target.textContent = "Copied!";
  37. setTimeout(() => {
  38. event.target.textContent = "Copy";
  39. }, 1000);
  40. },
  41. (err) => {
  42. console.error("Could not copy to clipboard:", err);
  43. },
  44. );
  45. };
  46. </script>
  47. <style scoped>
  48. .CopyToClipboardInput {
  49. display: flex;
  50. }
  51. .CopyToClipboardInput-input {
  52. font-size: 0.9em;
  53. font-family: monospace;
  54. flex-grow: 1;
  55. border: 1px solid var(--vp-c-border);
  56. border-top-left-radius: 4px;
  57. border-bottom-left-radius: 4px;
  58. background-color: var(--vp-c-bg);
  59. padding: 8px 13px;
  60. &:focus {
  61. border-color: var(--vp-button-brand-bg);
  62. }
  63. }
  64. .CopyToClipboardInput-button {
  65. font-size: 14px;
  66. border-top-right-radius: 4px;
  67. border-bottom-right-radius: 4px;
  68. color: var(--vp-button-brand-text);
  69. min-width: 73px;
  70. font-weight: 600;
  71. padding: 5px 10px;
  72. background-color: var(--vp-button-brand-bg);
  73. transition: background-color 0.25s;
  74. &:hover {
  75. background-color: var(--vp-button-brand-hover-bg);
  76. }
  77. }
  78. </style>