@scaleflex/widget-url 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 scaleflex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @scaleflex/widget-url
2
+
3
+ [![Plugins][plugins-image]](#plugins)
4
+ [![Website][filerobot-image]][sfx-url]
5
+ [![Version][filerobot-version]][version-url]
6
+ [![Scaleflex team][made-by-image]][sfx-url]
7
+ [![License][license-image]][license-url]
8
+ [![CodeSandbox][codeSandbox-image]][codeSandbox-url]
9
+
10
+
11
+ <div align='center'>
12
+ <img title="Scaleflex Widget logo" alt="Scaleflex Widget logo" src="https://cdn.scaleflex.com/plugins/filerobot-widget/assets/filerobot_widget_logo_with_fire.png?vh=b2ff09" width="140"/>
13
+ </div>
14
+
15
+ The Url plugin for [Scaleflex Media Asset Widget](https://www.npmjs.com/package/@scaleflex/widget-core)
16
+ lets users import files from the Internet. Paste any URL and it’ll be added!
17
+
18
+ ## Usage
19
+
20
+ ### NPM
21
+
22
+ ```bash
23
+ npm install --save @scaleflex/widget-url
24
+ ```
25
+
26
+ ### YARN
27
+
28
+ ```bash
29
+ yarn add @scaleflex/widget-url
30
+ ```
31
+
32
+ then
33
+
34
+ ```js
35
+ import Url from '@scaleflex/widget-url'
36
+ ...
37
+ ...
38
+ ...
39
+ scaleflexWidget.use(Url, propertiesObject)
40
+ ```
41
+
42
+ ### CDN
43
+
44
+ The plugin from CDN is found inside `Scaleflex` global object `Scaleflex.Url`
45
+
46
+ ```js
47
+ const url = window.ScaleflexWidget.Url
48
+ ...
49
+ ...
50
+ ...
51
+ scaleflexWidget.use(url, propertiesObject)
52
+ ```
53
+
54
+ ## Plugin's styles
55
+
56
+ ```js
57
+ import '@scaleflex/widget-core/dist/style.css'
58
+ import '@scaleflex/widget-url/dist/style.css'
59
+ ```
60
+
61
+ or if you prefer the minified version
62
+
63
+ ```js
64
+ import '@scaleflex/widget-core/dist/style.min.css'
65
+ import '@scaleflex/widget-url/dist/style.min.css'
66
+ ```
67
+
68
+ > The plugin's css file should be imported after the [Core's css file](../@scaleflex/widget-core/#modules-styles) for having the styles shown correctly.
69
+
70
+ ## Properties
71
+
72
+ ### `title`
73
+
74
+ <u>Type:</u> `string`
75
+
76
+ <u>Default:</u> `'Link'`
77
+
78
+ The title/label that would be shown & used for the plugin.
79
+
80
+ ### `companionHeaders`
81
+
82
+ <u>Type:</u> `null` | `object`
83
+
84
+ <u>Default:</u> `null`
85
+
86
+ If you need to pass additional headers for in companion requests then pass them in this property.
87
+
88
+ <!-- Variables -->
89
+
90
+ [npm-url]: https://www.npmjs.com/package/@scaleflex/widget-url
91
+ [license-url]: https://opensource.org/licenses/MIT
92
+ [sfx-url]: https://www.scaleflex.com/
93
+ [version-url]: https://www.npmjs.com/package/@scaleflex/widget-url
94
+ [codeSandbox-url]: https://codesandbox.io/s/filerobot-widget-v3-c5l9th
95
+
96
+ [npm-image]: https://img.shields.io/npm/v/@telus/remark-config.svg?style=for-the-badge&logo=npm
97
+ [license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=for-the-badge
98
+ [made-by-image]: https://img.shields.io/badge/%3C%2F%3E%20with%20%E2%99%A5%20by-the%20Scaleflex%20team-6986fa.svg?style=for-the-badge
99
+ [plugins-image]: https://img.shields.io/static/v1?label=Scaleflex&message=Plugins&color=yellow&style=for-the-badge
100
+ [filerobot-image]: https://img.shields.io/static/v1?label=Scaleflex&message=website&color=orange&style=for-the-badge
101
+ [filerobot-version]: https://img.shields.io/npm/v/@scaleflex/widget-url?label=Version&style=for-the-badge&logo=npm
102
+ [codeSandbox-image]: https://img.shields.io/badge/CodeSandbox-black?style=for-the-badge&logo=CodeSandbox
package/lib/UrlUI.js ADDED
@@ -0,0 +1,123 @@
1
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
+ import { useState } from 'react';
8
+ import { useSelector } from 'react-redux';
9
+ import { Link } from '@scaleflex/icons';
10
+ import { selectInfo } from '@scaleflex/widget-core/lib/slices/info.slice';
11
+ import Styled from './UrlUI.styled';
12
+ import { selectCurrentFolderPath } from '@scaleflex/widget-explorer/lib/slices/folders.slice';
13
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
14
+ var HTTP_REGEX = /(http):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
15
+ var DUPLICATE_MESSAGE = 'duplicate';
16
+ var UrlUI = function UrlUI(_ref) {
17
+ var addFile = _ref.addFile,
18
+ i18n = _ref.i18n,
19
+ fileName = _ref.fileName;
20
+ var currentFolderPath = useSelector(selectCurrentFolderPath);
21
+ var _useState = useState(false),
22
+ _useState2 = _slicedToArray(_useState, 2),
23
+ isLoading = _useState2[0],
24
+ setIsLoading = _useState2[1];
25
+ var _useState3 = useState(''),
26
+ _useState4 = _slicedToArray(_useState3, 2),
27
+ inputValue = _useState4[0],
28
+ setInputValue = _useState4[1];
29
+ var _useState5 = useState(false),
30
+ _useState6 = _slicedToArray(_useState5, 2),
31
+ isError = _useState6[0],
32
+ setIsError = _useState6[1];
33
+ var _useState7 = useState(false),
34
+ _useState8 = _slicedToArray(_useState7, 2),
35
+ isNotHttps = _useState8[0],
36
+ setIsNotHttps = _useState8[1];
37
+
38
+ // TODO: we should improve the logic as it depends on the language?, better to trigger an event maybe? or some better solution.
39
+ var isFileExists = useSelector(function (state) {
40
+ return selectInfo(state).message.includes(DUPLICATE_MESSAGE);
41
+ });
42
+ var handleChangeInput = function handleChangeInput(event) {
43
+ setIsError(false);
44
+ setInputValue(event.target.value);
45
+ };
46
+ var handleError = function handleError() {
47
+ setIsError(true);
48
+ setIsLoading(false);
49
+ };
50
+ var handleSubmit = function handleSubmit() {
51
+ if (inputValue.match(HTTP_REGEX)) {
52
+ setIsNotHttps(true);
53
+ setIsError(true);
54
+ } else {
55
+ setIsLoading(true);
56
+ setIsError(false);
57
+ addFile({
58
+ url: inputValue,
59
+ toFolder: currentFolderPath,
60
+ callback: function callback() {
61
+ return setIsLoading(false);
62
+ },
63
+ onError: handleError
64
+ });
65
+ }
66
+ };
67
+ var handleKeyPress = function handleKeyPress(event) {
68
+ if (event.keyCode === 13 && inputValue.length) {
69
+ handleSubmit();
70
+ }
71
+ };
72
+ var errorMessage = function errorMessage() {
73
+ if (isNotHttps && isError) {
74
+ return i18n('urlUiInputErrorHttpsRequired');
75
+ }
76
+ if (isFileExists && isError) {
77
+ return i18n('urlUiInputExistsError', {
78
+ fileName: fileName(inputValue)
79
+ });
80
+ }
81
+ if (isError) {
82
+ return i18n('urlUiInputError');
83
+ }
84
+ return '';
85
+ };
86
+ return /*#__PURE__*/_jsx(Styled.Wrapper, {
87
+ className: "filerobot-Url",
88
+ children: /*#__PURE__*/_jsxs(Styled.Content, {
89
+ className: "filerobot-Url-content",
90
+ children: [/*#__PURE__*/_jsx(Styled.IconWrapper, {
91
+ children: /*#__PURE__*/_jsx(Link, {
92
+ size: 34
93
+ })
94
+ }), /*#__PURE__*/_jsxs(Styled.Info, {
95
+ children: [i18n('urlUiEnterPublicUrlText'), ' ', /*#__PURE__*/_jsxs(Styled.Hint, {
96
+ className: "filerobot-Url-required",
97
+ children: ["(", i18n('urlUiHttpsRequiredText'), ")"]
98
+ })]
99
+ }), /*#__PURE__*/_jsxs(Styled.InputWrapper, {
100
+ children: [/*#__PURE__*/_jsx(Styled.InputGroup, {
101
+ className: "filerobot-Url-input",
102
+ placeholder: i18n('urlUiInputPlaceholder'),
103
+ focusOnMount: true,
104
+ onKeyUp: handleKeyPress,
105
+ onChange: handleChangeInput,
106
+ fullWidth: true,
107
+ value: inputValue,
108
+ error: isError,
109
+ hint: errorMessage()
110
+ }), /*#__PURE__*/_jsx(Styled.Button, {
111
+ className: "filerobot-Url-actionsBtn",
112
+ disabled: isLoading || !inputValue.length,
113
+ onClick: handleSubmit,
114
+ loading: isLoading,
115
+ size: "lg",
116
+ color: "primary",
117
+ children: i18n('mutualizedImportLabel')
118
+ })]
119
+ })]
120
+ })
121
+ });
122
+ };
123
+ export default UrlUI;
@@ -0,0 +1,30 @@
1
+ var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8;
2
+ function _taggedTemplateLiteral(e, t) { return t || (t = e.slice(0)), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } })); }
3
+ import { PC } from '@scaleflex/widget-common';
4
+ import styled from 'styled-components';
5
+ import { InputGroup as SfxInputGroup, Button as SfxButton } from '@scaleflex/ui/core';
6
+ var Wrapper = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n width: 100%;\n height: 100%;\n flex: 1;\n padding: 0 24px;\n"])));
7
+ var Content = styled.div(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n row-gap: 16px;\n"])));
8
+ var IconWrapper = styled.div(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n display: flex;\n align-items: center;\n justify-content: center;\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background-color: ", ";\n\n svg {\n color: ", ";\n }\n"])), function (_ref) {
9
+ var theme = _ref.theme;
10
+ return theme.palette[PC.Link];
11
+ }, function (_ref2) {
12
+ var theme = _ref2.theme;
13
+ return theme.palette[PC.ButtonPrimaryText];
14
+ });
15
+ var Info = styled.p(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n font-size: 18px;\n line-height: 20px;\n text-align: center;\n font-weight: 400;\n margin: 0;\n"])));
16
+ var Hint = styled.span(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["\n\n"])));
17
+ var InputWrapper = styled.div(_templateObject6 || (_templateObject6 = _taggedTemplateLiteral(["\n display: flex;\n column-gap: 12px;\n height: 48px;\n width: 100%;\n max-width: 714px;\n\n .SfxInputGroup-root {\n width: 100%;\n height: 100%;\n }\n"])));
18
+ var InputGroup = styled(SfxInputGroup)(_templateObject7 || (_templateObject7 = _taggedTemplateLiteral(["\n height: 100%;\n width: 100%;\n padding: 11px 20px;\n"])));
19
+ var Button = styled(SfxButton)(_templateObject8 || (_templateObject8 = _taggedTemplateLiteral(["\n width: 102px;\n display: flex;\n justify-content: center;\n transition: all 100ms ease-out;\n"])));
20
+ var Styled = {
21
+ Wrapper: Wrapper,
22
+ Content: Content,
23
+ IconWrapper: IconWrapper,
24
+ Info: Info,
25
+ Hint: Hint,
26
+ InputWrapper: InputWrapper,
27
+ InputGroup: InputGroup,
28
+ Button: Button
29
+ };
30
+ export default Styled;
@@ -0,0 +1,16 @@
1
+ export default {
2
+ mutualizedImportLabel: 'Import',
3
+ urlUiImportingLabel: 'Importing...',
4
+ mutualizedCancelButtonLabel: 'Cancel',
5
+ urlUiEnterUrlToImportLabel: 'Enter URL to import a file',
6
+ urlUiInputPlaceholder: 'eg. https://sample-site.com/path-to-file',
7
+ urlUiInputError: 'Incorrect URL!',
8
+ urlUiInputExistsError: 'the %{fileName} already exists',
9
+ urlUiInputErrorHttpsRequired: 'Incorrect URL, https required',
10
+ addFileFailedToFetchMessage: 'Companion failed to fetch this URL, please make sure it’s correct',
11
+ addFileEnterCorrectUrlInfo: 'Incorrect URL: Please make sure you are entering a direct link to a file',
12
+ urlUiEnterPublicUrlText: 'Enter public URL of file to upload',
13
+ urlUiHttpsRequiredText: 'https required',
14
+ addFileImportingCancelledInfo: 'Importing request has just cancelled.',
15
+ addFileNoPendingImportsToCancelInfo: 'No import requests were found to cancel.'
16
+ };
package/lib/index.js ADDED
@@ -0,0 +1,268 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
5
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
6
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
7
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
8
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
9
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
10
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
11
+ function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
12
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
13
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
14
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
15
+ function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
16
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
17
+ import { Plugin } from '@scaleflex/widget-core';
18
+ import Explorer from '@scaleflex/widget-explorer';
19
+ import Translator from '@scaleflex/widget-utils/lib/Translator';
20
+ import { RequestClient } from '@scaleflex/widget-companion-client';
21
+ import { UrlIcon } from '@scaleflex/widget-icons';
22
+ import isImage from '@scaleflex/widget-utils/lib/isImage';
23
+ import isThumbnailCloudimgSupported from '@scaleflex/widget-utils/lib/isThumbnailCloudimgSupported';
24
+ import { PLUGINS_IDS } from '@scaleflex/widget-utils/lib/constants';
25
+ import { selectCurrentFolderPath } from '@scaleflex/widget-core/lib/slices/common.slice';
26
+ import defaultLocale from './defaultLocale';
27
+ import UrlUI from './UrlUI';
28
+ import forEachDroppedOrPastedUrl from './utils/forEachDroppedOrPastedUrl';
29
+ // TODO: find a way to show version of the current plugin
30
+ // why solution below isn't good?
31
+ // first import doesn't work with webpack 5 as it was deprecated
32
+ // second import fixes webpack 5 issue as it was mentioned in their docs
33
+ // but it exposes our package.json to the client and it is mentioned as security rist in mutiple places
34
+ // https://github.com/axelpale/genversion
35
+ // https://stackoverflow.com/questions/64993118/error-should-not-import-the-named-export-version-imported-as-version
36
+ // https://stackoverflow.com/questions/9153571/is-there-a-way-to-get-version-from-package-json-in-nodejs-code/10855054#10855054
37
+ // import { version } from '../package.json'
38
+ // import packageInfo from '../package.json'
39
+ var Url = /*#__PURE__*/function (_Plugin) {
40
+ // static VERSION = packageInfo.version
41
+
42
+ function Url(filerobot) {
43
+ var _this;
44
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
45
+ _classCallCheck(this, Url);
46
+ _this = _callSuper(this, Url, [filerobot, opts]);
47
+ _this.id = PLUGINS_IDS.URL;
48
+ _this.title = _this.opts.title || 'Link';
49
+ _this.type = 'acquirer';
50
+ _this.icon = UrlIcon;
51
+ _this.onRequestClose = _this.cancelImporting;
52
+ // Set default options and locale
53
+ _this.defaultLocale = {
54
+ strings: defaultLocale
55
+ };
56
+ var defaultOptions = {};
57
+ _this.opts = _objectSpread(_objectSpread({}, defaultOptions), opts);
58
+ _this.i18nInit();
59
+
60
+ // Bind all event handlers for referencability
61
+ _this.getMeta = _this.getMeta.bind(_this);
62
+ _this.addFile = _this.addFile.bind(_this);
63
+ _this.cancelImporting = _this.cancelImporting.bind(_this);
64
+ _this.handleRootDrop = _this.handleRootDrop.bind(_this);
65
+ _this.handleRootPaste = _this.handleRootPaste.bind(_this);
66
+ _this.client = new RequestClient(filerobot, {
67
+ companionHeaders: _this.opts.companionHeaders
68
+ });
69
+ _this.hostname = _this.client.companionUrl;
70
+ if (!_this.hostname) {
71
+ throw new Error('Companion hostname is required');
72
+ }
73
+ return _this;
74
+ }
75
+ _inherits(Url, _Plugin);
76
+ return _createClass(Url, [{
77
+ key: "i18nInit",
78
+ value: function i18nInit() {
79
+ this.translator = new Translator([this.defaultLocale, this.filerobot.locale, this.opts.locale]);
80
+ this.i18n = this.translator.translate.bind(this.translator);
81
+ this.i18nArray = this.translator.translateArray.bind(this.translator);
82
+ }
83
+ }, {
84
+ key: "getFileNameFromUrl",
85
+ value: function getFileNameFromUrl(url) {
86
+ var urlParamsRegex = /\?(.*)/gm;
87
+ return url.substring(url.lastIndexOf('/') + 1).replace(urlParamsRegex, '');
88
+ }
89
+ }, {
90
+ key: "checkIfCorrectURL",
91
+ value: function checkIfCorrectURL(url) {
92
+ var webProtocolRegex = /^http(s)?:\/\//;
93
+ if (!url || !webProtocolRegex.test(url)) {
94
+ return false;
95
+ }
96
+ return true;
97
+ }
98
+ }, {
99
+ key: "addProtocolToURL",
100
+ value: function addProtocolToURL(url) {
101
+ var protocolRegex = /^[a-z0-9]+:\/\//;
102
+ var defaultProtocol = 'http://';
103
+ if (protocolRegex.test(url)) {
104
+ return url;
105
+ }
106
+ return defaultProtocol + url;
107
+ }
108
+ }, {
109
+ key: "getCurrentFolderPath",
110
+ value: function getCurrentFolderPath() {
111
+ var state = this.filerobot.getGlobalState();
112
+ return selectCurrentFolderPath(state);
113
+ }
114
+ }, {
115
+ key: "getMeta",
116
+ value: async function getMeta(url) {
117
+ var _this2 = this;
118
+ return this.client.post('url/meta', {
119
+ url: url
120
+ }).then(function (res) {
121
+ if (res.error) {
122
+ _this2.filerobot.log('[URL] Error:');
123
+ _this2.filerobot.log(res.error);
124
+ throw new Error('Failed to fetch the file');
125
+ }
126
+ return res;
127
+ });
128
+ }
129
+ }, {
130
+ key: "addFile",
131
+ value: function addFile(_ref) {
132
+ var _this3 = this;
133
+ var _ref$url = _ref.url,
134
+ url = _ref$url === void 0 ? '' : _ref$url,
135
+ toFolder = _ref.toFolder,
136
+ _ref$callback = _ref.callback,
137
+ callback = _ref$callback === void 0 ? function () {
138
+ return undefined;
139
+ } : _ref$callback,
140
+ _ref$onError = _ref.onError,
141
+ onError = _ref$onError === void 0 ? function () {
142
+ return undefined;
143
+ } : _ref$onError;
144
+ if (!url) {
145
+ return;
146
+ }
147
+ if (url.toLowerCase().startsWith('www.')) {
148
+ url = this.addProtocolToURL(url);
149
+ }
150
+ if (!this.checkIfCorrectURL(url)) {
151
+ this.filerobot.log("[URL] Incorrect URL entered: ".concat(url));
152
+ this.filerobot.info(this.i18n('addFileEnterCorrectUrlInfo'), 'warning', 5000);
153
+ return onError();
154
+ }
155
+ return this.getMeta(url).then(function (meta) {
156
+ var tagFile = {
157
+ source: _this3.id,
158
+ name: _this3.getFileNameFromUrl(url),
159
+ type: meta.type,
160
+ toFolder: toFolder,
161
+ data: {
162
+ size: meta.size
163
+ },
164
+ isRemote: true,
165
+ body: {
166
+ url: url
167
+ },
168
+ remote: {
169
+ companionUrl: _this3.client.companionUrl,
170
+ url: "".concat(_this3.hostname, "/url/get"),
171
+ body: {
172
+ fileId: url,
173
+ url: url
174
+ },
175
+ providerOptions: _this3.client.opts
176
+ }
177
+ };
178
+ if (!isImage(tagFile) && isThumbnailCloudimgSupported(tagFile)) {
179
+ tagFile.preview = "https://".concat(_this3.filerobot.opts.container, ".filerobot.com/").concat(encodeURIComponent(url), "?bypass_process_proxy=1&ci_url_encoded=1");
180
+ }
181
+ return tagFile;
182
+ }).then(function (tagFile) {
183
+ _this3.filerobot.log('[Url] Adding remote file');
184
+ try {
185
+ _this3.filerobot.addFile(tagFile);
186
+ callback(tagFile);
187
+ } catch (err) {
188
+ onError(err);
189
+ if (!err.isRestriction) {
190
+ _this3.filerobot.log(err);
191
+ }
192
+ }
193
+ })["catch"](function (err) {
194
+ _this3.filerobot.log(err);
195
+ onError(err);
196
+ _this3.filerobot.info({
197
+ message: _this3.i18n('addFileFailedToFetchMessage'),
198
+ details: err.message
199
+ }, 'error', 5000);
200
+ });
201
+ }
202
+ }, {
203
+ key: "cancelImporting",
204
+ value: function cancelImporting() {
205
+ var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {
206
+ return undefined;
207
+ };
208
+ if (this.client.checkIfTherePendingRequests()) {
209
+ this.client.cancel();
210
+ this.filerobot.hideInfo();
211
+ this.filerobot.info(this.i18n('addFileImportingCancelledInfo'), 'warning');
212
+ } else {
213
+ this.filerobot.info(this.i18n('addFileNoPendingImportsToCancelInfo'));
214
+ }
215
+ callback();
216
+ }
217
+ }, {
218
+ key: "handleRootDrop",
219
+ value: function handleRootDrop(e) {
220
+ var _this4 = this;
221
+ forEachDroppedOrPastedUrl(e.dataTransfer, 'drop', function (url) {
222
+ _this4.filerobot.log("[URL] Adding file from dropped url: ".concat(url));
223
+ _this4.addFile({
224
+ url: url,
225
+ toFolder: _this4.getCurrentFolderPath()
226
+ });
227
+ });
228
+ }
229
+ }, {
230
+ key: "handleRootPaste",
231
+ value: function handleRootPaste(e) {
232
+ var _this5 = this;
233
+ var tagName = e.target.tagName;
234
+ if (tagName === 'INPUT' || tagName === 'TEXTAREA') {
235
+ return;
236
+ }
237
+ forEachDroppedOrPastedUrl(e.clipboardData, 'paste', function (url) {
238
+ _this5.filerobot.log("[URL] Adding file from pasted url: ".concat(url));
239
+ _this5.addFile({
240
+ url: url,
241
+ toFolder: _this5.getCurrentFolderPath()
242
+ });
243
+ });
244
+ }
245
+ }, {
246
+ key: "render",
247
+ value: function render() {
248
+ return UrlUI({
249
+ i18n: this.i18n,
250
+ addFile: this.addFile,
251
+ fileName: this.getFileNameFromUrl
252
+ });
253
+ }
254
+ }, {
255
+ key: "install",
256
+ value: function install() {
257
+ if (Explorer) {
258
+ this.mount(Explorer, this);
259
+ }
260
+ }
261
+ }, {
262
+ key: "uninstall",
263
+ value: function uninstall() {
264
+ this.unmount();
265
+ }
266
+ }]);
267
+ }(Plugin);
268
+ export { Url as default };
@@ -0,0 +1,94 @@
1
+ import toArray from '@scaleflex/widget-utils/lib/toArray';
2
+
3
+ /*
4
+ SITUATION
5
+
6
+ 1. Cross-browser dataTransfer.items
7
+
8
+ paste in chrome [Copy Image]:
9
+ 0: {kind: "file", type: "image/png"}
10
+ 1: {kind: "string", type: "text/html"}
11
+ paste in safari [Copy Image]:
12
+ 0: {kind: "file", type: "image/png"}
13
+ 1: {kind: "string", type: "text/html"}
14
+ 2: {kind: "string", type: "text/plain"}
15
+ 3: {kind: "string", type: "text/uri-list"}
16
+ paste in firefox [Copy Image]:
17
+ 0: {kind: "file", type: "image/png"}
18
+ 1: {kind: "string", type: "text/html"}
19
+
20
+ paste in chrome [Copy Image Address]:
21
+ 0: {kind: "string", type: "text/plain"}
22
+ paste in safari [Copy Image Address]:
23
+ 0: {kind: "string", type: "text/plain"}
24
+ 1: {kind: "string", type: "text/uri-list"}
25
+ paste in firefox [Copy Image Address]:
26
+ 0: {kind: "string", type: "text/plain"}
27
+
28
+ drop in chrome [from browser]:
29
+ 0: {kind: "string", type: "text/uri-list"}
30
+ 1: {kind: "string", type: "text/html"}
31
+ drop in safari [from browser]:
32
+ 0: {kind: "string", type: "text/uri-list"}
33
+ 1: {kind: "string", type: "text/html"}
34
+ 2: {kind: "file", type: "image/png"}
35
+ drop in firefox [from browser]:
36
+ 0: {kind: "string", type: "text/uri-list"}
37
+ 1: {kind: "string", type: "text/x-moz-url"}
38
+ 2: {kind: "string", type: "text/plain"}
39
+
40
+ 2. We can determine if it's a 'copypaste' or a 'drop', but we can't discern between [Copy Image] and [Copy Image Address].
41
+
42
+ CONCLUSION
43
+
44
+ 1. 'paste' ([Copy Image] or [Copy Image Address], we can't discern between these two)
45
+ Don't do anything if there is 'file' item. .handlePaste in the ExplorerPlugin will deal with all 'file' items.
46
+ If there are no 'file' items - handle 'text/plain' items.
47
+
48
+ 2. 'drop'
49
+ Take 'text/uri-list' items. Safari has an additional item of .kind === 'file', and you may worry about the item being duplicated (first by ExplorerPlugin, and then by UrlPlugin, now), but don't. Directory handling code won't pay attention to this particular item of kind 'file'.
50
+ */
51
+
52
+ /**
53
+ * Finds all links dropped/pasted from one browser window to another.
54
+ *
55
+ * @param {object} dataTransfer - DataTransfer instance, e.g. e.clipboardData, or e.dataTransfer
56
+ * @param {string} isDropOrPaste - either 'drop' or 'paste'
57
+ * @param {Function} callback - (urlString) => {}
58
+ */
59
+ export default function forEachDroppedOrPastedUrl(dataTransfer, isDropOrPaste, callback) {
60
+ var items = toArray(dataTransfer.items);
61
+ var urlItems;
62
+ switch (isDropOrPaste) {
63
+ case 'paste':
64
+ {
65
+ var atLeastOneFileIsDragged = items.some(function (item) {
66
+ return item.kind === 'file';
67
+ });
68
+ if (atLeastOneFileIsDragged) {
69
+ return;
70
+ } else {
71
+ urlItems = items.filter(function (item) {
72
+ return item.kind === 'string' && item.type === 'text/plain';
73
+ });
74
+ }
75
+ break;
76
+ }
77
+ case 'drop':
78
+ {
79
+ urlItems = items.filter(function (item) {
80
+ return item.kind === 'string' && item.type === 'text/uri-list';
81
+ });
82
+ break;
83
+ }
84
+ default:
85
+ {
86
+ throw new Error("isDropOrPaste must be either 'drop' or 'paste', but it's ".concat(isDropOrPaste));
87
+ }
88
+ }
89
+ urlItems.forEach(function (item) {
90
+ item.getAsString(function (urlString) {
91
+ return callback(urlString);
92
+ });
93
+ });
94
+ }