Skip to content

Instantly share code, notes, and snippets.

@Peretz30
Created November 17, 2020 18:42
Show Gist options
  • Save Peretz30/35f7cdd02d1fcea88f15deb7b8994228 to your computer and use it in GitHub Desktop.
Save Peretz30/35f7cdd02d1fcea88f15deb7b8994228 to your computer and use it in GitHub Desktop.
(function (w) {
if (w.fastXDM) return;
var handlers = {};
var onEnvLoad = [];
var env = {};
// Key generation
function genKey() {
var key = '';
for (var i = 0; i < 5; i++) {
key += Math.ceil(Math.random() * 15).toString(16);
}
return key;
}
function waitFor(obj, prop, func, self, count) {
if (obj[prop]) {
func.apply(self);
} else {
count = count || 0;
if (count < 1000) {
setTimeout(function () {
waitFor(obj, prop, func, self, count + 1);
}, 0);
}
}
}
function attachScript(url) {
setTimeout(function () {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url || w.fastXDM.helperUrl;
waitFor(document, 'body', function () {
document.getElementsByTagName('HEAD')[0].appendChild(newScript);
});
}, 0);
}
function walkVar(value, clean) {
var newValue;
switch (typeof value) {
case 'string':
if (clean) {
newValue = value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
} else {
newValue = value.replace(/&#039;/g, '\'').replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&');
}
break;
case 'object':
if (Object.prototype.toString.apply(value) === '[object Array]') {
newValue = [];
for (var i = 0, len = value.length; i < len; i++) {
newValue[i] = walkVar(value[i], clean);
}
} else {
newValue = {};
for (var k in value) {
if (Object.hasOwnProperty.call(value, k)) {
newValue[k] = walkVar(value[k], clean);
}
}
}
break;
default:
newValue = value;
break;
}
return newValue;
}
// Env functions
function getEnv(callback, self) {
if (env.loaded) {
callback.apply(self, [env]);
} else {
onEnvLoad.push([self, callback]);
}
}
function envLoaded() {
env.loaded = true;
for (var i = 0, len = onEnvLoad.length; i < len; i++) {
onEnvLoad[i][1].apply(onEnvLoad[i][0], [env]);
}
}
function applyMethod(strData, self) {
getEnv(function (env) {
var data = env.json.parse(strData);
if (data[0]) {
if (!data[1]) data[1] = [];
for (var i = 0, len = data[1].length; i < len; i++) {
if (data[1][i] && data[1][i]._func) {
var funcNum = data[1][i]._func;
data[1][i] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift('_func' + funcNum);
self.callMethod.apply(self, args);
}
} else if (self.options.safe) {
data[1][i] = walkVar(data[1][i], true);
}
}
setTimeout(function () {
if (!self.methods[data[0]]) {
throw Error('fastXDM: Method ' + data[0] + ' is undefined');
}
self.methods[data[0]].apply(self, data[1]);
}, 0);
}
});
}
function extend(obj1, obj2) {
for (var i in obj2) {
if (obj1[i] && typeof (obj1[i]) === 'object') {
extend(obj1[i], obj2[i])
} else {
obj1[i] = obj2[i];
}
}
}
// XDM object
w.fastXDM = {
_id: 0,
helperUrl: 'https://sdk-narrator.kiozk.ru/js/xdmHelper.js',
Server: function (methods, filter, options) {
this.methods = methods || {};
this.filter = filter;
this.options = options || {};
this.id = w.fastXDM._id++;
this.key = genKey();
this.frameName = 'fXD' + this.key;
this.server = true;
this.methods['%init%'] = this.methods.__fxdm_i = function () {
w.fastXDM.run(this.id);
if (this.methods.onInit) {
this.methods.onInit();
}
};
handlers[this.key] = [applyMethod, this];
},
Client: function (methods, options) {
this.methods = methods || {};
this.options = options || {};
this.id = w.fastXDM._id++;
this.client = true;
w.fastXDM.run(this.id);
if (window.name.indexOf('fXD') === 0) {
this.key = window.name.substr(3);
} else {
throw Error('Wrong window.name property.');
}
this.caller = window.parent;
handlers[this.key] = [applyMethod, this];
w.fastXDM.on('helper', function () {
w.fastXDM.onClientStart(this);
}, this);
getEnv(function (env) {
env.send(this, env.json.stringify(['%init%']));
var methods = this.methods;
setTimeout(function () {
if (methods.onInit) {
methods.onInit();
}
}, 0);
}, this);
},
onMessage: function (e) {
var data = e.data;
if (!data) {
return false;
}
if (typeof data !== 'string' && !(data instanceof String)) {
return false;
}
var key = data.substr(0, 5);
if (handlers[key]) {
var self = handlers[key][1];
if (self && (!self.filter || self.filter(e.origin))) {
handlers[key][0](data.substr(6), self);
}
}
},
setJSON: function (json) {
env.json = json;
},
getJSON: function (callback) {
if (!callback) {
return env.json;
}
getEnv(function (env) {
callback(env.json);
});
},
setEnv: function (exEnv) {
for (var i in exEnv) {
env[i] = exEnv[i];
}
envLoaded();
},
_q: {},
on: function (key, act, self) {
if (!this._q[key]) this._q[key] = [];
if (this._q[key] == -1) {
act.apply(self);
} else {
this._q[key].push([act, self]);
}
},
run: function (key) {
var len = (this._q[key] || []).length;
for (var i = 0; i < len; i++) {
this._q[key][i][0].apply(this._q[key][i][1]);
}
this._q[key] = -1;
},
waitFor: waitFor
}
w.fastXDM.Server.prototype.start = function (obj, count) {
if (obj.contentWindow) {
this.caller = obj.contentWindow;
this.frame = obj;
w.fastXDM.on('helper', function () {
w.fastXDM.onServerStart(this);
}, this);
} else { // Opera old versions
var self = this;
count = count || 0;
if (count < 50) {
setTimeout(function () {
self.start.apply(self, [obj, count + 1]);
}, 100);
}
}
}
w.fastXDM.Server.prototype.destroy = function () {
delete handlers[this.key];
}
w.fastXDM.Server.prototype.append = function (obj, options, attrs) {
var div = document.createElement('DIV');
div.innerHTML = '<iframe name="' + this.frameName + '" ' + (attrs || '') + '></iframe>';
var frame = div.firstChild;
var self = this;
setTimeout(function () {
frame.frameBorder = '0';
if (options) extend(frame, options);
obj.insertBefore(frame, obj.firstChild);
self.start(frame);
}, 0);
return frame;
}
w.fastXDM.Client.prototype.callMethod = w.fastXDM.Server.prototype.callMethod = function () {
var args = Array.prototype.slice.call(arguments);
var method = args.shift();
for (var i = 0, len = args.length; i < len; i++) {
if (typeof (args[i]) === 'function') {
this.funcsCount = (this.funcsCount || 0) + 1;
var func = args[i];
var funcName = '_func' + this.funcsCount;
this.methods[funcName] = function () {
func.apply(this, arguments);
delete this.methods[funcName];
}
args[i] = { _func: this.funcsCount };
} else if (this.options.safe) {
args[i] = walkVar(args[i], false);
}
}
waitFor(this, 'caller', function () {
w.fastXDM.on(this.id, function () {
getEnv(function (env) {
env.send(this, env.json.stringify([method, args]));
}, this);
}, this);
}, this);
}
if (w.JSON && typeof (w.JSON) === 'object' && w.JSON.parse && w.JSON.stringify && w.JSON.stringify({ a: [1, 2, 3] }).replace(/ /g, '') === '{"a":[1,2,3]}') {
env.json = { parse: w.JSON.parse, stringify: w.JSON.stringify };
} else {
w.fastXDM._needJSON = true;
}
// PostMessage cover
if (w.postMessage) {
env.protocol = 'p';
env.send = function (xdm, strData) {
var win = (xdm.frame ? xdm.frame.contentWindow : xdm.caller);
if (win) {
try {
win.postMessage(xdm.key + ':' + strData, "*");
} catch (e) {
window.postMessage.call(win, xdm.key + ':' + strData, "*");
}
}
}
if (w.addEventListener) {
w.addEventListener("message", w.fastXDM.onMessage, false);
} else {
w.attachEvent("onmessage", w.fastXDM.onMessage);
}
if (w.fastXDM._needJSON) {
w.fastXDM._onlyJSON = true;
attachScript();
} else {
envLoaded();
}
} else {
attachScript();
}
})(window);
if (!window.KIOZK) window.KIOZK = {};
/*
* Based on JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
*/
if (!KIOZK.MD5) {
KIOZK.MD5 = function (n) {
var j = function (o, r) {
var q = (o & 65535) + (r & 65535), p = (o >> 16) + (r >> 16) + (q >> 16);
return (p << 16) | (q & 65535)
}, g = function (o, p) {
return (o << p) | (o >>> (32 - p))
}, k = function (w, r, p, o, v, u) {
return j(g(j(j(r, w), j(o, u)), v), p)
}, a = function (q, p, w, v, o, u, r) {
return k((p & w) | ((~p) & v), q, p, o, u, r)
}, h = function (q, p, w, v, o, u, r) {
return k((p & v) | (w & (~v)), q, p, o, u, r)
}, c = function (q, p, w, v, o, u, r) {
return k(p ^ w ^ v, q, p, o, u, r)
}, m = function (q, p, w, v, o, u, r) {
return k(w ^ (p | (~v)), q, p, o, u, r)
}, b = function (A, u) {
var z = 1732584193, y = -271733879, w = -1732584194, v = 271733878, r, q, p, o;
A[u >> 5] |= 128 << ((u) % 32);
A[(((u + 64) >>> 9) << 4) + 14] = u;
for (var t = 0, s = A.length; t < s; t += 16) {
r = z;
q = y;
p = w;
o = v;
z = a(z, y, w, v, A[t + 0], 7, -680876936);
v = a(v, z, y, w, A[t + 1], 12, -389564586);
w = a(w, v, z, y, A[t + 2], 17, 606105819);
y = a(y, w, v, z, A[t + 3], 22, -1044525330);
z = a(z, y, w, v, A[t + 4], 7, -176418897);
v = a(v, z, y, w, A[t + 5], 12, 1200080426);
w = a(w, v, z, y, A[t + 6], 17, -1473231341);
y = a(y, w, v, z, A[t + 7], 22, -45705983);
z = a(z, y, w, v, A[t + 8], 7, 1770035416);
v = a(v, z, y, w, A[t + 9], 12, -1958414417);
w = a(w, v, z, y, A[t + 10], 17, -42063);
y = a(y, w, v, z, A[t + 11], 22, -1990404162);
z = a(z, y, w, v, A[t + 12], 7, 1804603682);
v = a(v, z, y, w, A[t + 13], 12, -40341101);
w = a(w, v, z, y, A[t + 14], 17, -1502002290);
y = a(y, w, v, z, A[t + 15], 22, 1236535329);
z = h(z, y, w, v, A[t + 1], 5, -165796510);
v = h(v, z, y, w, A[t + 6], 9, -1069501632);
w = h(w, v, z, y, A[t + 11], 14, 643717713);
y = h(y, w, v, z, A[t + 0], 20, -373897302);
z = h(z, y, w, v, A[t + 5], 5, -701558691);
v = h(v, z, y, w, A[t + 10], 9, 38016083);
w = h(w, v, z, y, A[t + 15], 14, -660478335);
y = h(y, w, v, z, A[t + 4], 20, -405537848);
z = h(z, y, w, v, A[t + 9], 5, 568446438);
v = h(v, z, y, w, A[t + 14], 9, -1019803690);
w = h(w, v, z, y, A[t + 3], 14, -187363961);
y = h(y, w, v, z, A[t + 8], 20, 1163531501);
z = h(z, y, w, v, A[t + 13], 5, -1444681467);
v = h(v, z, y, w, A[t + 2], 9, -51403784);
w = h(w, v, z, y, A[t + 7], 14, 1735328473);
y = h(y, w, v, z, A[t + 12], 20, -1926607734);
z = c(z, y, w, v, A[t + 5], 4, -378558);
v = c(v, z, y, w, A[t + 8], 11, -2022574463);
w = c(w, v, z, y, A[t + 11], 16, 1839030562);
y = c(y, w, v, z, A[t + 14], 23, -35309556);
z = c(z, y, w, v, A[t + 1], 4, -1530992060);
v = c(v, z, y, w, A[t + 4], 11, 1272893353);
w = c(w, v, z, y, A[t + 7], 16, -155497632);
y = c(y, w, v, z, A[t + 10], 23, -1094730640);
z = c(z, y, w, v, A[t + 13], 4, 681279174);
v = c(v, z, y, w, A[t + 0], 11, -358537222);
w = c(w, v, z, y, A[t + 3], 16, -722521979);
y = c(y, w, v, z, A[t + 6], 23, 76029189);
z = c(z, y, w, v, A[t + 9], 4, -640364487);
v = c(v, z, y, w, A[t + 12], 11, -421815835);
w = c(w, v, z, y, A[t + 15], 16, 530742520);
y = c(y, w, v, z, A[t + 2], 23, -995338651);
z = m(z, y, w, v, A[t + 0], 6, -198630844);
v = m(v, z, y, w, A[t + 7], 10, 1126891415);
w = m(w, v, z, y, A[t + 14], 15, -1416354905);
y = m(y, w, v, z, A[t + 5], 21, -57434055);
z = m(z, y, w, v, A[t + 12], 6, 1700485571);
v = m(v, z, y, w, A[t + 3], 10, -1894986606);
w = m(w, v, z, y, A[t + 10], 15, -1051523);
y = m(y, w, v, z, A[t + 1], 21, -2054922799);
z = m(z, y, w, v, A[t + 8], 6, 1873313359);
v = m(v, z, y, w, A[t + 15], 10, -30611744);
w = m(w, v, z, y, A[t + 6], 15, -1560198380);
y = m(y, w, v, z, A[t + 13], 21, 1309151649);
z = m(z, y, w, v, A[t + 4], 6, -145523070);
v = m(v, z, y, w, A[t + 11], 10, -1120210379);
w = m(w, v, z, y, A[t + 2], 15, 718787259);
y = m(y, w, v, z, A[t + 9], 21, -343485551);
z = j(z, r);
y = j(y, q);
w = j(w, p);
v = j(v, o)
}
return [z, y, w, v]
}, f = function (r) {
var q = "", s = -1, p = r.length, o, t;
while (++s < p) {
o = r.charCodeAt(s);
t = s + 1 < p ? r.charCodeAt(s + 1) : 0;
if (55296 <= o && o <= 56319 && 56320 <= t && t <= 57343) {
o = 65536 + ((o & 1023) << 10) + (t & 1023);
s++
}
if (o <= 127) {
q += String.fromCharCode(o)
} else {
if (o <= 2047) {
q += String.fromCharCode(192 | ((o >>> 6) & 31), 128 | (o & 63))
} else {
if (o <= 65535) {
q += String.fromCharCode(224 | ((o >>> 12) & 15), 128 | ((o >>> 6) & 63), 128 | (o & 63))
} else {
if (o <= 2097151) {
q += String.fromCharCode(240 | ((o >>> 18) & 7), 128 | ((o >>> 12) & 63), 128 | ((o >>> 6) & 63), 128 | (o & 63))
}
}
}
}
}
return q
}, e = function (p) {
var o = Array(p.length >> 2), r, q;
for (r = 0, q = o.length; r < q; r++) {
o[r] = 0
}
for (r = 0, q = p.length * 8; r < q; r += 8) {
o[r >> 5] |= (p.charCodeAt(r / 8) & 255) << (r % 32)
}
return o
}, l = function (p) {
var o = "";
for (var r = 0, q = p.length * 32; r < q; r += 8) {
o += String.fromCharCode((p[r >> 5] >>> (r % 32)) & 255)
}
return o
}, d = function (o) {
return l(b(e(o), o.length * 8))
}, i = function (q) {
var t = "0123456789abcdef", p = "", o;
for (var s = 0, r = q.length; s < r; s++) {
o = q.charCodeAt(s);
p += t.charAt((o >>> 4) & 15) + t.charAt(o & 15)
}
return p
};
return i(d(f(n)))
}
}
/*
* KIOZK widgets JavaScript library
* http://kiozk.ru/
*/
KIOZK.extend = function (target, source, overwrite) {
for (var key in source) {
if (overwrite || typeof target[key] === 'undefined') {
target[key] = source[key];
}
}
return target;
};
KIOZK._protocol = 'https:';
KIOZK._base_domain = '';
if (!KIOZK.xdConnectionCallbacks) {
KIOZK.extend(KIOZK, {
version: 1,
_apiKey: null,
_session: null,
_domain: {
// main: KIOZK._protocol + '//sdk-narrator.kiozk.ru/',
main: KIOZK._protocol + '//sdk-narrator.kiozk.ru/',
api: KIOZK._protocol + '//api-narrator.kiozk.ru/'
},
_path: {
login: 'authorize',
proxy: 'fxdm_oauth_proxy.html'
},
_rootId: 'kiozk_api_transport',
_nameTransportPath: '',
xdReady: false,
});
KIOZK.init = function (options) {
var body, root;
KIOZK._apiKey = null;
if (!options.apiKey) {
throw Error('KIOZK.init() called without an apiKey');
}
KIOZK._apiKey = options.apiKey;
KIOZK.userId = options.userId;
return true;
};
} else { // if KIOZK.xdConnectionCallbacks
setTimeout(function () {
var callback;
while (callback = KIOZK.xdConnectionCallbacks.pop()) {
callback();
}
}, 0);
if (KIOZK.Widgets && !KIOZK.Widgets._constructor) {
KIOZK.Widgets = false;
}
}
if (!KIOZK.XDM) {
KIOZK.XDM = {
remote: null,
init: function () {
if (this.remote) return false;
var url = KIOZK._domain.api + KIOZK._path.proxy;
this.remote = new fastXDM.Server({
onInit: function () {
KIOZK.xdReady = true;
KIOZK.Observer.publish('xdm.init');
}
});
this.remote.append(document.getElementById(KIOZK._rootId), {
src: url
});
},
xdHandler: function (code) {
try {
eval('KIOZK.' + code);
} catch (e) {
// nope
}
}
};
}
if (!KIOZK.Observer) {
KIOZK.Observer = {
_subscribers: function () {
if (!this._subscribersMap) {
this._subscribersMap = {};
}
return this._subscribersMap;
},
publish: function (eventName) {
var
args = Array.prototype.slice.call(arguments),
eventName = args.shift(),
subscribers = this._subscribers()[eventName],
i, j;
if (!subscribers) return;
for (i = 0, j = subscribers.length; i < j; i++) {
if (subscribers[i] != null) {
subscribers[i].apply(this, args);
}
}
},
subscribe: function (eventName, handler) {
var
subscribers = this._subscribers();
if (typeof handler != 'function') return false;
if (!subscribers[eventName]) {
subscribers[eventName] = [handler];
} else {
subscribers[eventName].push(handler);
}
},
unsubscribe: function (eventName, handler) {
var
subscribers = this._subscribers()[eventName],
i, j;
if (!subscribers) return false;
if (typeof handler == 'function') {
for (i = 0, j = subscribers.length; i < j; i++) {
if (subscribers[i] == handler) {
subscribers[i] = null;
}
}
} else {
delete this._subscribers()[eventName];
}
}
};
}
if (!KIOZK.Widgets) {
KIOZK.Widgets = {};
KIOZK.Widgets.count = 0;
KIOZK.Widgets.RPC = {};
KIOZK.Widgets.showBoxUrl = function (domain, url) {
domain = (domain || KIOZK._protocol + '//sdk-narrator.kiozk.ru').replace(/\/?\s*$/, '');
url = url.replace(/^\s*\/?/, '');
return domain + '/' + url;
};
KIOZK.Widgets.loading = function (obj, enabled) {
obj.style.background = enabled ? 'url("' + KIOZK._protocol + '//sdk-narrator.kiozk.ru/images/upload2.gif") center center no-repeat transparent' : 'none';
};
/**
*
* @param objId
* @param options
* @returns {*|number}
* @constructor
*/
KIOZK.Widgets.Stories = function (objId, options) {
if (!options.apiKey) {
throw Error('KIOZK.init() called without an apiKey');
}
KIOZK._apiKey = options.apiKey;
if (!KIOZK._apiKey) throw Error('KIOZK not initialized. Please use KIOZK.init');
options = options || {};
let params = {
// настройки storiesList виджета
// storiesLayoutHeight: options.storiesLayoutHeight || 0,
storiesTitle: options.storiesTitle || '',
storiesTitleColor: options.storiesTitleColor || '',
storiesTitleFont: options.storiesTitleFont || '-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji',
storiesTitleFontSize: options.storiesTitleFontSize !== undefined ? options.storiesTitleFontSize : 20,
storiesTitleLineHeight: options.storiesTitleFontSize !== undefined ? options.storiesTitleLineHeight : 20,
storiesTitleFontWeight: options.storiesTitleFontWeight || 'bold',
storiesTitleMarginBottom: options.storiesTitleMarginBottom !== undefined ? options.storiesTitleMarginBottom : 20,
storiesListItemTitleColor: options.storiesListItemTitleColor || '',
storiesListItemTitleFont: options.storiesListItemTitleFont || '-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji',
storiesListItemTitleFontSize: options.storiesListItemTitleFontSize !== undefined ? options.storiesListItemTitleFontSize : 15,
storiesListItemTitleLineHeight: options.storiesListItemTitleLineHeight !== undefined ? options.storiesListItemTitleLineHeight : 15,
storiesListItemTitleFontWeight: options.storiesListItemTitleFontWeight || 'normal',
storiesBackgroundColor: options.storiesBackgroundColor || 'rgba(0,0,0,0)',
storiesHeight: options.storiesHeight || 70,
storiesListSidePadding: options.storiesListSidePadding || 20,
storiesListTopPadding: options.storiesListTopPadding || 20,
storiesListBottomPadding: options.storiesListBottomPadding || 20,
storiesGap: options.storiesGap || 10,
storiesStyle: ['circle', 'quad', 'rectangle'].indexOf(options.storiesStyle) !== -1 ? options.storiesStyle : 'circle',
storiesBorderNotReadColor: options.storiesBorderNotReadedColor || '#00b956',
storiesBorderReadColor: options.storiesBorderReadedColor || '#ededed',
storiesListBorderNotReadWidth: options.storiesListBorderNotReadWidth !== undefined ? options.storiesListBorderNotReadWidth : 2,
storiesListBorderReadWidth: options.storiesListBorderReadWidth !== undefined ? options.storiesListBorderReadWidth : 1,
storiesListBorderGapNotRead: options.storiesListBorderGapNotRead !== undefined ? options.storiesListBorderGapNotRead : 2,
storiesListBorderGapRead: options.storiesListBorderGapRead !== undefined ? options.storiesListBorderGapRead : 3,
storiesListBorderRadius: options.storiesListBorderRadius !== undefined ? options.storiesListBorderRadius : 5,
// настройки storiesViewer виджета
storiesCloseButtonPosition: options.storiesCloseButtonPosition || 'right',
storiesScrollStyle: options.storiesScrollStyle || 'flat',
tags: options.tags || '',
userId: options.userId || null,
hasLike: options.hasLike || false,
hasFavorite: options.hasFavorite || false,
},
widgetRoot,
widget,
rpc,
inFullScreenMode = false,
scrollPosition = [0, 0];
options.allowTransparency = true;
options.overflowTouch = false;
options.backgroundColor = params.storiesBackgroundColor;
var defaults = {
startHeight: 70,
minWidth: 150,
storiesHeight: 70
};
if (!params.storiesTitle) {
defaults.startHeight = parseFloat((params.storiesHeight || defaults.storiesHeight)) + parseFloat(params.storiesListTopPadding) + parseFloat(params.storiesListBottomPadding);
} else {
defaults.startHeight = 50 + parseFloat((params.storiesHeight || defaults.storiesHeight)) + parseFloat(params.storiesListTopPadding) + parseFloat(params.storiesListBottomPadding);
}
var body = document.querySelector('body'),
html = document.querySelector('html'),
zIndex = options.zIndex || 10000;
const functions = {
// TODO add class to body
switchToFullScreen: function () {
if (inFullScreenMode) {
return;
}
window.ReactNativeWebView.postMessage("onEnterFullscreen")
scrollPosition = KIOZK.Util.getScroll();
if (body) {
body.style.setProperty('user-select', 'none');
body.style.setProperty('-webkit-user-select', 'none');
body.style.setProperty('overflow', 'hidden');
body.style.setProperty('-webkit-overflow-scrolling', 'touch');
}
if (html) {
html.style.setProperty('position', 'fixed');
html.style.setProperty('overflow', 'hidden');
}
if (widgetRoot && widget) {
// получаем текущее смещение от начала viewport
const viewportOffset = widgetRoot.getBoundingClientRect();
const offsetTop = viewportOffset.top;
widget.style.setProperty('position', 'fixed')
widget.style.setProperty('top', '0')
widget.style.setProperty('bottom', '0')
widget.style.setProperty('left', '0')
widget.style.setProperty('right', '0')
widget.style.setProperty('height', '0')
widget.style.setProperty('min-height', '100%')
widget.style.setProperty('max-height', '100%')
widget.style.setProperty('z-index', zIndex)
rpc.callMethod('onEnterFullScreen', { offsetTop: offsetTop })
}
inFullScreenMode = true;
// newWidth = parseInt(newWidth);
// newHeight = parseInt(newHeight);
// var widgetElem = document.getElementById('kiozkwidget' + widgetId);
// if (isFinite(newWidth)) {
// obj.style.width = newWidth + 'px';
// if (widgetElem) {
// widgetElem.style.width = newWidth + 'px';
// }
// }
// if (isFinite(newHeight)) {
// obj.style.height = newHeight + 'px';
// if (widgetElem) {
// widgetElem.style.height = newHeight + 'px';
// }
// }
// if (options.onResizeWidget) options.onResizeWidget();
//
},
switchFromFullScreen: function () {
if (!inFullScreenMode) {
return;
}
window.ReactNativeWebView.postMessage("onExitFullscreen")
if (widgetRoot && widget) {
widget.style.setProperty('position', '')
widget.style.setProperty('top', '')
widget.style.setProperty('bottom', '')
widget.style.setProperty('left', '')
widget.style.setProperty('right', '')
widget.style.setProperty('height', isFinite(defaults['startHeight']) ? defaults['startHeight'] + 'px' : '100%')
widget.style.setProperty('min-height', '')
widget.style.setProperty('max-height', '')
widget.style.setProperty('z-index', '')
rpc.callMethod('onLeaveFullScreen')
}
if (body) {
body.style.setProperty('user-select', '');
body.style.setProperty('-webkit-user-select', '');
body.style.setProperty('overflow', '');
body.style.setProperty('-webkit-overflow-scrolling', '');
}
if (html) {
html.style.setProperty('position', '');
html.style.setProperty('overflow', '');
}
window.scrollTo(scrollPosition[0], scrollPosition[1])
inFullScreenMode = false;
},
};
return KIOZK.Widgets._constructor('widget_stories.php', objId, options, params, functions, defaults, function (o, i, r) {
widgetRoot = o;
widget = i;
rpc = r;
});
};
KIOZK.Widgets._constructor = function (widgetUrl, objId, options, params, funcs, defaults, onDone, widgetId, iter) {
var obj = document.getElementById(objId);
widgetId = widgetId || (++KIOZK.Widgets.count);
if (!obj) {
iter = iter || 0;
if (iter > 10) {
throw Error('KIOZK.Widgets: object #' + objId + ' not found.');
}
setTimeout(function () {
KIOZK.Widgets._constructor(widgetUrl, objId, options, params, funcs, defaults, onDone, widgetId, iter + 1);
}, 500);
return widgetId;
}
options = options || {};
defaults = defaults || {};
funcs = funcs || {};
if (options.preview) {
params.preview = 1;
delete options['preview'];
}
let ifr, url, urlQueryString, encodedParam, rpc, iframe, i,
base_domain = options.base_domain || KIOZK._protocol + '//sdk-narrator.kiozk.ru',
// base_domain = options.base_domain || KIOZK._protocol + '//sdk-nar-nar.test.kiozk.ru',
width = options.width === 'auto' ? (obj.clientWidth || obj.offsetWidth || defaults.minWidth) | 0 : parseInt(options.width || 0, 10);
width = width ? (Math.max(defaults.minWidth || 200, Math.min(defaults.maxWidth || 10000, width)) + 'px') : '100%';
obj.style.width = width;
if (options.height) {
params.height = options.height;
obj.style.height = options.height + 'px';
} else {
obj.style.height = (defaults.startHeight || 200) + 'px';
}
if (options.overflowTouch) {
obj.style['overflow'] = 'auto';
obj.style['-webkit-overflow-scrolling'] = 'touch';
}
if (width === '100%') params.startWidth = (obj.clientWidth || obj.offsetWidth) | 0;
if (!params.url) params.url = options.pageUrl || location.href.replace(/#.*$/, '');
url = base_domain + '/' + widgetUrl;
urlQueryString = '';
if (!options.noDefaultParams) {
urlQueryString += '&appKey=' + KIOZK._apiKey + '&width=' + encodeURIComponent(width)
}
urlQueryString += '&_ver=' + KIOZK.version
params.url = params.url || "";
params.referrer = params.referrer || document.referrer || "";
params.title = params.title || document.title || "";
params.userId = params.userId || null;
for (i in params) {
if (typeof (params[i]) == 'number') {
encodedParam = params[i];
} else {
try {
encodedParam = encodeURIComponent(params[i]);
} catch (e) {
encodedParam = '';
}
}
urlQueryString += '&' + i + '=' + encodedParam;
}
urlQueryString += '&' + (+new Date()).toString(16);
url += '?' + urlQueryString.substr(1);
funcs.onStartLoading && funcs.onStartLoading();
if (!options.no_loading) {
KIOZK.Widgets.loading(obj, true);
}
funcs.showLoader = function (enable) {
KIOZK.Util.Loader(enable);
};
funcs.publish = function () {
var args = Array.prototype.slice.call(arguments);
args.push(widgetId);
KIOZK.Observer.publish.apply(KIOZK.Observer, args);
};
funcs.onInit = function () {
KIOZK.Widgets.loading(obj, false);
if (funcs.onReady) funcs.onReady();
if (options.onReady) options.onReady();
};
funcs.resize = function (e, cb) {
obj.style.height = e + 'px';
var el = document.getElementById('kiozkwidget' + widgetId);
if (el) {
el.style.height = e + 'px';
}
};
funcs.resizeWidget = function (newWidth, newHeight) {
newWidth = parseInt(newWidth);
newHeight = parseInt(newHeight);
var widgetElem = document.getElementById('kiozkwidget' + widgetId);
if (isFinite(newWidth)) {
obj.style.width = newWidth + 'px';
if (widgetElem) {
widgetElem.style.width = newWidth + 'px';
}
}
if (isFinite(newHeight)) {
obj.style.height = newHeight + 'px';
if (widgetElem) {
widgetElem.style.height = newHeight + 'px';
}
}
if (options.onResizeWidget) options.onResizeWidget();
};
rpc = KIOZK.Widgets.RPC[widgetId] = new fastXDM.Server(funcs, function (origin) {
if (!origin) return true;
origin = origin.toLowerCase();
return (origin.match(/(\.|\/)kiozk\.ru($|\/|\?)/));
}, { safe: true });
iframe = KIOZK.Widgets.RPC[widgetId].append(obj, {
src: url,
width: (width.indexOf('%') != -1) ? width : (parseInt(width) || width),
height: defaults.startHeight || '100%',
scrolling: 'no',
id: 'kiozkwidget' + widgetId,
allowTransparency: options.allowTransparency || false,
style: {
overflow: 'hidden',
backgroundColor: options.backgroundColor || 'transparent'
}
});
onDone && setTimeout(function () {
onDone(obj, iframe || obj.firstChild, rpc);
}, 10);
return widgetId;
};
KIOZK.Widgets.destroy = function (widgetId, objId) {
var obj = document.getElementById(objId);
if (!obj) {
throw Error('KIOZK.Widgets: object #' + objId + ' not found.');
}
var rpc = KIOZK.Widgets.RPC[widgetId];
if (!rpc) {
rpc.destroy();
}
// TODO destroy APP
obj.innerHTML = '';
};
}
if (!KIOZK.Util) {
KIOZK.Util = {
getStyle: function (elem, name) {
var ret, defaultView = document.defaultView || window;
if (defaultView.getComputedStyle) {
name = name.replace(/([A-Z])/g, '-$1').toLowerCase();
var computedStyle = defaultView.getComputedStyle(elem, null);
if (computedStyle) {
ret = computedStyle.getPropertyValue(name);
}
} else if (elem.currentStyle) {
var camelCase = name.replace(/\-(\w)/g, function (all, letter) {
return letter.toUpperCase();
});
ret = elem.currentStyle[name] || elem.currentStyle[camelCase];
}
return ret;
},
getXY: function (obj, fixed) {
if (!obj || obj === undefined) return;
var left = 0, top = 0;
if (obj.getBoundingClientRect !== undefined) {
var rect = obj.getBoundingClientRect();
left = rect.left;
top = rect.top;
fixed = true;
} else if (obj.offsetParent) {
do {
left += obj.offsetLeft;
top += obj.offsetTop;
if (fixed) {
left -= obj.scrollLeft;
top -= obj.scrollTop;
}
} while (obj = obj.offsetParent);
}
if (fixed) {
top += window.pageYOffset || window.scrollNode && scrollNode.scrollTop || document.documentElement.scrollTop;
left += window.pageXOffset || window.scrollNode && scrollNode.scrollLeft || document.documentElement.scrollLeft;
}
return [left, top];
},
Loader: function self(enable) {
if (!self.loader) {
self.loader = document.createElement('DIV');
self.loader.innerHTML = '<style type="text/css">\
@-webkit-keyframes KIOZKWidgetsLoaderKeyframes {0%{opacity: 0.2;}30%{opacity: 1;}100%{opacity: 0.2;}}\
@keyframes KIOZKWidgetsLoaderKeyframes {0%{opacity: 0.2;}30%{opacity: 1;}100%{opacity: 0.2;}}\
.KIOZKWidgetsLoader div {width: 7px;height: 7px;-webkit-border-radius: 50%;-khtml-border-radius: 50%;-moz-border-radius: 50%;border-radius: 50%;background: #fff;top: 21px;position: absolute;z-index: 2;-o-transition: opacity 350ms linear; transition: opacity 350ms linear;opacity: 0.2;-webkit-animation-duration: 750ms;-o-animation-duration: 750ms;animation-duration: 750ms;-webkit-animation-name: KIOZKWidgetsLoaderKeyframes;-o-animation-name: KIOZKWidgetsLoaderKeyframes;animation-name: KIOZKWidgetsLoaderKeyframes;-webkit-animation-iteration-count: infinite;-o-animation-iteration-count: infinite;animation-iteration-count: infinite;-webkit-transform: translateZ(0);transform: translateZ(0);}</style><div class="KIOZKWidgetsLoader" style="position: fixed;left: 50%;top: 50%;margin: -25px -50px;z-index: 1002;height: 50px;width: 100px;"><div style="left: 36px;-webkit-animation-delay: 0ms;-o-animation-delay: 0ms;animation-delay: 0ms;"></div><div style="left: 47px;-webkit-animation-delay: 180ms;-o-animation-delay: 180ms;animation-delay: 180ms;"></div><div style="left: 58px;-webkit-animation-delay: 360ms;-o-animation-delay: 360ms;animation-delay: 360ms;"></div><span style="display: block;background-color: #000;-webkit-border-radius: 4px;-khtml-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;-webkit-box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.35);-moz-box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.35);box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.35);position: absolute;left: 0;top: 0;bottom: 0; right: 0;z-index: 1;opacity: 0.7;"></span></div>';
document.body.insertBefore(self.loader, document.body.firstChild);
}
self.loader.style.display = enable ? 'block' : 'none';
},
addEvent: function (type, func, target) {
target = target || window.document;
if (target.addEventListener) {
target.addEventListener(type, func, false);
} else if (target.attachEvent) {
target.attachEvent('on' + type, func);
}
},
removeEvent: function (type, func, target) {
target = target || window.document;
if (target.removeEventListener) {
target.removeEventListener(type, func, false);
} else if (target.detachEvent) {
target.detachEvent('on' + type, func);
}
},
ss: function (el, styles) {
KIOZK.extend(el.style, styles, true);
},
getScroll: function () {
if (window.pageYOffset !== undefined) {
return [pageXOffset, pageYOffset];
} else {
var sx, sy, d = document,
r = d.documentElement,
b = d.body;
sx = r.scrollLeft || b.scrollLeft || 0;
sy = r.scrollTop || b.scrollTop || 0;
return [sx, sy];
}
}
};
}
// Init asynchronous library loading
for (var i = 0; i < KIOZK._e.length; i++) {
setTimeout(KIOZK._e[i], 0);
}
// window.kiozkAsyncInit && setTimeout(kiozkAsyncInit, 0);
if (window.kiozkAsyncInitCallbacks && kiozkAsyncInitCallbacks.length) {
setTimeout(function () {
var callback;
while (callback = kiozkAsyncInitCallbacks.pop()) {
try {
callback();
} catch (e) {
try {
console.error(e);
} catch (e2) {
}
}
}
}, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment