!function(e){var t="advads_procfp",a="advanced_ads_ad_clicks",n=null,d=null;function o(e){try{return JSON.parse(e)}catch(e){return null}}e(document).on("advads-passive-cb-conditions",(function(e,t){t.conditions.ad_clicks="check_ad_clicks",t.check_ad_clicks=function(e,t){if(advads.cookie_exists(a+"_"+t.id)){var n=advads.get_cookie(a+"_"+t.id);n=o(n)}if(n){var d=parseInt((new Date).getTime()/1e3);for(var i in n)if("_"+e.expiration==i&&n[i].ttl>=d&&n[i].count>=parseInt(e.limit))return!1}return!0}}));var i=function(){this.$elements={},this.currentIFrame=!1,this.focusLost=!1,this.wrappers=[".google-auto-placed"],this.attributes={"data-anchor-status":"displayed","data-vignette-loaded":"true"},this.lastClick=0,this.init()};i.prototype={constructor:i,init:function(){const t=this;let a;e(document).on("click","a[data-cfpa]",(function(){t.onClick(parseInt(e(this).attr("data-cfpa")))})),e(window).on("blur",(function(e){setTimeout((function(){if(!t.currentIFrame)for(let e=document.activeElement;e&&e!==this&&e!==document&&(t.currentIFrame=t.checkWrappers(e),!t.currentIFrame);e=e.parentNode);t.currentIFrame&&(t.onClick(t.currentIFrame),t.focusLost=!0,top.focus())}),0)})),e(document).on("mouseenter","div[data-cfpa]",(function(){var a=parseInt(e(this).attr("data-cfpa"));t.addElement(a)})),document.addEventListener("touchmove",(function(){a=!0}),!1),document.addEventListener("touchstart",(function(){a=!1}),!1),["click","touchend"].forEach((function(e){document.addEventListener(e,(function(e){if(a||t.getTimestamp()-t.lastClick<1)return;let n=null;for(let a=e.target;a&&a!==this&&a!==document;a=a.parentNode){if(n=t.checkWrappers(a),n){t.onClick(n);break}if(a.hasAttribute("data-cfpa")&&a.hasAttribute("data-cfptl")){n=parseInt(a.getAttribute("data-cfpa"),10),t.onClick(n);break}}}))}))},getTimestamp:function(){return Math.floor(Date.now()/1e3)},checkWrappers:function(e){for(let t=0,a=this.wrappers.length,n=null;t=e&&c[f].count>=parseInt(t[f],10)&&(o.forEach((function(e){e.remove()})),r.removeEmptyWrappers()));var u=new Date,p=new Date(c.exp),v=parseInt((p.getTime()-u.getTime())/1e3);advads.set_cookie_sec(a+"_"+i,JSON.stringify(c,"false",!1),v,n,d)}else{var _={},l=0,m=new Date;u=new Date;for(var f in t)f=f.substring(1),parseFloat(f)>l&&(l=parseFloat(f)),_["_"+f]={count:1,ttl:parseInt(u.getTime()/1e3+3600*parseFloat(f),10)};m.setTime(m.getTime()+60*l*60*1e3);var w="expires="+m.toUTCString();v=parseInt((m.getTime()-u.getTime())/1e3);_.exp=w,advads.set_cookie_sec(a+"_"+i,JSON.stringify(_,"false",!1),v,n,d),1===t[Object.keys(t)[0]]&&(document.querySelectorAll('[data-cfpw="'+i+'"]').forEach((function(e){e.remove()})),this.removeEmptyWrappers())}}if("1"===advadsCfpInfo.cfpEnabled)if(advads.cookie_exists(t+"_"+i)&&(s=o(advads.get_cookie(t+"_"+i))),s){s.count=parseInt(s.count,10)+1;u=new Date,v=((p=new Date(s.exp)).getTime()-u.getTime())/1e3;advads.set_cookie_sec(t+"_"+i,JSON.stringify(s,"false",!1),v,n,d),parseInt(advadsCfpInfo.cfpClickLimit,10)<=s.count&&r._banVisitor()}else{m=new Date,u=new Date;m.setTime(m.getTime()+60*parseInt(advadsCfpInfo.cfpExpHours,10)*60*1e3);w="expires="+m.toUTCString(),v=(m.getTime()-u.getTime())/1e3;advads.set_cookie_sec(t+"_"+i,'{"count":1,"exp":"'+w+'"}',v,n,d),1===parseInt(advadsCfpInfo.cfpClickLimit,10)&&r._banVisitor()}}},e((function(){for(var t in window.advadsProCfp=new i,e(document).on("mouseenter","iframe[data-cfpa]",(function(t){var a=parseInt(e(this).attr("data-cfpa"));advadsProCfp.currentIFrame=a})).on("mouseenter",".google-auto-placed",(function(e){advadsProCfp.currentIFrame="google-auto-placed"})).on("mouseleave mouseout","[data-cfpa], .google-auto-placed",(function(){advadsProCfp.currentIFrame=!1,advadsProCfp.focusLost&&(advadsProCfp.focusLost=!1,e(window).trigger("focus"))})),advadsCfpQueue)advadsCfpQueue.hasOwnProperty(t)&&advadsProCfp.addElement(advadsCfpQueue[t]);advadsCfpQueue=[],void 0!==window.advadsCfpInfo.cfpPath&&(""!=advadsCfpInfo.cfpPath&&(n=advadsCfpInfo.cfpPath),""!=advadsCfpInfo.cfpDomain&&(d=advadsCfpInfo.cfpDomain))}))}(window.jQuery);var advanced_ads_resizetimeout=1e3,advanced_ads_cookieexpires=30,advanced_ads_browser_width=advanced_ads_get_browser_width();if(void 0!==window.advads){var cookieValue=advads.get_cookie("advanced_ads_visitor"),info=cookieValue?JSON.parse(cookieValue):{};info.browser_width&&info.browser_width===advanced_ads_browser_width||advanced_ads_save_width(advanced_ads_browser_width)}function advanced_ads_resize_window(){advads_resize_delay((function(){if(advanced_ads_browser_width!==(advanced_ads_browser_width=advanced_ads_get_browser_width())){advanced_ads_save_width(advanced_ads_browser_width);var e=window.advanced_ads_responsive||{};window.jQuery&&parseInt(e.reload_on_resize,10)&&jQuery(document).triggerHandler("advanced-ads-resize-window")}}),advanced_ads_resizetimeout)}function advanced_ads_save_width(e){if(void 0!==window.advads){var t=advads.get_cookie("advanced_ads_visitor"),a=t?JSON.parse(t):{};a.browser_width=e,advads.set_cookie("advanced_ads_visitor",JSON.stringify(a),advanced_ads_cookieexpires,advanced_ads_cookies.cookie_path,advanced_ads_cookies.cookie_domain)}}window.addEventListener?window.addEventListener("resize",advanced_ads_resize_window,!1):window.attachEvent&&window.attachEvent("onresize",advanced_ads_resize_window);var advads_resize_delay=function(){var e=0;return function(t,a){clearTimeout(e),e=setTimeout(t,a)}}();function advanced_ads_get_browser_width(){if(window.jQuery)return jQuery(window).width();var e=0;return"number"==typeof window.innerWidth?e=window.innerWidth:document.documentElement&&document.documentElement.clientWidth?e=document.documentElement.clientWidth:document.body&&document.body.clientWidth&&(e=document.body.clientWidth),e}
;
;(function($, window, document) {
"use strict";
// dependencies
if (typeof $ === "undefined")
throw "Missing dependency: jQuery" + "\n" + "https://code.jquery.com/";
/**
* Initialize Accordion
*
* @param {Object} element HTML node
* @param {Object} options see Accordion.prototype._defaults
* @return {Void}
*/
var Accordion = function(element, options) {
if (!(this instanceof Accordion))
throw "Accordion: Accordion is a constructor.";
this._element = element;
this._options = options;
this._init();
}
/**
* Accordion prototype
*
* @type {Object}
*/
$.extend(Accordion.prototype, {
/**
* Default options
*
* @type {Object}
*/
_defaults: {
parent: null,
questionClass: '.question',
answerClass: '.answer',
itemClass: '.item',
closeOthers: true,
animationDuration: 200,
},
/**
* Constructor
*
* @return {Void}
*/
_init: function() {
this._element = $(this._element)
.addClass("jquery-accordion")
.data("jquery-accordion", this)
.get(0);
// extend options
this._options = $.extend(true, {}, this._defaults, this._options);
for (var key in this._options) {
if (!(key in this._defaults))
delete this._options[key];
}
// bind events
$(this._element)
// .find(this._options.questionClass)
.on("click.jqueryaccordion", this._options.questionClass, this._handleQuestionClick.bind(this));
$(this._element).trigger("jqueryaccordioninit");
},
/**
* Question click event handler
*
* @param {Event} e
*/
_handleQuestionClick: function(e) {
var $target = $(e.currentTarget);
this.toggle($target);
},
/**
* Open/Close question
*
* @param {Object} element
*/
toggle: function(element) {
$(this._element).trigger("jqueryaccordiontoggle");
var $answer = element
.parent()
.find(this._options.answerClass);
var item = element.closest(this._options.itemClass);
if (this._options.closeOthers)
item
.siblings()
.removeClass("jquery-accordion-active")
.find(this._options.answerClass)
.slideUp(this._options.animationDuration);
item.toggleClass("jquery-accordion-active")
$answer.slideToggle(this._options.animationDuration);
$(this._element).trigger("jqueryaccordiontoggled");
},
/**
* Destructor
*
* @return {Void}
*/
destroy: function() {
$(this._element)
.removeClass("jquery-accordion")
.removeData("jquery-accordion")
.trigger("jqueryaccordiondestroy");
this._element = null;
this._options = null;
},
/**
* Get/Set lib option
*
* @param {String} key
* @param {Mixed} value
* @return {Mixed}
*/
options: function(key, value) {
if (!(key in this._options))
throw "Accordion: invalid options key '" + key + "'";
// get
if (typeof value === "undefined")
return this._options[key];
// set
this._options[key] = value
},
});
// jQuery plugin
$.fn.accordion = function(options) {
var $this = $(this);
var args = Array.prototype.slice.call(arguments, 1);
// iterate all
$this.each(function() {
// is init
var lib = $(this).data("jquery-accordion");
// create new instance
if (!lib)
lib = new Accordion(this, typeof options === "object" ? options : {});
// global methods
if (typeof options === "string") {
if (options.substr(0,1) !== "_" && options in lib && typeof lib[options] === "function") {
// execute
var result = lib[options].apply(lib, args);
// result, exit loop
if (typeof result !== "undefined") {
$this = result;
return false;
}
}
else
throw "Accordion: no method named '" + options + "'";
}
});
// ...finally
return $this;
}
})(window.jQuery, window, document);;
jQuery(document).ready(function ($) {
const pymntsResultsOutputEl = document.querySelector("#results-output .row");
let archiveCurrentPageNumber = 1;
let archiveCurrentFilterType = "category";
let archiveCurrentFilterItems = [];
let initApplyFiltersTimer = null;
let updateUrlParams = false;
let keepCurrentPage = false;
const url = new URL(window.location.href);
if (url.searchParams.get("page")) {
keepCurrentPage = true;
archiveCurrentPageNumber = url.searchParams.get("page");
}
const clearFilters = () => {
[...document.getElementsByClassName("pymnts-filter")].forEach(
(checkbox) => {
if (checkbox.checked) {
checkbox.click();
}
}
);
};
const getReportHTML = (data) => {
let ctaHTML = "";
let contentTypeIcon = "";
let sponsor = "";
let imageHTML = "";
let aboutHTML = "";
let reportDetailsHTML = "";
if (data?.pymnts_custom?.other_editions) {
const otherEditions = data.pymnts_custom.other_editions.filter(
(edition) => edition.month
);
if (otherEditions.length) {
ctaHTML = /* html */ `
`;
}
}
if (["tracker", "study"].includes(data?.post_type)) {
contentTypeIcon = ` `;
}
if (data?.pymnts_custom?.sponsor) {
sponsor = `${data.pymnts_custom.sponsor}
`;
}
if (data?.pymnts_custom?.about) {
aboutHTML = data.pymnts_custom.about;
} else {
aboutHTML = /* html */ `
`;
}
if (data?.pymnts_custom?.cover_image) {
imageHTML = /* html */ `
`;
} else {
imageHTML = /* html */ `
`;
}
if (data?.pymnts_custom?.url) {
reportDetailsHTML = /* html */ `
`;
} else {
reportDetailsHTML = /* html */ `
`;
}
const resultHTML = /* html */ `
${imageHTML}
${reportDetailsHTML}
${aboutHTML}
${ctaHTML}
`;
return resultHTML;
};
const applyFilters = () => {
if (!archiveCurrentFilterItems.length) {
document.querySelector(".pymnts-filter.form-check-input").click();
document.querySelector(".pymnts-filter.form-check-input").click();
updateUrlParams = false;
}
// if (!archiveCurrentFilterItems.length) {
// switch (archiveCurrentFilterType) {
// case "category":
// archiveCurrentFilterItems = allCategories.join(",");
// break;
// case "series":
// archiveCurrentFilterItems = allSeries.join(",");
// break;
// }
// }
const filterType = archiveCurrentFilterType;
const filterItems = archiveCurrentFilterItems;
const accordionContent = document.querySelector(
`.accordion-content-${filterType}`
);
if (accordionContent.style.display === "none") {
document.querySelector(`h4[id="accordion-${filterType}"]`).click();
}
const items = filterItems.split(",");
items.forEach((item) => {
try {
const checkbox = document.querySelector(
`[data-filter="${filterType}"][value="${item}"]`
);
checkbox.click();
checkbox.scrollIntoView({ block: "nearest", inline: "nearest" });
} catch (error) {
console.log("pymnts_applyfilters_error", error);
}
});
keepCurrentPage = false;
};
const applyFiltersFromURLParams = () => {
const url = new URL(window.location.href);
if (url.searchParams.get("filter-type")) {
archiveCurrentFilterType = url.searchParams.get("filter-type");
}
if (url.searchParams.get("filter-items")) {
archiveCurrentFilterItems = url.searchParams.get("filter-items");
}
applyFilters();
};
const showFilteredPosts = async () => {
pymntsResultsOutputEl.innerHTML = Array(4)
.fill(null)
.map((report) => getReportHTML(report))
.join("");
clearTimeout(initApplyFiltersTimer);
initApplyFiltersTimer = setTimeout(async () => {
const filterType = archiveCurrentFilterType;
let allCategories = [];
let showCategories = [];
let allSeries = [];
let showSeries = [];
switch (filterType) {
case "category":
seriesFilters.forEach((checkbox) => {
checkbox.checked = false;
});
break;
case "series":
categoryFilters.forEach((checkbox) => {
checkbox.checked = false;
});
break;
}
allFilters.forEach((checkbox) => {
switch (checkbox.dataset.filter) {
case "category":
if (checkbox.checked) {
showCategories.push(checkbox.value);
}
break;
case "series":
if (checkbox.checked) {
showSeries.push(checkbox.value);
}
break;
}
});
let queryParamsObject = {};
let queryParams = "";
let searchQueryParams = "";
if (showCategories.length === 0) {
showCategories = allCategories;
} else {
queryParamsObject["filter-type"] = "category";
queryParamsObject["filter-items"] = showCategories.join(",");
searchQueryParams = `category=${showCategories.join(",")}`;
}
if (showSeries.length === 0) {
showSeries = allSeries;
} else {
queryParamsObject["filter-type"] = "series";
queryParamsObject["filter-items"] = showSeries.join(",");
searchQueryParams = `series=${showSeries.join(",")}`;
}
queryParamsObject["page"] = archiveCurrentPageNumber;
searchQueryParams += `&paged=${archiveCurrentPageNumber}`;
if (updateUrlParams) {
queryParams = new URLSearchParams(queryParamsObject).toString();
window.history.replaceState("", "", "?" + queryParams);
}
const resp = await fetch(
`/wp-json/pymnts/search?post-type=${pymntsGlobal.post_types_to_use.join(
","
)}&${searchQueryParams}`
);
const respJSON = await resp.json();
const reportsHTML = respJSON.posts
.map((report) => getReportHTML(report))
.join("");
pymntsResultsOutputEl.innerHTML = reportsHTML + respJSON.pagination;
if (updateUrlParams) {
let rect = pymntsResultsOutputEl.getBoundingClientRect();
if (rect.top < 0) {
pymntsResultsOutputEl.scrollIntoView();
}
}
}, 1200);
};
$(".question_accordion").accordion({
questionClass: ".question",
answerClass: ".content",
itemClass: ".column-item",
});
const categoryFilters = [
...document.querySelectorAll(`.pymnts-filter[data-filter="category"]`),
];
const seriesFilters = [
...document.querySelectorAll(`.pymnts-filter[data-filter="series"]`),
];
const allFilters = [...categoryFilters, ...seriesFilters];
let allCategories = [];
let allSeries = [];
// const reports = [...document.getElementsByClassName("pymnts-report")];
allFilters.forEach((checkbox) => {
switch (checkbox.dataset.filter) {
case "category":
allCategories.push(checkbox.value);
break;
case "series":
allSeries.push(checkbox.value);
break;
}
});
if (window.innerWidth > 800) {
document.querySelector(".question_accordion .question h4").click();
}
allFilters.forEach((filter) => {
filter.addEventListener("change", async (ev) => {
updateUrlParams = true;
archiveCurrentFilterType = ev.target.dataset.filter;
if (!keepCurrentPage) {
archiveCurrentPageNumber = 1;
}
showFilteredPosts(true);
});
});
document.querySelector("body").addEventListener(
"click",
(ev) => {
if (
ev.target.classList.contains("page-numbers") &&
ev.target.tagName.toLowerCase() === "a"
) {
ev.preventDefault();
updateUrlParams = true;
const pageNum = ev.target.innerHTML;
if (pageNum === "‹") {
archiveCurrentPageNumber--;
} else if (pageNum === "›") {
archiveCurrentPageNumber++;
} else {
archiveCurrentPageNumber = ev.target.innerHTML;
}
showFilteredPosts(true);
}
},
true
);
setTimeout(() => {
[...document.getElementsByClassName("category-switcher")].forEach((el) => {
el.addEventListener("click", (ev) => {
const category = ev.target.dataset.category;
if (category) {
clearFilters();
archiveCurrentFilterType = "category";
archiveCurrentFilterItems = ev.target.dataset.category;
applyFilters();
}
});
});
applyFiltersFromURLParams();
}, 10);
});
// var textAreas = document.getElementById("searchForm");
// Array.prototype.forEach.call(textAreas, function (elem) {
// elem.placeholder = elem.placeholder.replace(/\\n/g, "\n");
// });
;
/**
* @file postscribe
* @description Asynchronously write javascript, even with document.write.
* @version v2.0.8
* @see {@link https://krux.github.io/postscribe}
* @license MIT
* @author Derek Brans
* @copyright 2016 Krux Digital, Inc
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["advads_postscribe"] = factory();
root["advads_postscribe"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ 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;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _postscribe = __webpack_require__(1);
var _postscribe2 = _interopRequireDefault(_postscribe);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
module.exports = _postscribe2['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = postscribe;
var _writeStream = __webpack_require__(2);
var _writeStream2 = _interopRequireDefault(_writeStream);
var _utils = __webpack_require__(4);
var utils = _interopRequireWildcard(_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* A function that intentionally does nothing.
*/
function doNothing() {}
/**
* Available options and defaults.
*
* @type {Object}
*/
var OPTIONS = {
/**
* Called when an async script has loaded.
*/
afterAsync: doNothing,
/**
* Called immediately before removing from the write queue.
*/
afterDequeue: doNothing,
/**
* Called sync after a stream's first thread release.
*/
afterStreamStart: doNothing,
/**
* Called after writing buffered document.write calls.
*/
afterWrite: doNothing,
/**
* Allows disabling the autoFix feature of prescribe
*/
autoFix: true,
/**
* Called immediately before adding to the write queue.
*/
beforeEnqueue: doNothing,
/**
* Called before writing a token.
*
* @param {Object} tok The token
*/
beforeWriteToken: function beforeWriteToken(tok) {
return tok;
},
/**
* Called before writing buffered document.write calls.
*
* @param {String} str The string
*/
beforeWrite: function beforeWrite(str) {
return str;
},
/**
* Called when evaluation is finished.
*/
done: doNothing,
/**
* Called when a write results in an error.
*
* @param {Error} e The error
*/
error: function error(e) {
throw new Error(e.msg);
},
/**
* Whether to let scripts w/ async attribute set fall out of the queue.
*/
releaseAsync: false
};
var nextId = 0;
var queue = [];
var active = null;
function nextStream() {
var args = queue.shift();
if (args) {
var options = utils.last(args);
options.afterDequeue();
args.stream = runStream.apply(undefined, args);
options.afterStreamStart();
}
}
function runStream(el, html, options) {
active = new _writeStream2['default'](el, options);
// Identify this stream.
active.id = nextId++;
active.name = options.name || active.id;
postscribe.streams[active.name] = active;
// Override document.write.
var doc = el.ownerDocument;
var stash = {
close: doc.close,
open: doc.open,
write: doc.write,
writeln: doc.writeln
};
function _write(str) {
str = options.beforeWrite(str);
active.write(str);
options.afterWrite(str);
}
_extends(doc, {
close: doNothing,
open: doNothing,
write: function write() {
for (var _len = arguments.length, str = Array(_len), _key = 0; _key < _len; _key++) {
str[_key] = arguments[_key];
}
return _write(str.join(''));
},
writeln: function writeln() {
for (var _len2 = arguments.length, str = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
str[_key2] = arguments[_key2];
}
return _write(str.join('') + '\n');
}
});
// Override window.onerror
var oldOnError = active.win.onerror || doNothing;
// This works together with the try/catch around WriteStream::insertScript
// In modern browsers, exceptions in tag scripts go directly to top level
active.win.onerror = function (msg, url, line) {
options.error({ msg: msg + ' - ' + url + ': ' + line });
oldOnError.apply(active.win, [msg, url, line]);
};
// Write to the stream
active.write(html, function () {
// restore document.write
_extends(doc, stash);
// restore window.onerror
active.win.onerror = oldOnError;
options.done();
active = null;
nextStream();
});
return active;
}
function postscribe(el, html, options) {
if (utils.isFunction(options)) {
options = { done: options };
} else if (options === 'clear') {
queue = [];
active = null;
nextId = 0;
return;
}
options = utils.defaults(options, OPTIONS);
// id selector
if (/^#/.test(el)) {
el = window.document.getElementById(el.substr(1));
} else {
el = el.jquery ? el[0] : el;
}
var args = [el, html, options];
el.postscribe = {
cancel: function cancel() {
if (args.stream) {
args.stream.abort();
} else {
args[1] = doNothing;
}
}
};
options.beforeEnqueue(args);
queue.push(args);
if (!active) {
nextStream();
}
return el.postscribe;
}
_extends(postscribe, {
// Streams by name.
streams: {},
// Queue of streams.
queue: queue,
// Expose internal classes.
WriteStream: _writeStream2['default']
});
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _prescribe = __webpack_require__(3);
var _prescribe2 = _interopRequireDefault(_prescribe);
var _utils = __webpack_require__(4);
var utils = _interopRequireWildcard(_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Turn on to debug how each chunk affected the DOM.
* @type {boolean}
*/
var DEBUG_CHUNK = false;
/**
* Prefix for data attributes on DOM elements.
* @type {string}
*/
var BASEATTR = 'data-ps-';
/**
* ID for the style proxy
* @type {string}
*/
var PROXY_STYLE = 'ps-style';
/**
* ID for the script proxy
* @type {string}
*/
var PROXY_SCRIPT = 'ps-script';
/**
* Get data attributes
*
* @param {Object} el The DOM element.
* @param {String} name The attribute name.
* @returns {String}
*/
function getData(el, name) {
var attr = BASEATTR + name;
var val = el.getAttribute(attr);
// IE 8 returns a number if it's a number
return !utils.existy(val) ? val : String(val);
}
/**
* Set data attributes
*
* @param {Object} el The DOM element.
* @param {String} name The attribute name.
* @param {null|*} value The attribute value.
*/
function setData(el, name) {
var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var attr = BASEATTR + name;
if (utils.existy(value) && value !== '') {
el.setAttribute(attr, value);
} else {
el.removeAttribute(attr);
}
}
/**
* Stream static html to an element, where "static html" denotes "html
* without scripts".
*
* This class maintains a *history of writes devoid of any attributes* or
* "proxy history".
*
* Injecting the proxy history into a temporary div has no side-effects,
* other than to create proxy elements for previously written elements.
*
* Given the `staticHtml` of a new write, a `tempDiv`'s innerHTML is set to
* `proxy_history + staticHtml`.
* The *structure* of `tempDiv`'s contents, (i.e., the placement of new nodes
* beside or inside of proxy elements), reflects the DOM structure that would
* have resulted if all writes had been squashed into a single write.
*
* For each descendent `node` of `tempDiv` whose parentNode is a *proxy*,
* `node` is appended to the corresponding *real* element within the DOM.
*
* Proxy elements are mapped to *actual* elements in the DOM by injecting a
* `data-id` attribute into each start tag in `staticHtml`.
*
*/
var WriteStream = function () {
/**
* Constructor.
*
* @param {Object} root The root element
* @param {?Object} options The options
*/
function WriteStream(root) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, WriteStream);
this.root = root;
this.options = options;
this.doc = root.ownerDocument;
this.win = this.doc.defaultView || this.doc.parentWindow;
this.parser = new _prescribe2['default']('', { autoFix: options.autoFix });
// Actual elements by id.
this.actuals = [root];
// Embodies the "structure" of what's been written so far,
// devoid of attributes.
this.proxyHistory = '';
// Create a proxy of the root element.
this.proxyRoot = this.doc.createElement(root.nodeName);
this.scriptStack = [];
this.writeQueue = [];
setData(this.proxyRoot, 'proxyof', 0);
}
/**
* Writes the given strings.
*
* @param {...String} str The strings to write
*/
WriteStream.prototype.write = function write() {
var _writeQueue;
(_writeQueue = this.writeQueue).push.apply(_writeQueue, arguments);
// Process writes
// When new script gets pushed or pending this will stop
// because new writeQueue gets pushed
while (!this.deferredRemote && this.writeQueue.length) {
var arg = this.writeQueue.shift();
if (utils.isFunction(arg)) {
this._callFunction(arg);
} else {
this._writeImpl(arg);
}
}
};
/**
* Calls the given function.
*
* @param {Function} fn The function to call
* @private
*/
WriteStream.prototype._callFunction = function _callFunction(fn) {
var tok = { type: 'function', value: fn.name || fn.toString() };
this._onScriptStart(tok);
fn.call(this.win, this.doc);
this._onScriptDone(tok);
};
/**
* The write implementation
*
* @param {String} html The HTML to write.
* @private
*/
WriteStream.prototype._writeImpl = function _writeImpl(html) {
this.parser.append(html);
var tok = void 0;
var script = void 0;
var style = void 0;
var tokens = [];
// stop if we see a script token
while ((tok = this.parser.readToken()) && !(script = utils.isScript(tok)) && !(style = utils.isStyle(tok))) {
tok = this.options.beforeWriteToken(tok);
if (tok) {
tokens.push(tok);
}
}
if (tokens.length > 0) {
this._writeStaticTokens(tokens);
}
if (script) {
this._handleScriptToken(tok);
}
if (style) {
this._handleStyleToken(tok);
}
};
/**
* Write contiguous non-script tokens (a chunk)
*
* @param {Array