@canalis/react-link
Version:
265 lines (253 loc) • 9.22 kB
JavaScript
import require$$0, { useEffect, useCallback } from 'react';
function _iterableToArrayLimit(arr, i) {
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _s,
_e,
_x,
_r,
_arr = [],
_n = !0,
_d = !1;
try {
if (_x = (_i = _i.call(arr)).next, 0 === i) {
if (Object(_i) !== _i) return;
_n = !1;
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally {
try {
if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
} finally {
if (_d) throw _e;
}
}
return _arr;
}
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
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.");
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var lib = {};
var useScript$1 = {};
(function (exports) {
var __rest = commonjsGlobal && commonjsGlobal.__rest || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.scripts = void 0;
var react_1 = require$$0;
// Previously loading/loaded scripts and their current status
exports.scripts = {};
// Check for existing <script> tags with this src. If so, update scripts[src]
// and return the new status; otherwise, return undefined.
var checkExisting = function (src) {
var existing = document.querySelector("script[src=\"" + src + "\"]");
if (existing) {
// Assume existing <script> tag is already loaded,
// and cache that data for future use.
return exports.scripts[src] = {
loading: false,
error: null,
scriptEl: existing
};
}
return undefined;
};
function useScript(_a) {
var src = _a.src,
_b = _a.checkForExisting,
checkForExisting = _b === void 0 ? false : _b,
attributes = __rest(_a, ["src", "checkForExisting"]);
// Check whether some instance of this hook considered this src.
var status = src ? exports.scripts[src] : undefined;
// If requested, check for existing <script> tags with this src
// (unless we've already loaded the script ourselves).
if (!status && checkForExisting && src && isBrowser) {
status = checkExisting(src);
}
var _c = (0, react_1.useState)(status ? status.loading : Boolean(src)),
loading = _c[0],
setLoading = _c[1];
var _d = (0, react_1.useState)(status ? status.error : null),
error = _d[0],
setError = _d[1];
// Tracks if script is loaded so we can avoid duplicate script tags
var _e = (0, react_1.useState)(false),
scriptLoaded = _e[0],
setScriptLoaded = _e[1];
(0, react_1.useEffect)(function () {
// Nothing to do on server, or if no src specified, or
// if script is already loaded or "error" state.
if (!isBrowser || !src || scriptLoaded || error) return;
// Check again for existing <script> tags with this src
// in case it's changed since mount.
// eslint-disable-next-line react-hooks/exhaustive-deps
status = exports.scripts[src];
if (!status && checkForExisting) {
status = checkExisting(src);
}
// Determine or create <script> element to listen to.
var scriptEl;
if (status) {
scriptEl = status.scriptEl;
} else {
scriptEl = document.createElement('script');
scriptEl.src = src;
Object.keys(attributes).forEach(function (key) {
if (scriptEl[key] === undefined) {
scriptEl.setAttribute(key, attributes[key]);
} else {
scriptEl[key] = attributes[key];
}
});
status = exports.scripts[src] = {
loading: true,
error: null,
scriptEl: scriptEl
};
}
// `status` is now guaranteed to be defined: either the old status
// from a previous load, or a newly created one.
var handleLoad = function () {
if (status) status.loading = false;
setLoading(false);
setScriptLoaded(true);
};
var handleError = function (error) {
if (status) status.error = error;
setError(error);
};
scriptEl.addEventListener('load', handleLoad);
scriptEl.addEventListener('error', handleError);
document.body.appendChild(scriptEl);
return function () {
scriptEl.removeEventListener('load', handleLoad);
scriptEl.removeEventListener('error', handleError);
};
// we need to ignore the attributes as they're a new object per call, so we'd never skip an effect call
}, [src]);
return [loading, error];
}
exports.default = useScript;
var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
})(useScript$1);
(function (exports) {
var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function (mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.scripts = exports.default = void 0;
var use_script_1 = useScript$1;
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return __importDefault(use_script_1).default;
}
});
Object.defineProperty(exports, "scripts", {
enumerable: true,
get: function () {
return use_script_1.scripts;
}
});
})(lib);
var useScript = /*@__PURE__*/getDefaultExportFromCjs(lib);
// SDK is served as static content from the GCS bucket URL.
var BASE_URL = "https://storage.googleapis.com/canalis-link-sdk/canalis-link-sdk.js";
function useCanalisLink(props) {
var _useScript = useScript({
src: BASE_URL,
checkForExisting: true
}),
_useScript2 = _slicedToArray(_useScript, 2),
loading = _useScript2[0],
errorState = _useScript2[1];
useEffect(function () {
window.addEventListener("message", postMessageListener);
return function () {
window.removeEventListener("message", postMessageListener);
};
}, [loading]);
// TODO: Give event parameter a type.
var postMessageListener = useCallback(function (event) {
// TODO: Check if the origin is not at our hosted domain (when we have one)
if (event.origin !== "http://localhost:3000") {
console.log("Unknown origin detected: ".concat(event.origin));
return;
}
// Extract data from event.
console.log(event.data);
var _event$data = event.data,
code = _event$data.code,
status = _event$data.status,
error = _event$data.error;
if (status === "success") {
props.onSuccess(code);
} else if (status === "error") {
console.log(error);
console.log(event.data.error);
props.onError && props.onError(error);
} else {
console.log("Unknown response received: ".concat(JSON.stringify(event)));
}
}, []);
var open = function open(_ref) {
var clientId = _ref.clientId,
endUserOriginId = _ref.endUserOriginId;
if (errorState) {
throw new Error("Error loading Canalis SDK: ".concat(errorState));
}
if (!window.Canalis) {
console.error("Canalis is not initialised");
return;
}
// Open modal
window.Canalis.open({
clientId: clientId,
endUserOriginId: endUserOriginId
});
};
return {
ready: !loading,
errorState: errorState,
open: open
};
}
export { useCanalisLink };
//# sourceMappingURL=index.esm.js.map