瀏覽代碼

Merge pull request #16 from ryangjchandler/v3

release: Alpine v3.x support
Ryan Chandler 4 年之前
父節點
當前提交
e64cc6c319

+ 14 - 24
README.md

@@ -8,6 +8,8 @@ Copy text to the user's clipboard.
 ![Build size Brotli](https://img.badgesize.io/ryangjchandler/alpine-clipboard/master/dist/alpine-clipboard.js.svg?compression=gzip&style=flat-square&color=green)
 [![Monthly downloads via CDN](https://data.jsdelivr.com/v1/package/npm/@ryangjchandler/alpine-clipboard/badge)](https://www.jsdelivr.com/package/npm/@ryangjchandler/alpine-clipboard)
 
+> Since v2.0, this package only supports Alpine v3.x. If you're still using Alpine 2.x, please use [v1.0](https://github.com/ryangjchandler/alpine-clipboard/tree/v1.0.0) of this package.
+
 ## About
 
 This plugin adds a new `$clipboard` magic property to all of your Alpine components that can be used to copy any piece of data to the user's clipboard.
@@ -16,10 +18,10 @@ This plugin adds a new `$clipboard` magic property to all of your Alpine compone
 
 ### CDN
 
-Include the following `<script>` tag at the end of your `<body>`:
+Include the following `<script>` tag in the `<head>` of your document, just before Alpine.
 
 ```html
-<script src="https://cdn.jsdelivr.net/npm/@ryangjchandler/alpine-clipboard@1.x.x/dist/alpine-clipboard.js"></script>
+<script src="https://cdn.jsdelivr.net/npm/@ryangjchandler/alpine-clipboard@2.x.x/dist/alpine-clipboard.js" defer></script>
 ```
 
 ### NPM
@@ -31,25 +33,13 @@ npm install @ryangjchandler/alpine-clipboard
 Add the `$clipboard` magic property to your project by importing the package **before** Alpine.js.
 
 ```js
-import "@ryangjchandler/alpine-clipboard"
-// import "alpinejs"
-```
-
-#### Legacy Browser Support
-
-If you need to support legacy browsers, you can import the `alpine-clipboard.ie11.js` file instead.
-
-**CDN**
+import Alpine from 'alpinejs'
+import Clipboard from "@ryangjchandler/alpine-clipboard"
 
-```
-<script src="https://cdn.jsdelivr.net/npm/@ryangjchandler/alpine-clipboard@1.x.x/dist/alpine-clipboard.ie11.js"></script>
-```
-
-**NPM**
+Alpine.plugin(Clipboard)
 
-```js
-import "@ryangjchandler/alpine-clipboard/src/index.ie11.js"
-// import "alpinejs"
+window.Alpine = Alpine
+window.Alpine.start()
 ```
 
 ## Usage
@@ -59,7 +49,9 @@ To copy some data to the clipboard, invoke `$clipboard` from an event handler in
 ```html
 <div x-data="{ input: '' }">
     <input x-model="input">
-    <button type="button" @click="$clipboard(input)">Copy to Clipboard</button>
+    <button type="button" @click="$clipboard(input)">
+        Copy to Clipboard
+    </button>
 </div>
 ```
 
@@ -77,12 +69,10 @@ The clipboard will now contain `["foo","bar"]`.
 
 ## Versioning
 
-This projects follow the [Semantic Versioning](https://semver.org/) guidelines. This means that there *could* be breaking changes on minor version changes, up until v1.x is reached.
-
-For example, 0.1 -> 0.2 might introduce a breaking change.
+This projects follow the [Semantic Versioning](https://semver.org/) guidelines.
 
 ## License
 
-Copyright (c) 2020 Ryan Chandler and contributors
+Copyright (c) 2021 Ryan Chandler and contributors
 
 Licensed under the MIT license, see [LICENSE.md](LICENSE.md) for details.

+ 5 - 0
builds/cdn.js

@@ -0,0 +1,5 @@
+import clipboard from '../src/index'
+
+document.addEventListener('alpine:initializing', () => {
+    clipboard(window.Alpine)
+})

+ 0 - 70
dist/alpine-clipboard.ie11.js

@@ -1,70 +0,0 @@
-(function (global, factory) {
-    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
-    typeof define === 'function' && define.amd ? define(factory) :
-    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.AlpineClipboard = factory());
-}(this, (function () { 'use strict';
-
-    var AlpineClipboard = {
-      start: function start() {
-        if (!window.Alpine) {
-          throw new Error('Alpine is required for `alpine-clipboard` to work.');
-        }
-
-        Alpine.addMagicProperty('clipboard', function () {
-          return function (target) {
-            var value = target;
-
-            if (typeof value === 'function') {
-              value = value();
-            } else if (typeof value !== 'string') {
-              try {
-                value = JSON.stringify(value);
-              } catch (e) {
-                console.warn(e);
-              }
-            }
-
-            var container = document.createElement('textarea');
-            container.value = value;
-            container.setAttribute('readonly', '');
-            container.style.cssText = 'position:fixed;pointer-events:none;z-index:-9999;opacity:0;';
-            document.body.appendChild(container);
-
-            if (navigator.userAgent && navigator.userAgent.match(/ipad|ipod|iphone/i)) {
-              container.contentEditable = true;
-              container.readOnly = true;
-              var range = document.createRange();
-              range.selectNodeContents(container);
-              var selection = window.getSelection();
-              selection.removeAllRanges();
-              selection.addRange(range);
-              container.setSelectionRange(0, 999999);
-            } else {
-              container.select();
-            }
-
-            try {
-              document.execCommand('copy');
-            } catch (e) {
-              console.warn(err);
-            }
-
-            document.body.removeChild(container);
-          };
-        });
-      }
-    };
-
-    var alpine = window.deferLoadingAlpine || function (callback) {
-      return callback();
-    };
-
-    window.deferLoadingAlpine = function (callback) {
-      AlpineClipboard.start();
-      alpine(callback);
-    };
-
-    return AlpineClipboard;
-
-})));
-//# sourceMappingURL=alpine-clipboard.ie11.js.map

文件差異過大導致無法顯示
+ 0 - 0
dist/alpine-clipboard.ie11.js.map


+ 23 - 32
dist/alpine-clipboard.js

@@ -1,36 +1,27 @@
-(function (global, factory) {
-    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+(function (factory) {
     typeof define === 'function' && define.amd ? define(factory) :
-    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.AlpineClipboard = factory());
-}(this, (function () { 'use strict';
-
-    const AlpineClipboard = {
-      start() {
-        if (!window.Alpine) {
-          throw new Error('Alpine is required for `alpine-clipboard` to work.');
-        }
-
-        Alpine.addMagicProperty('clipboard', () => {
-          return function (target) {
-            if (typeof target === 'function') {
-              target = target();
-            }
-
-            return window.navigator.clipboard.writeText(target);
-          };
-        });
-      }
-
-    };
-
-    const deferrer = window.deferLoadingAlpine || (callback => callback());
-
-    window.deferLoadingAlpine = function (callback) {
-      AlpineClipboard.start();
-      deferrer(callback);
-    };
-
-    return AlpineClipboard;
+    factory();
+}((function () { 'use strict';
+
+    function clipboard (Alpine) {
+      Alpine.magic('clipboard', () => {
+        return function (target) {
+          if (typeof target === 'function') {
+            target = target();
+          }
+
+          if (typeof target === 'object') {
+            target = JSON.stringify(target);
+          }
+
+          return window.navigator.clipboard.writeText(target);
+        };
+      });
+    }
+
+    document.addEventListener('alpine:initializing', () => {
+      clipboard(window.Alpine);
+    });
 
 })));
 //# sourceMappingURL=alpine-clipboard.js.map

+ 1 - 1
dist/alpine-clipboard.js.map

@@ -1 +1 @@
-{"version":3,"file":"alpine-clipboard.js","sources":["../src/index.js"],"sourcesContent":["const AlpineClipboard = {\n    start() {\n        if (!window.Alpine) {\n            throw new Error('Alpine is required for `alpine-clipboard` to work.')\n        }\n\n        Alpine.addMagicProperty('clipboard', () => {\n            return function (target) {\n                if (typeof target === 'function') {\n                    target = target()\n                }\n                \n                return window.navigator.clipboard.writeText(target)\n            }\n        })\n    }\n}\n\nconst deferrer = window.deferLoadingAlpine || ((callback) => callback())\n\nwindow.deferLoadingAlpine = function (callback) {\n    AlpineClipboard.start()\n\n    deferrer(callback)\n}\n\nexport default AlpineClipboard"],"names":["AlpineClipboard","start","window","Alpine","Error","addMagicProperty","target","navigator","clipboard","writeText","deferrer","deferLoadingAlpine","callback"],"mappings":";;;;;;UAAMA,eAAe,GAAG;IACpBC,EAAAA,KAAK,GAAG;IACJ,QAAI,CAACC,MAAM,CAACC,MAAZ,EAAoB;IAChB,YAAM,IAAIC,KAAJ,CAAU,oDAAV,CAAN;IACH;;IAEDD,IAAAA,MAAM,CAACE,gBAAP,CAAwB,WAAxB,EAAqC,MAAM;IACvC,aAAO,UAAUC,MAAV,EAAkB;IACrB,YAAI,OAAOA,MAAP,KAAkB,UAAtB,EAAkC;IAC9BA,UAAAA,MAAM,GAAGA,MAAM,EAAf;IACH;;IAED,eAAOJ,MAAM,CAACK,SAAP,CAAiBC,SAAjB,CAA2BC,SAA3B,CAAqCH,MAArC,CAAP;IACH,OAND;IAOH,KARD;IASH;;IAfmB;;IAkBxB,MAAMI,QAAQ,GAAGR,MAAM,CAACS,kBAAP,KAA+BC,QAAD,IAAcA,QAAQ,EAApD,CAAjB;;IAEAV,MAAM,CAACS,kBAAP,GAA4B,UAAUC,QAAV,EAAoB;IAC5CZ,EAAAA,eAAe,CAACC,KAAhB;IAEAS,EAAAA,QAAQ,CAACE,QAAD,CAAR;IACH,CAJD;;;;;;;;"}
+{"version":3,"file":"alpine-clipboard.js","sources":["../src/index.js","../builds/cdn.js"],"sourcesContent":["export default function (Alpine) {\n    Alpine.magic('clipboard', () => {\n        return function (target) {\n            if (typeof target === 'function') {\n                target = target()\n            }\n\n            if (typeof target === 'object') {\n                target = JSON.stringify(target)\n            }\n\n            return window.navigator.clipboard.writeText(target)\n        }\n    })\n}","import clipboard from '../src/index'\n\ndocument.addEventListener('alpine:initializing', () => {\n    clipboard(window.Alpine)\n})"],"names":["Alpine","magic","target","JSON","stringify","window","navigator","clipboard","writeText","document","addEventListener"],"mappings":";;;;;IAAe,oBAAUA,MAAV,EAAkB;IAC7BA,EAAAA,MAAM,CAACC,KAAP,CAAa,WAAb,EAA0B,MAAM;IAC5B,WAAO,UAAUC,MAAV,EAAkB;IACrB,UAAI,OAAOA,MAAP,KAAkB,UAAtB,EAAkC;IAC9BA,QAAAA,MAAM,GAAGA,MAAM,EAAf;IACH;;IAED,UAAI,OAAOA,MAAP,KAAkB,QAAtB,EAAgC;IAC5BA,QAAAA,MAAM,GAAGC,IAAI,CAACC,SAAL,CAAeF,MAAf,CAAT;IACH;;IAED,aAAOG,MAAM,CAACC,SAAP,CAAiBC,SAAjB,CAA2BC,SAA3B,CAAqCN,MAArC,CAAP;IACH,KAVD;IAWH,GAZD;IAaH;;ICZDO,QAAQ,CAACC,gBAAT,CAA0B,qBAA1B,EAAiD,MAAM;IACnDH,EAAAA,SAAS,CAACF,MAAM,CAACL,MAAR,CAAT;IACH,CAFD;;;;;;"}

+ 0 - 17
examples/ie11.html

@@ -1,17 +0,0 @@
-<!DOCTYPE html>
-<head>
-    <title>Alpine Clipboard IE11</title>
-    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js" defer></script>
-</head>
-<body>
-    <div x-data="{ input: '' }">
-        <input x-model="input">
-        <button type="button" @click="$clipboard(input)">Copy to Clipboard</button>
-    </div>
-
-    <div x-data="{}">
-        <button type="button" @click="$clipboard(() => 'Testing')">Copy 'Testing' to Clipboard</button>
-    </div>
-
-    <script src="../dist/alpine-clipboard.ie11.js"></script>
-</body>

+ 9 - 1
examples/index.html

@@ -1,7 +1,7 @@
 <!DOCTYPE html>
 <head>
     <title>Alpine Clipboard</title>
-    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js" defer></script>
+    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine-next/packages/alpinejs/dist/cdn.min.js" defer></script>
 </head>
 <body>
     <div x-data="{ input: '' }">
@@ -13,5 +13,13 @@
         <button type="button" @click="$clipboard(() => 'Testing')">Copy 'Testing' to Clipboard</button>
     </div>
 
+    <div x-data="{ items: ['foo', 'bar'] }">
+        <template x-for="item in items">
+            <p x-text="item"></p>
+        </template>
+
+        <button type="button" @click="$clipboard(items)">Copy the JSON representation of `items` to your clipboard</button>
+    </div>
+
     <script src="../dist/alpine-clipboard.js"></script>
 </body>

文件差異過大導致無法顯示
+ 4685 - 225
package-lock.json


+ 4 - 8
package.json

@@ -1,25 +1,21 @@
 {
     "name": "@ryangjchandler/alpine-clipboard",
     "description": "Simply copy to the users clipboard in your Alpine.js components.",
-    "version": "1.0.0",
+    "version": "2.0.0",
     "license": "MIT",
     "author": "Ryan Chandler <support@ryangjchandler.co.uk>",
     "repository": {
         "type": "git",
         "url": "https://github.com/ryangjchandler/alpine-clipboard"
     },
-    "main": "dist/alpine-clipboard.ie11.js",
-    "module": "src/index.js",
+    "main": "src/index.js",
     "scripts": {
-        "build": "rollup -c && rollup -c rollup.ie11.config.js",
+        "build": "rollup -c",
         "watch": "rollup -c -w"
     },
-    "dependencies": {
-        "alpinejs": "^2.6.0"
-    },
     "devDependencies": {
-        "@babel/preset-env": "^7.12.11",
         "@babel/core": "^7.12.10",
+        "@babel/preset-env": "^7.12.11",
         "rollup": "^2.35.1",
         "rollup-plugin-babel": "^4.4.0",
         "rollup-plugin-filesize": "^9.1.0",

+ 1 - 1
rollup.config.js

@@ -4,7 +4,7 @@ import filesize from 'rollup-plugin-filesize'
 import resolve from 'rollup-plugin-node-resolve'
 
 export default {
-    input: 'src/index.js',
+    input: 'builds/cdn.js',
     output: [
         {
             name: 'AlpineClipboard',

+ 0 - 37
rollup.ie11.config.js

@@ -1,37 +0,0 @@
-import babel from 'rollup-plugin-babel'
-import filesize from 'rollup-plugin-filesize'
-import resolve from 'rollup-plugin-node-resolve'
-
-export default {
-    input: 'src/index.ie11.js',
-    output: [
-        {
-            name: 'AlpineClipboard',
-            file: 'dist/alpine-clipboard.ie11.js',
-            format: 'umd',
-            sourcemap: true,
-        }
-    ],
-    plugins: [
-        resolve(),
-        filesize(),
-        babel({
-            exclude: 'node_modules/**',
-            babelrc: false,
-            presets: [
-                [
-                    '@babel/preset-env',
-                    {
-                        targets: {
-                            node: 'current',
-                            edge: '18',
-                            ie: '11',
-                            ios: '11.3',
-                            safari: '13'
-                        }
-                    }
-                ]
-            ]
-        })
-    ]
-}

+ 0 - 67
src/index.ie11.js

@@ -1,67 +0,0 @@
-const AlpineClipboard = {
-    start() {
-        if (!window.Alpine) {
-            throw new Error('Alpine is required for `alpine-clipboard` to work.')
-        }
-
-        Alpine.addMagicProperty('clipboard', () => {
-            return function (target) {
-                let value = target
-
-                if (typeof value === 'function') {
-                    value = value()
-                } else if (typeof value !== 'string') {
-                    try {
-                        value = JSON.stringify(value)
-                    } catch (e) {
-                        console.warn(e)
-                    }
-                }
-
-                const container = document.createElement('textarea')
-
-                container.value = value
-                container.setAttribute('readonly', '')
-                container.style.cssText = 'position:fixed;pointer-events:none;z-index:-9999;opacity:0;'
-
-                document.body.appendChild(container)
-
-                if (navigator.userAgent && navigator.userAgent.match(/ipad|ipod|iphone/i)) {
-                    container.contentEditable = true
-                    container.readOnly = true
-
-                    const range = document.createRange()
-
-                    range.selectNodeContents(container)
-
-                    const selection = window.getSelection()
-
-                    selection.removeAllRanges()
-                    selection.addRange(range)
-
-                    container.setSelectionRange(0, 999999)
-                } else {
-                    container.select()
-                }
-
-                try {
-                    document.execCommand('copy')
-                } catch (e) {
-                    console.warn(err)
-                }
-
-                document.body.removeChild(container)
-            }
-        })
-    }
-}
-
-const alpine = window.deferLoadingAlpine || ((callback) => callback())
-
-window.deferLoadingAlpine = function (callback) {
-    AlpineClipboard.start()
-
-    alpine(callback)
-}
-
-export default AlpineClipboard

+ 12 - 24
src/index.js

@@ -1,27 +1,15 @@
-const AlpineClipboard = {
-    start() {
-        if (!window.Alpine) {
-            throw new Error('Alpine is required for `alpine-clipboard` to work.')
-        }
-
-        Alpine.addMagicProperty('clipboard', () => {
-            return function (target) {
-                if (typeof target === 'function') {
-                    target = target()
-                }
-                
-                return window.navigator.clipboard.writeText(target)
+export default function (Alpine) {
+    Alpine.magic('clipboard', () => {
+        return function (target) {
+            if (typeof target === 'function') {
+                target = target()
             }
-        })
-    }
-}
-
-const deferrer = window.deferLoadingAlpine || ((callback) => callback())
 
-window.deferLoadingAlpine = function (callback) {
-    AlpineClipboard.start()
-
-    deferrer(callback)
-}
+            if (typeof target === 'object') {
+                target = JSON.stringify(target)
+            }
 
-export default AlpineClipboard
+            return window.navigator.clipboard.writeText(target)
+        }
+    })
+}

+ 0 - 0
tests/.gitkeep


+ 0 - 27
tests/clipboard.spec.js

@@ -1,27 +0,0 @@
-import AlpineClipboard from '../dist/alpine-clipboard'
-import Alpine from 'alpinejs'
-import { waitFor } from '@testing-library/dom'
-
-beforeEach(() => {
-    window.Alpine = Alpine
-})
-
-test('contents can be copied to clipboard', async () => {
-    document.execCommand = jest.fn()
-
-    document.body.innerHTML = `
-        <div x-data="{ input: '' }">
-            <button x-on:click.prevent="$clipboard(input)"></button>
-        </div>
-    `
-
-    AlpineClipboard.start()
-    
-    await Alpine.start()
-
-    document.querySelector('button').click()
-
-    await waitFor(() => {
-        expect(document.execCommand).toHaveBeenCalledWith('copy')
-    })
-})

部分文件因文件數量過多而無法顯示