Typewriter is not working when loaded via npm import (compiled with Babel) - npm

I set up Typewriter on a site, it works fine when loaded via the direct src.
<script src="https://unpkg.com/typewriter-effect#2.3.1/dist/core.js"></script>
<script>
window.addEventListener('DOMContentLoaded', () => {document.getElementById('typewriter-container');
const typewriter = new Typewriter(whatever, { ... });
...
But when I do it with npm, it doesn't work.
What does "doing it with npm" mean?
Well, since loading stuff the traditional way seems to be outdated... I'm doing the same thing with npm and using the import into a file:
src/typewriter.js
import Typewriter from 'typewriter-effect/dist/core';
And then compiling this file with webpack and babel, and loading that file instead.
<script src="/my_site_stuff/dist/typewriter.js"></script>
This is the compiled file:
dist/typewriter.js
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/typewriter-effect/dist/core.js":
/*!*****************************************************!*\
!*** ./node_modules/typewriter-effect/dist/core.js ***!
\*****************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { "#babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
!function (e, t) {
"object" == ( false ? 0 : _typeof(exports)) && "object" == ( false ? 0 : _typeof(module)) ? module.exports = t() : true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (t),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
}("undefined" != typeof self ? self : this, function () {
return function () {
var e = {
75: function _(e) {
(function () {
var t, n, r, o, a, s;
"undefined" != typeof performance && null !== performance && performance.now ? e.exports = function () {
return performance.now();
} : "undefined" != typeof process && null !== process && process.hrtime ? (e.exports = function () {
return (t() - a) / 1e6;
}, n = process.hrtime, o = (t = function t() {
var e;
return 1e9 * (e = n())[0] + e[1];
})(), s = 1e9 * process.uptime(), a = o - s) : Date.now ? (e.exports = function () {
return Date.now() - r;
}, r = Date.now()) : (e.exports = function () {
return new Date().getTime() - r;
}, r = new Date().getTime());
}).call(this);
},
4087: function _(e, t, n) {
for (var r = n(75), o = "undefined" == typeof window ? n.g : window, a = ["moz", "webkit"], s = "AnimationFrame", i = o["request" + s], u = o["cancel" + s] || o["cancelRequest" + s], l = 0; !i && l < a.length; l++) {
i = o[a[l] + "Request" + s], u = o[a[l] + "Cancel" + s] || o[a[l] + "CancelRequest" + s];
}
if (!i || !u) {
var c = 0,
p = 0,
d = [];
i = function i(e) {
if (0 === d.length) {
var t = r(),
n = Math.max(0, 16.666666666666668 - (t - c));
c = n + t, setTimeout(function () {
var e = d.slice(0);
d.length = 0;
for (var t = 0; t < e.length; t++) {
if (!e[t].cancelled) try {
e[t].callback(c);
} catch (e) {
setTimeout(function () {
throw e;
}, 0);
}
}
}, Math.round(n));
}
return d.push({
handle: ++p,
callback: e,
cancelled: !1
}), p;
}, u = function u(e) {
for (var t = 0; t < d.length; t++) {
d[t].handle === e && (d[t].cancelled = !0);
}
};
}
e.exports = function (e) {
return i.call(o, e);
}, e.exports.cancel = function () {
u.apply(o, arguments);
}, e.exports.polyfill = function (e) {
e || (e = o), e.requestAnimationFrame = i, e.cancelAnimationFrame = u;
};
}
},
t = {};
function n(r) {
var o = t[r];
if (void 0 !== o) return o.exports;
var a = t[r] = {
exports: {}
};
return e[r].call(a.exports, a, a.exports, n), a.exports;
}
n.n = function (e) {
var t = e && e.__esModule ? function () {
return e.default;
} : function () {
return e;
};
return n.d(t, {
a: t
}), t;
}, n.d = function (e, t) {
for (var r in t) {
n.o(t, r) && !n.o(e, r) && Object.defineProperty(e, r, {
enumerable: !0,
get: t[r]
});
}
}, n.g = function () {
if ("object" == (typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis))) return globalThis;
try {
return this || new Function("return this")();
} catch (e) {
if ("object" == (typeof window === "undefined" ? "undefined" : _typeof(window))) return window;
}
}(), n.o = function (e, t) {
return Object.prototype.hasOwnProperty.call(e, t);
};
var r = {};
return function () {
"use strict";
n.d(r, {
default: function _default() {
return S;
}
});
var e = n(4087),
t = n.n(e);
var o = function o(e) {
return new RegExp(/<[a-z][\s\S]*>/i).test(e);
},
a = function a(e) {
var t = document.createElement("div");
return t.innerHTML = e, t.childNodes;
},
s = function s(e, t) {
return Math.floor(Math.random() * (t - e + 1)) + e;
};
var i = "TYPE_CHARACTER",
u = "REMOVE_CHARACTER",
l = "REMOVE_ALL",
c = "REMOVE_LAST_VISIBLE_NODE",
p = "PAUSE_FOR",
d = "CALL_FUNCTION",
f = "ADD_HTML_TAG_ELEMENT",
v = "CHANGE_DELETE_SPEED",
h = "CHANGE_DELAY",
m = "CHANGE_CURSOR",
y = "PASTE_STRING",
g = "HTML_TAG";
function E(e, t) {
var n = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var r = Object.getOwnPropertySymbols(e);
t && (r = r.filter(function (t) {
return Object.getOwnPropertyDescriptor(e, t).enumerable;
})), n.push.apply(n, r);
}
return n;
}
function w(e) {
for (var t = 1; t < arguments.length; t++) {
var n = null != arguments[t] ? arguments[t] : {};
t % 2 ? E(Object(n), !0).forEach(function (t) {
N(e, t, n[t]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : E(Object(n)).forEach(function (t) {
Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
});
}
return e;
}
function T(e) {
return function (e) {
if (Array.isArray(e)) return b(e);
}(e) || function (e) {
if ("undefined" != typeof Symbol && null != e[Symbol.iterator] || null != e["##iterator"]) return Array.from(e);
}(e) || function (e, t) {
if (e) {
if ("string" == typeof e) return b(e, t);
var n = Object.prototype.toString.call(e).slice(8, -1);
return "Object" === n && e.constructor && (n = e.constructor.name), "Map" === n || "Set" === n ? Array.from(e) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? b(e, t) : void 0;
}
}(e) || function () {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}();
}
function b(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var n = 0, r = new Array(t); n < t; n++) {
r[n] = e[n];
}
return r;
}
function A(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);
}
}
function N(e, t, n) {
return t in e ? Object.defineProperty(e, t, {
value: n,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = n, e;
}
var S = function () {
function n(r, E) {
var b = this;
if (function (e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, n), N(this, "state", {
cursorAnimation: null,
lastFrameTime: null,
pauseUntil: null,
eventQueue: [],
eventLoop: null,
eventLoopPaused: !1,
reverseCalledEvents: [],
calledEvents: [],
visibleNodes: [],
initialOptions: null,
elements: {
container: null,
wrapper: document.createElement("span"),
cursor: document.createElement("span")
}
}), N(this, "options", {
strings: null,
cursor: "|",
delay: "natural",
pauseFor: 1500,
deleteSpeed: "natural",
loop: !1,
autoStart: !1,
devMode: !1,
skipAddStyles: !1,
wrapperClassName: "Typewriter__wrapper",
cursorClassName: "Typewriter__cursor",
stringSplitter: null,
onCreateTextNode: null,
onRemoveNode: null
}), N(this, "setupWrapperElement", function () {
b.state.elements.container && (b.state.elements.wrapper.className = b.options.wrapperClassName, b.state.elements.cursor.className = b.options.cursorClassName, b.state.elements.cursor.innerHTML = b.options.cursor, b.state.elements.container.innerHTML = "", b.state.elements.container.appendChild(b.state.elements.wrapper), b.state.elements.container.appendChild(b.state.elements.cursor));
}), N(this, "start", function () {
return b.state.eventLoopPaused = !1, b.runEventLoop(), b;
}), N(this, "pause", function () {
return b.state.eventLoopPaused = !0, b;
}), N(this, "stop", function () {
return b.state.eventLoop && ((0, e.cancel)(b.state.eventLoop), b.state.eventLoop = null), b;
}), N(this, "pauseFor", function (e) {
return b.addEventToQueue(p, {
ms: e
}), b;
}), N(this, "typeOutAllStrings", function () {
return "string" == typeof b.options.strings ? (b.typeString(b.options.strings).pauseFor(b.options.pauseFor), b) : (b.options.strings.forEach(function (e) {
b.typeString(e).pauseFor(b.options.pauseFor).deleteAll(b.options.deleteSpeed);
}), b);
}), N(this, "typeString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
if (o(e)) return b.typeOutHTMLString(e, t);
if (e) {
var n = b.options || {},
r = n.stringSplitter,
a = "function" == typeof r ? r(e) : e.split("");
b.typeCharacters(a, t);
}
return b;
}), N(this, "pasteString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
return o(e) ? b.typeOutHTMLString(e, t, !0) : (e && b.addEventToQueue(y, {
character: e,
node: t
}), b);
}), N(this, "typeOutHTMLString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null,
n = arguments.length > 2 ? arguments[2] : void 0,
r = a(e);
if (r.length > 0) for (var o = 0; o < r.length; o++) {
var s = r[o],
i = s.innerHTML;
s && 3 !== s.nodeType ? (s.innerHTML = "", b.addEventToQueue(f, {
node: s,
parentNode: t
}), n ? b.pasteString(i, s) : b.typeString(i, s)) : s.textContent && (n ? b.pasteString(s.textContent, t) : b.typeString(s.textContent, t));
}
return b;
}), n;
}();
}(), r.default;
}();
});
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/node module decorator */
/******/ !function() {
/******/ __webpack_require__.nmd = function(module) {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
/*!*************************************!*\
!*** ./src/js/typewriter-effect.js ***!
\*************************************/
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! typewriter-effect/dist/core */ "./node_modules/typewriter-effect/dist/core.js");
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__);
}();
/******/ })()
;
//# sourceMappingURL=typeWriter.js.map
How do I know what the problem is?

