Browse Source

feature: add support for custom mime types

Ryan Chandler 1 year ago
parent
commit
f5c4e22a4a
5 changed files with 38 additions and 3 deletions
  1. 9 1
      dist/alpine-clipboard.js
  2. 0 0
      dist/alpine-clipboard.js.map
  3. 1 1
      examples/index.html
  4. 16 0
      examples/mime-type.html
  5. 12 1
      src/index.js

+ 9 - 1
dist/alpine-clipboard.js

@@ -5,7 +5,7 @@
 
     let onCopy = () => {};
 
-    const copy = target => {
+    const copy = (target, mimeType = undefined) => {
       if (typeof target === 'function') {
         target = target();
       }
@@ -14,6 +14,14 @@
         target = JSON.stringify(target);
       }
 
+      if (mimeType !== undefined) {
+        return window.navigator.clipboard.write([new ClipboardItem({
+          [mimeType]: new Blob([target], {
+            type: mimeType
+          })
+        })]).then(onCopy);
+      }
+
       return window.navigator.clipboard.writeText(target).then(onCopy);
     };
 

File diff suppressed because it is too large
+ 0 - 0
dist/alpine-clipboard.js.map


+ 1 - 1
examples/index.html

@@ -1,7 +1,7 @@
 <!DOCTYPE html>
 <head>
     <title>Alpine Clipboard</title>
-    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine-next/packages/alpinejs/dist/cdn.min.js" defer></script>
+    <script src="//unpkg.com/alpinejs" defer></script>
 </head>
 <body>
     <div x-data="{ input: '' }">

+ 16 - 0
examples/mime-type.html

@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+
+<head>
+    <title>Alpine Clipboard</title>
+    <script src="//unpkg.com/alpinejs" defer></script>
+</head>
+
+<body>
+    <button type="button" x-data x-on:click="$clipboard(document.getElementById('target').outerHTML, 'text/html')">Copy as HTML</button>
+
+    <div id="target" style="background: red; width: 200px; height: 200px; color: white;">
+        <p>Hello, world.</p>
+    </div>
+
+    <script src="../dist/alpine-clipboard.js"></script>
+</body>

+ 12 - 1
src/index.js

@@ -1,6 +1,6 @@
 let onCopy = () => {}
 
-const copy = (target) => {
+const copy = (target, mimeType = undefined) => {
     if (typeof target === 'function') {
         target = target()
     }
@@ -9,6 +9,17 @@ const copy = (target) => {
         target = JSON.stringify(target)
     }
 
+    if (mimeType !== undefined) {
+        return window.navigator.clipboard.write([
+            new ClipboardItem({
+                [mimeType]: new Blob([target], {
+                    type: mimeType,
+                })
+            })
+        ])
+            .then(onCopy)
+    }
+
     return window.navigator.clipboard.writeText(target)
         .then(onCopy)
 }

Some files were not shown because too many files changed in this diff