Webpack encloses everything in the compiled file so nothing leaks into the global scope.
You'd have to change your src file and do:
import Typewriter from 'typewriter-effect/dist/core';
window.Typewriter = Typewriter;
Then, when using it, instead of:
const typewriter = new Typewriter(...);
Just do:
const typewriter = new window.Typewriter(...);
What we are doing here is, making it available to the global scope.

Related

Trying to generate custom play button for SoundCloud API

I was experimenting with SoundCloud API in Elementor, but I couldn't solve a problem because I have very little knowledge about JS. I was trying to achieve custom play/stop button.
I added a play icon, which changes to a stop icon
It started playing as it should be, but now it's not stopping.
So when I click the icon with the id of #playBPP works well but when I click to the button again it's not working.
This is where I added JS.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<!-- SoundCloud-->
<script type="text/javascript" src="http://w.soundcloud.com/player/api.js"></script>
<script type="text/javascript">
// Play - Stop
$(function(){
var widget1 = SC.Widget("bppRadioPlayer");
$("#playBPP").click(function() {
widget1.play();
});
$("toggle-pause").click(function() {
widget1.pause();
});
});
// Audio button toggle
const audioButton = document.querySelector('.audio-button');
audioButton.addEventListener('click', function(){
audioButton.classList.toggle('toggle-pause');
});
</script>
<iframe id="bppRadioPlayer" width="100%" height="160" scrolling="no" src="http://w.soundcloud.com/player/?url=https://soundcloud.com/sdyld/bpp-bonvoyage" frameborder="0" ></iframe>
Icon HTML
<div class="elementor-element elementor-element-ff4607e audio-button elementor-view-default elementor-widget elementor-widget-icon" data-id="ff4607e" data-element_type="widget" id="playBPP" data-widget_type="icon.default">
<div class="elementor-widget-container">
<div class="elementor-icon-wrapper">
<div class="elementor-icon">
<i aria-hidden="true" class="fas fa-play"></i> </div>
</div>
</div>
</div>
.toggle-pause .elementor-icon i::before{
content: '\f04c';
}
check out the page screenshot
I updated the snippet to achieve the goal, dropping here, so you can use.
var SC = "object" == typeof SC ? SC : {};
SC.Widget = function(e) {
var t = {};
function n(r) {
if (t[r]) return t[r].exports;
var o = t[r] = {
i: r,
l: !1,
exports: {}
};
return e[r].call(o.exports, o, o.exports, n), o.l = !0, o.exports
}
return n.m = e, n.c = t, n.d = function(e, t, r) {
n.o(e, t) || Object.defineProperty(e, t, {
enumerable: !0,
get: r
})
}, n.r = function(e) {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {
value: "Module"
}), Object.defineProperty(e, "__esModule", {
value: !0
})
}, n.t = function(e, t) {
if (1 & t && (e = n(e)), 8 & t) return e;
if (4 & t && "object" == typeof e && e && e.__esModule) return e;
var r = Object.create(null);
if (n.r(r), Object.defineProperty(r, "default", {
enumerable: !0,
value: e
}), 2 & t && "string" != typeof e)
for (var o in e) n.d(r, o, function(t) {
return e[t]
}.bind(null, o));
return r
}, n.n = function(e) {
var t = e && e.__esModule ? function() {
return e.default
} : function() {
return e
};
return n.d(t, "a", t), t
}, n.o = function(e, t) {
return Object.prototype.hasOwnProperty.call(e, t)
}, n.p = "", n(n.s = 0)
}([function(e, t, n) {
var r, o, i, u = n(1),
a = n(2),
c = n(3),
s = u.api,
l = u.bridge,
d = [],
f = [],
p = /^http(?:s?)/;
function E(e) {
var t, n;
for (t = 0, n = f.length; t < n && !1 !== e(f[t]); t++);
}
function v(e) {
return e.contentWindow ? e.contentWindow : e.contentDocument && "parentWindow" in e.contentDocument ? e.contentDocument.parentWindow : null
}
function _(e) {
var t, n = [];
for (t in e) e.hasOwnProperty(t) && n.push(e[t]);
return n
}
function S(e, t, n) {
n.callbacks[e] = n.callbacks[e] || [], n.callbacks[e].push(t)
}
function h(e, t) {
var n = !0;
return t.callbacks[e] = [], E((function(t) {
if ((t.callbacks[e] || []).length) return n = !1, !1
})), n
}
function y(e, t, n) {
var r, o, i = v(n);
if (!i.postMessage) return !1;
r = n.getAttribute("src").split("?")[0], o = JSON.stringify({
method: e,
value: t
}), "//" === r.substr(0, 2) && (r = window.location.protocol + r), r = r.replace(/http:\/\/(w|wt).soundcloud.com/, "https://$1.soundcloud.com"), i.postMessage(o, r)
}
function b(e) {
var t;
return E((function(n) {
if (n.instance === e) return t = n, !1
})), t
}
function g(e) {
var t;
return E((function(n) {
if (v(n.element) === e) return t = n, !1
})), t
}
function m(e, t) {
return function(n) {
var r, o = !!((r = n) && r.constructor && r.call && r.apply),
i = b(this),
u = !o && t ? n : null,
a = o && !t ? n : null;
return a && S(e, a, i), y(e, u, i.element), this
}
}
function R(e, t, n) {
var r, o, i;
for (r = 0, o = t.length; r < o; r++) e[i = t[r]] = m(i, n)
}
function O(e, t, n) {
return e + "?url=" + t + "&" + function(e) {
var t, n, r = [];
for (t in e) e.hasOwnProperty(t) && (n = e[t], r.push(t + "=" + ("start_track" === t ? parseInt(n, 10) : n ? "true" : "false")));
return r.join("&")
}(n)
}
function w(e, t, n) {
var r, o, i = e.callbacks[t] || [];
for (r = 0, o = i.length; r < o; r++) i[r].apply(e.instance, n);
(function(e) {
var t, n = !1;
for (t in a)
if (a.hasOwnProperty(t) && a[t] === e) {
n = !0;
break
} return n
}(t) || t === s.READY) && (e.callbacks[t] = [])
}
function A(e) {
var t, n, r, o, i;
try {
n = JSON.parse(e.data)
} catch (e) {
return !1
}
return t = g(e.source), r = n.method, o = n.value, (!t || P(e.origin) === P(t.domain)) && (t ? (r === s.READY && (t.isReady = !0, w(t, "__LATE_BINDING__"), h("__LATE_BINDING__", t)), r !== s.PLAY || t.playEventFired || (t.playEventFired = !0), r !== s.PLAY_PROGRESS || t.playEventFired || (t.playEventFired = !0, w(t, s.PLAY, [o])), i = [], void 0 !== o && i.push(o), void w(t, r, i)) : (r === s.READY && d.push(e.source), !1))
}
function P(e) {
return e.replace(p, "")
}
window.addEventListener ? window.addEventListener("message", A, !1) : window.attachEvent("onmessage", A), e.exports = i = function(e, t, n) {
var i;
if (("" === (i = e) || i && i.charCodeAt && i.substr) && (e = document.getElementById(e)), ! function(e) {
return !(!e || 1 !== e.nodeType || "IFRAME" !== e.nodeName.toUpperCase())
}(e)) throw new Error("SC.Widget function should be given either iframe element or a string specifying id attribute of iframe element.");
t && (n = n || {}, e.src = O("http://wt.soundcloud.test:9200/", t, n));
var u, a, c = g(v(e));
return c && c.instance ? c.instance : (u = d.indexOf(v(e)) > -1, a = new r(e), f.push(new o(a, e, u)), a)
}, i.Events = s, window.SC = window.SC || {}, window.SC.Widget = i, o = function(e, t, n) {
this.instance = e, this.element = t, this.domain = function(e) {
var t, n, r, o = "";
"//" === e.substr(0, 2) && (e = window.location.protocol + e);
for (r = e.split("/"), t = 0, n = r.length; t < n && t < 3; t++) o += r[t], t < 2 && (o += "/");
return o
}(t.getAttribute("src")), this.isReady = !!n, this.callbacks = {}
}, (r = function() {}).prototype = {
constructor: r,
load: function(e, t) {
if (e) {
t = t || {};
var n = this,
r = b(this),
o = r.element,
i = o.src,
u = i.substr(0, i.indexOf("?"));
r.isReady = !1, r.playEventFired = !1, o.onload = function() {
n.bind(s.READY, (function() {
var e, n = r.callbacks;
for (e in n) n.hasOwnProperty(e) && e !== s.READY && y(l.ADD_LISTENER, e, r.element);
t.callback && t.callback()
}))
}, o.src = O(u, e, t)
}
},
bind: function(e, t) {
var n = this,
r = b(this);
return r && r.element && (e === s.READY && r.isReady ? setTimeout(t, 1) : r.isReady ? (S(e, t, r), y(l.ADD_LISTENER, e, r.element)) : S("__LATE_BINDING__", (function() {
n.bind(e, t)
}), r)), this
},
unbind: function(e) {
var t, n = b(this);
n && n.element && (t = h(e, n), e !== s.READY && t && y(l.REMOVE_LISTENER, e, n.element))
}
}, R(r.prototype, _(a)), R(r.prototype, _(c), !0)
}, function(e, t) {
t.api = {
LOAD_PROGRESS: "loadProgress",
PLAY_PROGRESS: "playProgress",
PLAY: "play",
PAUSE: "pause",
FINISH: "finish",
SEEK: "seek",
READY: "ready",
OPEN_SHARE_PANEL: "sharePanelOpened",
CLICK_DOWNLOAD: "downloadClicked",
CLICK_BUY: "buyClicked",
ERROR: "error"
}, t.bridge = {
REMOVE_LISTENER: "removeEventListener",
ADD_LISTENER: "addEventListener"
}
}, function(e, t) {
e.exports = {
GET_VOLUME: "getVolume",
GET_DURATION: "getDuration",
GET_POSITION: "getPosition",
GET_SOUNDS: "getSounds",
GET_CURRENT_SOUND: "getCurrentSound",
GET_CURRENT_SOUND_INDEX: "getCurrentSoundIndex",
IS_PAUSED: "isPaused"
}
}, function(e, t) {
e.exports = {
PLAY: "play",
PAUSE: "pause",
TOGGLE: "toggle",
SEEK_TO: "seekTo",
SET_VOLUME: "setVolume",
NEXT: "next",
PREV: "prev",
SKIP: "skip"
}
}]);
//# sourceMappingURL=http://ent/web-sourcemaps/api.js-27d0ec1de3c5.map
const widget = SC.Widget(document.getElementById('track'));
const playBtn = document.getElementById("playRadio");
playBtn.addEventListener('click', function(e) {
e.preventDefault();
widget.toggle();
});
function myFunction(x) {
x.classList.toggle("fa-stop");
}
widget.getCurrentSoundIndex(function(sound) {
console.log(sound.title);
});
#playRadio {
font-size: 72px;
width: 50%;
text-align: center;
padding: 40px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://kit.fontawesome.com/0b1431f7fb.js" crossorigin="anonymous"></script>
</head>
<body>
<i id="playRadio" onclick="myFunction(this)" class="fas fa-play"></i>
<iframe id="track" width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/249593158&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false"></iframe>
</body>
</html>

hide index.php from ajax load search in osclass

link look like http://localhost/index.php?page=search&sOrder=dt_pub_date&iOrderType=desc&sPattern=car
// AJAX SEARCH
$('body#body-search').on('change click', '.link-check-box a, .filter-remove a, form.search-side-form input:not(.term), body#body-search #sub-nav a, #home-cat a, #sub-cat a, form.search-side-form select, .sort-it a, .user-type a,.list-grid a, .paginate a', function(event) {
var ajaxStop = false;
if(ajaxSearch == 1 && event.type != 'change') {
event.preventDefault();
}
// Disable on mobile devices when input selected from fancybox
if($(event.target).closest('.search-mobile-filter-box').length) {
if(!$(event.target).closest('#search-sort').length && !$(event.target).closest('.sub-line').length) { // it may not be required
var ajaxStop = true;
//return false;
}
}
var sidebarReload = true;
if($(this).closest('.sidebar-hooks').length || $(event.target).attr('name') == 'locUpdate') {
sidebarReload = false;
}
var sidebar = $('.filter form.search-side-form');
var ajaxSearchUrl = '';
if (event.type == 'click') {
if(typeof $(this).attr('href') !== typeof undefined && $(this).attr('href') !== false) {
ajaxSearchUrl = $(this).attr('href');
}
} else if (event.type == 'change') {
ajaxSearchUrl = baseDir + "index.php?" + sidebar.find(':input[value!=""]').serialize();
}
if(ajaxSearch == 1 && $('input[name="ajaxRun"]').val() != "1" && (ajaxSearchUrl != '#' && ajaxSearchUrl != '') && !ajaxStop) {
if(ajaxSearchUrl == $(location).attr('href')) {
return false;
}
sidebar.find('.init-search').addClass('btn-loading').addClass('disabled').attr('disabled', true);
sidebar.find('input[name="ajaxRun"]').val("1");
$('#search-items').addClass('loading');
$.ajax({
url: ajaxSearchUrl,
type: "GET",
success: function(response){
var length = response.length;
var data = $(response).contents().find('#main').html();
var bread = $(response).contents().find('ul.breadcrumb');
var filter = $(response).contents().find('.filter').html();
sidebar.find('.init-search').removeClass('btn-loading').removeClass('disabled').attr('disabled', false);
sidebar.find('input[name="ajaxRun"]').val("");
$('#main').fadeOut(0, function(){
$('#main').html(data).show(0);
$('#search-items').hide(0);
$('#search-items').removeClass('loading');
$('#search-items').show(0).css('opacity', 0).css('margin-top', '50px').css('margin-bottom', '-50px').animate( { opacity: 1, marginTop:'0', marginBottom:'0'} , 300);
});
if(sidebarReload) {
$('.filter').html(filter);
}
$('ul.breadcrumb').html(bread);

What is the fastest way to create a union of many polygons in turfjs?

I have something like this but with large sets it's awfully slow:
let unionize = (triangles) => {
if(triangles.length == 0) {
return null
}
let ret = triangles[0].feature
triangles.forEach((t, index) => {
if(index > 0) {
ret = turf.union(t, t)
}
})
return ret
}
featureEach tends to be faster than a trivial array forEach although with more features the gain decreases.
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#5.1.6/turf.min.js"></script>
<script>
const generateGrid = (cellSide = 100, units = "kilometers") => {
const bbox = [-95, 30, -85, 40];
return turf.triangleGrid(bbox, cellSide, {
units
});
}
const unionizeForEach = (triangles) => {
console.time('unionizeForEach');
if (triangles.length == 0) {
return null
}
let ret = triangles[0];
triangles.forEach((t, index) => {
if (index > 0) {
ret = turf.union(ret, t)
}
});
console.timeEnd('unionizeForEach');
return ret
}
const unionizeFeatureEach = (triangles) => {
console.time('unionizeFeatureEach');
if (triangles.features.length === 0) {
return null
}
let ret = triangles.features[0];
turf.featureEach(triangles, function (currentFeature, featureIndex) {
if (featureIndex > 0) {
ret = turf.union(ret, currentFeature)
}
});
console.timeEnd('unionizeFeatureEach');
return ret;
}
[100, 50, 10].map(cellSide => {
const triangleGrid = generateGrid(cellSide, 'kilometers');
console.info(`triangleGrid has ${triangleGrid.features.length} features`);
const union_foreach = unionizeForEach(triangleGrid.features);
const union_featureeach = unionizeFeatureEach(triangleGrid);
console.assert(JSON.stringify(union_foreach) === JSON.stringify(union_featureeach));
console.log('\n---\n');
})
</script>

Webrtc video chat not working in different networks

I am trying to implement video chat with webrtc using code from google code labs . It works fine on same network but does not work on different network. i have installed coturn on my server. I am not sure if it is working correctly.
Any one used google codelabs code and made it working?
This is the modified main.js file
'use strict';
var isChannelReady = false;
var isInitiator = false;
var isStarted = false;
var localStream;
var pc;
var remoteStream;
var turnReady;
var pcConfig = {
"iceServers":[
{'urls': 'stun:stun.l.google.com:19302'},
{"urls":["turn:78.129.167.90"],"username":"wyzturner1","credential":"wyzturnp2ss"}]
};
// Set up audio and video regardless of what devices are present.
var sdpConstraints = {
offerToReceiveAudio: true,
offerToReceiveVideo: true
};
/////////////////////////////////////////////
var room = 'foo';
// Could prompt for room name:
// room = prompt('Enter room name:');
var socket = io.connect('https://www.samplesite.com:8080');
if (room !== '') {
socket.emit('create or join', room);
console.log('Attempted to create or join room', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
isInitiator = true;
});
socket.on('full', function(room) {
console.log('Room ' + room + ' is full');
});
socket.on('join', function (room){
console.log('Another peer made a request to join room ' + room);
console.log('This peer is the initiator of room ' + room + '!');
isChannelReady = true;
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
isChannelReady = true;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
function sendMessage(message) {
console.log('Client sending message: ', message);
socket.emit('message', message);
}
// This client receives a message
socket.on('message', function(message) {
console.log('Client received message:', message);
if (message === 'got user media') {
maybeStart();
} else if (message.type === 'offer') {
if (!isInitiator && !isStarted) {
maybeStart();
}
pc.setRemoteDescription(new RTCSessionDescription(message));
doAnswer();
} else if (message.type === 'answer' && isStarted) {
pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate' && isStarted) {
var candidate = new RTCIceCandidate({
sdpMLineIndex: message.label,
candidate: message.candidate
});
pc.addIceCandidate(candidate);
} else if (message === 'bye' && isStarted) {
handleRemoteHangup();
}
});
////////////////////////////////////////////////////
var localVideo = document.querySelector('#localVideo');
var remoteVideo = document.querySelector('#remoteVideo');
navigator.mediaDevices.getUserMedia({
audio: false,
video: true
})
.then(gotStream)
.catch(function(e) {
alert('getUserMedia() error: ' + e.name);
});
function gotStream(stream) {
console.log('Adding local stream.');
localVideo.src = window.URL.createObjectURL(stream);
localStream = stream;
sendMessage('got user media');
if (isInitiator) {
maybeStart();
}
}
var constraints = {
video: true
};
console.log('Getting user media with constraints', constraints);
//if (location.hostname !== 'localhost') {
// requestTurn(
// 'https://computeengineondemand.appspot.com/turn?username=41784574&key=4080218913'
// );
//}
function maybeStart() {
console.log('>>>>>>> maybeStart() ', isStarted, localStream, isChannelReady);
if (!isStarted && typeof localStream !== 'undefined' && isChannelReady) {
console.log('>>>>>> creating peer connection');
createPeerConnection();
isStarted = true;
console.log('isInitiator', isInitiator);
if (isInitiator) {
doCall();
}
}
}
window.onbeforeunload = function() {
sendMessage('bye');
};
/////////////////////////////////////////////////////////
function createPeerConnection() {
try {
pc = new RTCPeerConnection(pcConfig);
pc.addStream(localStream);
pc.onicecandidate = handleIceCandidate;
pc.onaddstream = handleRemoteStreamAdded;
pc.oniceconnectionstatechange = function(){
console.log('ICE state: ',pc.iceConnectionState);
}
pc.onremovestream = handleRemoteStreamRemoved;
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function handleIceCandidate(event) {
console.log('icecandidate event: ', event);
if (event.candidate) {
sendMessage({
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
});
} else {
console.log('End of candidates.');
}
}
function handleRemoteStreamAdded(event) {
console.log('Remote stream added.');
remoteVideo.src = window.URL.createObjectURL(event.stream);
remoteStream = event.stream;
}
function handleCreateOfferError(event) {
console.log('createOffer() error: ', event);
}
function doCall() {
console.log('Sending offer to peer');
pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}
function doAnswer() {
console.log('Sending answer to peer.');
pc.createAnswer().then(
setLocalAndSendMessage,
onCreateSessionDescriptionError
);
}
function setLocalAndSendMessage(sessionDescription) {
// Set Opus as the preferred codec in SDP if Opus is present.
// sessionDescription.sdp = preferOpus(sessionDescription.sdp);
pc.setLocalDescription(sessionDescription);
console.log('setLocalAndSendMessage sending message', sessionDescription);
sendMessage(sessionDescription);
}
function onCreateSessionDescriptionError(error) {
trace('Failed to create session description: ' + error.toString());
}
function requestTurn(turnURL) {
var turnExists = false;
for (var i in pcConfig.iceServers) {
if (pcConfig.iceServers[i].urls.substr(0, 5) === 'turn:') {
turnExists = true;
turnReady = true;
break;
}
}
// if (!turnExists) {
// console.log('Getting TURN server from ', turnURL);
// // No TURN server. Get one from computeengineondemand.appspot.com:
// var xhr = new XMLHttpRequest();
// xhr.onreadystatechange = function() {
// if (xhr.readyState === 4 && xhr.status === 200) {
// var turnServer = JSON.parse(xhr.responseText);
// console.log('Got TURN server: ', turnServer);
// pcConfig.iceServers.push({
// 'url': 'turn:' + turnServer.username + '#' + turnServer.turn,
// 'credential': turnServer.password
// });
// turnReady = true;
// }
// };
// xhr.open('GET', turnURL, true);
// xhr.send();
// }
}
function handleRemoteStreamAdded(event) {
console.log('Remote stream added.');
remoteVideo.src = window.URL.createObjectURL(event.stream);
remoteStream = event.stream;
}
function handleRemoteStreamRemoved(event) {
console.log('Remote stream removed. Event: ', event);
}
function hangup() {
console.log('Hanging up.');
stop();
sendMessage('bye');
}
function handleRemoteHangup() {
console.log('Session terminated.');
stop();
isInitiator = false;
}
function stop() {
isStarted = false;
// isAudioMuted = false;
// isVideoMuted = false;
pc.close();
pc = null;
}
///////////////////////////////////////////
// Set Opus as the default audio codec if it's present.
function preferOpus(sdp) {
var sdpLines = sdp.split('\r\n');
var mLineIndex;
// Search for m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('m=audio') !== -1) {
mLineIndex = i;
break;
}
}
if (mLineIndex === null) {
return sdp;
}
// If Opus is available, set it as the default in m line.
for (i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('opus/48000') !== -1) {
var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
if (opusPayload) {
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex],
opusPayload);
}
break;
}
}
// Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
return sdp;
}
function extractSdp(sdpLine, pattern) {
var result = sdpLine.match(pattern);
return result && result.length === 2 ? result[1] : null;
}
// Set the selected codec to the first in m line.
function setDefaultCodec(mLine, payload) {
var elements = mLine.split(' ');
var newLine = [];
var index = 0;
for (var i = 0; i < elements.length; i++) {
if (index === 3) { // Format of media starts from the fourth.
newLine[index++] = payload; // Put target payload to the first.
}
if (elements[i] !== payload) {
newLine[index++] = elements[i];
}
}
return newLine.join(' ');
}
// Strip CN from sdp before CN constraints is ready.
function removeCN(sdpLines, mLineIndex) {
var mLineElements = sdpLines[mLineIndex].split(' ');
// Scan from end for the convenience of removing an item.
for (var i = sdpLines.length - 1; i >= 0; i--) {
var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
if (payload) {
var cnPos = mLineElements.indexOf(payload);
if (cnPos !== -1) {
// Remove CN payload from m line.
mLineElements.splice(cnPos, 1);
}
// Remove CN line in sdp
sdpLines.splice(i, 1);
}
}
sdpLines[mLineIndex] = mLineElements.join(' ');
return sdpLines;
}

Trello API add base64 data image as an attachement

I'd like to send base64 image as an attachment to a trello card through the API
POST /1/cards/[card id or shortlink]/attachments
There's a file field but it does not specify how should look the data there.
Refs: https://developers.trello.com/advanced-reference/card#post-1-cards-card-id-or-shortlink-attachments
Any idea?
Short answer: Trello's API only works to attach binary data via multipart/form-data. Examples below.
Long answer:
The Trello API to add attachments and images is frustratingly under-documented. They do have a coffeescript Client.js for those of us using Javascript to simplify all the basic operations: https://trello.com/1/client.coffee
Using the vanilla Client.js file I have been able to attach links and text files. While the CURL example shows pulling a binary file in from a hard drive, that doesn't work for those of us completely on a server or client where we don't have permissions to create a file.
From a LOT of trial and error, I've determined all binary data (images, documents, etc.) must be attached using multipart/form-data. Here is a jQuery snippet that will take a URL to an item, get it into memory, and then send it to Trello.
var opts = {'key': 'YOUR TRELLO KEY', 'token': 'YOUR TRELLO TOKEN'};
var xhr = new XMLHttpRequest();
xhr.open('get', params); // params is a URL to a file to grab
xhr.responseType = 'blob'; // Use blob to get the file's mimetype
xhr.onload = function() {
var fileReader = new FileReader();
fileReader.onload = function() {
var filename = (params.split('/').pop().split('#')[0].split('?')[0]) || params || '?'; // Removes # or ? after filename
var file = new File([this.result], filename);
var form = new FormData(); // this is the formdata Trello needs
form.append("file", file);
$.each(['key', 'token'], function(iter, item) {
form.append(item, opts.data[item] || 'ERROR! Missing "' + item + '"');
});
$.extend(opts, {
method: "POST",
data: form,
cache: false,
contentType: false,
processData: false
});
return $.ajax(opts);
};
fileReader.readAsArrayBuffer(xhr.response); // Use filereader on blob to get content
};
xhr.send();
I have submitted a new coffeescript for Trello developer support to consider uploading to replace Client.js. It adds a "Trello.upload(url)" that does this work.
I've also attached here for convenience in JS form.
// Generated by CoffeeScript 1.12.4
(function() {
var opts={"version":1,"apiEndpoint":"https://api.trello.com","authEndpoint":"https://trello.com"};
var deferred, isFunction, isReady, ready, waitUntil, wrapper,
slice = [].slice;
wrapper = function(window, jQuery, opts) {
var $, Trello, apiEndpoint, authEndpoint, authorizeURL, baseURL, collection, fn, fn1, i, intentEndpoint, j, key, len, len1, localStorage, location, parseRestArgs, readStorage, ref, ref1, storagePrefix, token, type, version, writeStorage;
$ = jQuery;
key = opts.key, token = opts.token, apiEndpoint = opts.apiEndpoint, authEndpoint = opts.authEndpoint, intentEndpoint = opts.intentEndpoint, version = opts.version;
baseURL = apiEndpoint + "/" + version + "/";
location = window.location;
Trello = {
version: function() {
return version;
},
key: function() {
return key;
},
setKey: function(newKey) {
key = newKey;
},
token: function() {
return token;
},
setToken: function(newToken) {
token = newToken;
},
rest: function() {
var args, error, method, params, path, ref, success;
method = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
ref = parseRestArgs(args), path = ref[0], params = ref[1], success = ref[2], error = ref[3];
opts = {
url: "" + baseURL + path,
type: method,
data: {},
dataType: "json",
success: success,
error: error
};
if (!$.support.cors) {
opts.dataType = "jsonp";
if (method !== "GET") {
opts.type = "GET";
$.extend(opts.data, {
_method: method
});
}
}
if (key) {
opts.data.key = key;
}
if (token) {
opts.data.token = token;
}
if (params != null) {
$.extend(opts.data, params);
}
if (method === 'UPLOAD' && typeof (params) === "string" && params.length > 5) {
var xhr = new XMLHttpRequest();
xhr.open('get', params);
xhr.responseType = 'blob'; // Use blob to get the mimetype
xhr.onload = function() {
var fileReader = new FileReader();
fileReader.onload = function() {
var filename = (params.split('/').pop().split('#')[0].split('?')[0]) || params || '?'; // Removes # or ? after filename
var file = new File([this.result], filename);
var form = new FormData();
form.append("file", file);
$.each(['key', 'token'], function(iter, item) {
form.append(item, opts.data[item] || 'ERROR! Missing "' + item + '"');
});
$.extend(opts, {
method: "POST",
data: form,
cache: false,
contentType: false,
processData: false
});
return $.ajax(opts);
};
fileReader.readAsArrayBuffer(xhr.response); // Use filereader on blob to get content
};
xhr.send();
} else {
return $.ajax(opts);
}
},
authorized: function() {
return token != null;
},
deauthorize: function() {
token = null;
writeStorage("token", token);
},
authorize: function(userOpts) {
var k, persistToken, ref, regexToken, scope, v;
opts = $.extend(true, {
type: "redirect",
persist: true,
interactive: true,
scope: {
read: true,
write: false,
account: false
},
expiration: "30days"
}, userOpts);
regexToken = /[&#]?token=([0-9a-f]{64})/;
persistToken = function() {
if (opts.persist && (token != null)) {
return writeStorage("token", token);
}
};
if (opts.persist) {
if (token == null) {
token = readStorage("token");
}
}
if (token == null) {
token = (ref = regexToken.exec(location.hash)) != null ? ref[1] : void 0;
}
if (this.authorized()) {
persistToken();
location.hash = location.hash.replace(regexToken, "");
return typeof opts.success === "function" ? opts.success() : void 0;
}
if (!opts.interactive) {
return typeof opts.error === "function" ? opts.error() : void 0;
}
scope = ((function() {
var ref1, results;
ref1 = opts.scope;
results = [];
for (k in ref1) {
v = ref1[k];
if (v) {
results.push(k);
}
}
return results;
})()).join(",");
switch (opts.type) {
case "popup":
(function() {
var authWindow, height, left, origin, receiveMessage, ref1, top, width;
waitUntil("authorized", (function(_this) {
return function(isAuthorized) {
if (isAuthorized) {
persistToken();
return typeof opts.success === "function" ? opts.success() : void 0;
} else {
return typeof opts.error === "function" ? opts.error() : void 0;
}
};
})(this));
width = 420;
height = 470;
left = window.screenX + (window.innerWidth - width) / 2;
top = window.screenY + (window.innerHeight - height) / 2;
origin = (ref1 = /^[a-z]+:\/\/[^\/]*/.exec(location)) != null ? ref1[0] : void 0;
authWindow = window.open(authorizeURL({
return_url: origin,
callback_method: "postMessage",
scope: scope,
expiration: opts.expiration,
name: opts.name
}), "trello", "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top);
receiveMessage = function(event) {
var ref2;
if (event.origin !== authEndpoint || event.source !== authWindow) {
return;
}
if ((ref2 = event.source) != null) {
ref2.close();
}
if ((event.data != null) && /[0-9a-f]{64}/.test(event.data)) {
token = event.data;
} else {
token = null;
}
if (typeof window.removeEventListener === "function") {
window.removeEventListener("message", receiveMessage, false);
}
isReady("authorized", Trello.authorized());
};
return typeof window.addEventListener === "function" ? window.addEventListener("message", receiveMessage, false) : void 0;
})();
break;
default:
window.location = authorizeURL({
redirect_uri: location.href,
callback_method: "fragment",
scope: scope,
expiration: opts.expiration,
name: opts.name
});
}
},
addCard: function(options, next) {
var baseArgs, getCard;
baseArgs = {
mode: 'popup',
source: key || window.location.host
};
getCard = function(callback) {
var height, left, returnUrl, top, width;
returnUrl = function(e) {
var data;
window.removeEventListener('message', returnUrl);
try {
data = JSON.parse(e.data);
if (data.success) {
return callback(null, data.card);
} else {
return callback(new Error(data.error));
}
} catch (error1) {}
};
if (typeof window.addEventListener === "function") {
window.addEventListener('message', returnUrl, false);
}
width = 500;
height = 600;
left = window.screenX + (window.outerWidth - width) / 2;
top = window.screenY + (window.outerHeight - height) / 2;
return window.open(intentEndpoint + "/add-card?" + $.param($.extend(baseArgs, options)), "trello", "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top);
};
if (next != null) {
return getCard(next);
} else if (window.Promise) {
return new Promise(function(resolve, reject) {
return getCard(function(err, card) {
if (err) {
return reject(err);
} else {
return resolve(card);
}
});
});
} else {
return getCard(function() {});
}
}
};
ref = ["GET", "PUT", "POST", "DELETE", "UPLOAD"];
fn = function(type) {
return Trello[type.toLowerCase()] = function() {
return this.rest.apply(this, [type].concat(slice.call(arguments)));
};
};
for (i = 0, len = ref.length; i < len; i++) {
type = ref[i];
fn(type);
}
Trello.del = Trello["delete"];
ref1 = ["actions", "cards", "checklists", "boards", "lists", "members", "organizations", "lists"];
fn1 = function(collection) {
return Trello[collection] = {
get: function(id, params, success, error) {
return Trello.get(collection + "/" + id, params, success, error);
}
};
};
for (j = 0, len1 = ref1.length; j < len1; j++) {
collection = ref1[j];
fn1(collection);
}
window.Trello = Trello;
authorizeURL = function(args) {
var baseArgs;
baseArgs = {
response_type: "token",
key: key
};
return authEndpoint + "/" + version + "/authorize?" + $.param($.extend(baseArgs, args));
};
parseRestArgs = function(arg) {
var error, params, path, success;
path = arg[0], params = arg[1], success = arg[2], error = arg[3];
if (isFunction(params)) {
error = success;
success = params;
params = {};
}
path = path.replace(/^\/*/, "");
return [path, params, success, error];
};
localStorage = window.localStorage;
if (localStorage != null) {
storagePrefix = "trello_";
readStorage = function(key) {
return localStorage[storagePrefix + key];
};
writeStorage = function(key, value) {
if (value === null) {
return delete localStorage[storagePrefix + key];
} else {
return localStorage[storagePrefix + key] = value;
}
};
} else {
readStorage = writeStorage = function() {};
}
};
deferred = {};
ready = {};
waitUntil = function(name, fx) {
if (ready[name] != null) {
return fx(ready[name]);
} else {
return (deferred[name] != null ? deferred[name] : deferred[name] = []).push(fx);
}
};
isReady = function(name, value) {
var fx, fxs, i, len;
ready[name] = value;
if (deferred[name]) {
fxs = deferred[name];
delete deferred[name];
for (i = 0, len = fxs.length; i < len; i++) {
fx = fxs[i];
fx(value);
}
}
};
isFunction = function(val) {
return typeof val === "function";
};
wrapper(window, jQuery, opts);
}).call(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>