///
///
///
///
define('app/ui/reader/resizablereader',["require", "exports", "app/ui/reader/page/contentsize", "app/helper/responsive", "jquery", "underscore", "i18n!locales"], function (require, exports, cs, rss) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reader = void 0;
var reader;
(function (reader) {
class ResizableReaderElement {
setElementDimensions(dimensions) {
if (!dimensions) {
dimensions = {};
}
this.elementDimensions = dimensions;
}
getElementDimensions() {
return this.elementDimensions;
}
}
reader.ResizableReaderElement = ResizableReaderElement;
class ResizableReaderContentProvider {
constructor(sandbox, context) {
this.sandbox = sandbox;
this.context = context;
}
modifyContentDimensions(descriptor, newContentDimensions, onContentDimensionsModifiedCallback, filter) {
if (newContentDimensions && descriptor) {
var modified = !filter || (filter && filter(descriptor.pearlId));
if (modified) {
descriptor.setElementDimensions(newContentDimensions);
if (onContentDimensionsModifiedCallback) {
onContentDimensionsModifiedCallback();
}
}
}
}
isResizeRequired(descriptor) {
if (!descriptor.getElementDimensions()) {
return false;
}
return cs.contentSize.isReaderResizable(this.sandbox, descriptor.getElementDimensions(), this.context);
}
getDescriptorId(descriptor) {
return descriptor.pearlId;
}
getContentHeight(descriptor, slideContainer, initialContentDimensions) {
if (!descriptor.getElementDimensions() && !initialContentDimensions) {
return 0;
}
var contentDimensions = descriptor.getElementDimensions();
if ((!contentDimensions || contentDimensions.height == 0) && initialContentDimensions && initialContentDimensions.height > 0) {
contentDimensions = initialContentDimensions;
}
return cs.contentSize.getResizedContentSize(this.sandbox, contentDimensions, rss.helper.getReaderTitleHeight(slideContainer))
.scrollableHeight;
}
}
reader.ResizableReaderContentProvider = ResizableReaderContentProvider;
})(reader = exports.reader || (exports.reader = {}));
});
///
///
///
define('app/objects/reader/slide',["require", "exports", "app/util/loader/spinloader", "app/helper/responsive", "app/ui/reader/page/contentsize", "app/ui/reader/resizablereader", "app/ui/values", "jquery"], function (require, exports, ld, re, cs, rr, va) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reader = void 0;
var reader;
(function (reader) {
var debugid = 0;
var NANO_CONTENT = '.nano-content';
var READER_CONTENT = '.reader-content';
var RESIZE_TIME = 400;
class Slide {
constructor(contentDescriptor, sandbox, withBanner) {
this.contentDescriptor = contentDescriptor;
this.sandbox = sandbox;
this.withBanner = withBanner;
this.contentId = 0;
this.loadingInProgress = false;
this.loaderHasBeenDisplayedLongEnough = true;
this.isContentEnabled = false;
this.contentIsReady = false;
this.bannerBottom = 0;
this.currentIdx = 0;
this.contentHistory = [];
this.arrayId = debugid++;
}
log(msg) {
}
setCurrentGraphicalParameters(params) {
this.log('[SLIDE] setCurrentGraphicalParameters ' + JSON.stringify(params));
this.currentGraphicalParameters = params;
if (params.initialContentDimensions) {
this.currentContentDimensions = params.initialContentDimensions;
}
}
getCurrentGraphicalParameters() {
return this.currentGraphicalParameters;
}
getOrCreateSlideBackground() {
if (!this.$slideBackground) {
this.$slideBackground = $('
');
if (this.$container) {
this.$container.append(this.$slideBackground);
this.hideSlideBackground();
}
}
return this.$slideBackground;
}
loadContent(container, contentProvider, loadedCallBack, readyCallBack) {
this.contentProvider = contentProvider;
this.$container = container;
this.isEnded = false;
this.listenToCurrentContentSizeChanged();
this.listenToSlideResizeRequest();
this.log('[SLIDE] load: ' + this.arrayId);
if (this.loadingInProgress) {
this.log('[SLIDE] was in progress:' + this.arrayId);
}
else if (this.getContent()) {
this.log('[SLIDE] was already loaded:' + this.arrayId);
}
else {
this.setInitialState();
this.loadingInProgress = true;
this.contentIsReady = false;
this.onLoadedCallback = loadedCallBack;
this.onReadyCallback = readyCallBack;
this.cancelAddLoaderToContainer();
this.showLoaderTimeoutId = this.scheduleAddLoaderToContainer();
var contentId = ++this.contentId;
contentProvider.getContent(this.contentDescriptor, (content) => {
if (contentId == this.contentId) {
this.onContentLoaded(content);
}
}, () => {
if (contentId == this.contentId) {
this.onContentReadyToDisplay();
}
});
}
}
getContentDescriptor() {
return this.contentDescriptor;
}
// may return undefined
getContent() {
return this.contentHistory[this.currentIdx];
}
setContent(content) {
this.contentHistory[this.currentIdx] = content;
}
enableContent() {
var content = this.getContent();
if (content && !this.isEnded && !this.loadingInProgress) {
this.isContentEnabled = true;
content.enable();
}
}
disableContent() {
if (this.isContentEnabled) {
var content = this.getContent();
if (content) {
content.disable();
}
this.isContentEnabled = false;
}
}
destroyContent() {
this.log('[SLIDE] destroy content:' + this.arrayId);
var content = this.getContent();
if (content && !content.onBeforeDestroy()) {
this.log('[SLIDE] destroy content prevented:' + this.arrayId);
return this.isEnded;
}
this.isContentEnabled = false;
this.hideLoader();
if (this.loadingInProgress) {
// this.log('destroy while loading in progress');
this.loadingInProgress = false;
this.contentIsReady = false;
this.onLoadedCallback = () => { };
}
this.sandbox.getEventBus().stopSubscription(this.resizeSubId);
// TODO destroy all contents, even the ones in the history
if (content) {
content.destroy();
this.setContent(undefined);
}
else {
this.log('[SLIDE] no content to destroy: ' + this.arrayId);
}
if (this.$slideBackground) {
this.$slideBackground.remove();
this.$slideBackground = null;
}
if (this.$readerBanner) {
this.$readerBanner.close();
this.$readerBanner = null;
}
this.isEnded = true;
return this.isEnded;
}
setInitialState() {
if (this.$container) {
this.getOrCreateSlideBackground();
this.log('[SLIDE] setInitialState');
var onReaderGraphicalParametersComputed = (params) => {
this.$slideBackground.show();
this.$container.addClass('withBackground');
this.$container.css('margin-top', params.top);
this.$container.find(READER_CONTENT).css('margin-top', '0px');
this.$container.height(params.height);
};
if (this.currentGraphicalParameters) {
this.log('setInitialState with params ' + JSON.stringify(this.currentGraphicalParameters));
onReaderGraphicalParametersComputed(this.currentGraphicalParameters);
}
else {
this.log('setInitialState default');
re.helper.getDefaultReaderGraphicalParameters(this.sandbox, onReaderGraphicalParametersComputed);
}
}
}
setInitialHeight(relatedHeight, anonymousOffset) {
var height = this.$container.closest('#reader').height() - 2 * re.helper.getHeaderPaddingTop() - relatedHeight - anonymousOffset;
if (re.helper.isiPadUnderIOS8()) {
height -= re.helper.getHeaderPaddingTop();
}
this.$container.height(height);
}
addSubContent(newContent) {
this.currentIdx++;
this.contentHistory[this.currentIdx] = newContent;
this.currentContentDimensions = undefined;
this.currentGraphicalParameters = undefined;
this.setInitialState();
}
changeCurrentContent(newContent) {
this.contentHistory[this.currentIdx] = newContent;
this.setInitialState();
}
hasPreviousContent() {
return this.currentIdx > 0;
}
goBackToPreviousContent(callback) {
this.setInitialState();
this.dontAnimateOnBack = true;
setTimeout(() => {
this.dontAnimateOnBack = false;
}, 1000);
var currentContent = this.getContent();
// currentIdx cond: ensure we cannot open multiples times the associated content
if (this.currentIdx == 0 && !!currentContent.allowGoBackToAssociatedContent && currentContent.allowGoBackToAssociatedContent()) {
!!currentContent.viewAssociatedContent && currentContent.viewAssociatedContent(callback);
}
else {
this.currentIdx--;
callback(this.getContent()); // previous in contentHistory
}
}
getPreviousContent() {
if (!this.hasPreviousContent()) {
return null;
}
return this.contentHistory[this.currentIdx - 1];
}
scheduleAddLoaderToContainer() {
return setTimeout(() => this.addLoaderToContainer(), Slide.WAIT_TIME_BEFORE_SHOWING_LOADER);
}
cancelAddLoaderToContainer() {
if (this.showLoaderTimeoutId) {
clearTimeout(this.showLoaderTimeoutId);
this.showLoaderTimeoutId = undefined;
}
}
addLoaderToContainer() {
this.log('[SLIDE] add loader:' + this.arrayId + '/' + this.contentIsReady);
if (!this.contentIsReady) {
this.loaderHasBeenDisplayedLongEnough = false;
if (!this.loader) {
this.loader = new ld.loader.SpinLoader(this.$container, 2 /* HUGE */, true);
}
this.loader.show();
}
}
onContentLoaded(content) {
this.log('[SLIDE] content loaded: ' + this.arrayId);
this.loadingInProgress = false;
if (this.isEnded) {
content.destroy();
this.hideLoader();
if (this.getContent()) {
alert('Content should be not available');
}
}
else {
this.setContent(content);
if (this.currentContentDimensions && cs.contentSize.isFullReaderWidthRequired(this.currentContentDimensions)) {
this.$container.addClass('withMagnified');
}
this.onLoadedCallback();
}
}
adaptReaderSize(slide, nanoContent) {
var adaptReaderSize = !this.hasPreviousContent() && this.contentProvider.isResizeRequired(this.contentDescriptor);
var contentHeight;
this.log('[SLIDE] adaptReaderSize');
var onReaderGraphicalParametersComputed = (params) => {
this.setCurrentGraphicalParameters(params);
if (!this.dontAnimateOnBack && parseInt(slide.css('margin-top').replace(/[^-\d\.]/g, '')) == 0) {
nanoContent.css('padding-top', params.top);
nanoContent.css('padding-bottom', params.bottom);
slide.css('margin-top', '0px');
slide.css('height', '100%');
//slide.css('margin-bottom', '-50px');
//nanoContent.animate({paddingTop: params.top, paddingBottom: params.bottom}, {duration: RESIZE_TIME, queue: false});
//slide.animate({marginTop: '0px', height: '100%', marginBottom: '-50px'}, {duration: RESIZE_TIME, queue: false});
}
else {
// during animation
nanoContent.css('padding-top', params.top);
nanoContent.css('padding-bottom', params.bottom);
slide.css('margin-top', '0px');
slide.css('height', '100%');
}
slide.removeClass('withBackground');
this.setBannerBottom(Math.max(Slide.MIN_BANNER_BOTTOM, params.bottom - Slide.BANNER_BOTTOM_SIZE));
};
if (adaptReaderSize) {
contentHeight = this.contentProvider.getContentHeight(this.contentDescriptor, slide, this.currentContentDimensions);
re.helper.getResizedReaderGraphicalParameters(this.sandbox, contentHeight, slide, onReaderGraphicalParametersComputed);
}
else {
re.helper.getDefaultReaderGraphicalParameters(this.sandbox, onReaderGraphicalParametersComputed);
}
}
getDescriptorId() {
return this.contentProvider.getDescriptorId(this.getContentDescriptor());
}
onWindowResized(slide) {
var content = slide.find(NANO_CONTENT);
this.resizeSlide(slide, content);
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 8 /* RESIZE_CONTENT */, {
id: this.getDescriptorId(),
});
}
resizeSlide(slide, content) {
if (content && content.length > 0) {
this.adaptReaderSize(slide, content);
}
this.resizeSlideContent(slide);
}
onContentReadyToDisplay() {
this.hideLoader();
this.log('[SLIDE] onContentReadyToDisplay: ' + this.arrayId);
var slide = this.$container;
var content = slide.find(NANO_CONTENT);
this.addBannerIfNeeded();
if (slide) {
this.resizeSubId = this.sandbox.getEventBus().subscribeTo(5 /* STAGE_CHANNEL */, 3 /* RESIZE */, () => {
this.onWindowResized(slide);
}, this);
this.resizeSlideContent(slide);
}
else {
this.log('[SLIDE] no slide found');
}
if (slide && slide.css && content && content.length > 0) {
this.resizeSlide(slide, content);
}
else {
this.log('[SLIDE] no content found');
}
this.onReadyCallback();
this.contentIsReady = true;
this.hideSlideBackground();
this.$container.removeClass('withMagnified');
}
resizeSlideContent(slide) {
var content = slide.find(READER_CONTENT);
var adaptReaderSize = !this.hasPreviousContent() && this.contentProvider.isResizeRequired(this.contentDescriptor);
var contentHeight;
this.log('[SLIDE] resizeSlideContent');
var onReaderGraphicalParametersComputed = (params) => {
this.setCurrentGraphicalParameters(params);
var shouldHide = true;
if (this.contentDescriptor && this.contentDescriptor instanceof rr.reader.ResizableReaderElement) {
var tre = this.getContentDescriptor();
if (tre.elementDimensions &&
(tre.elementDimensions.layout == 1 ||
tre.elementDimensions.layout == 2 ||
(tre.elementDimensions.embedInfo && tre.elementDimensions.embedInfo.embedInfoType == 14 /* INSTAGRAM */))) {
shouldHide = false;
}
}
if (shouldHide) {
this.hideSlideBackground();
}
this.setMinHeight(content, params.height);
};
if (this.currentGraphicalParameters) {
onReaderGraphicalParametersComputed(this.currentGraphicalParameters);
}
else {
if (adaptReaderSize) {
contentHeight = this.contentProvider.getContentHeight(this.contentDescriptor, slide);
re.helper.getResizedReaderGraphicalParameters(this.sandbox, contentHeight, content, onReaderGraphicalParametersComputed);
}
else {
re.helper.getDefaultReaderGraphicalParameters(this.sandbox, onReaderGraphicalParametersComputed);
}
}
}
setMinHeight(content, height) {
content.css('min-height', height);
}
hideLoader() {
this.log('[SLIDE] hideLoader: ' + this.arrayId);
if (this.loader) {
this.loader.hide();
}
if (this.$container && this.$container.children('.spinner')) {
this.$container.children('.spinner').remove();
}
this.loader = undefined;
this.hideSlideBackground();
}
hideSlideBackground() {
if (this.$slideBackground) {
this.$slideBackground.hide();
}
}
isReady() {
return this.contentIsReady;
}
isScrollableContent() {
return this.getContent().isScrollableContent();
}
getContainer() {
return this.$container;
}
listenToCurrentContentSizeChanged() {
this.currentContentSizeChangedListenerId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 9 /* FINAL_CONTENT_SIZE_CHANGED */, (ev) => {
this.contentProvider.modifyContentDimensions(this.getContentDescriptor(), ev.newContentDimensions, () => {
if (!this.currentContentDimensions ||
Math.abs(ev.newContentDimensions.height - this.currentContentDimensions.height) > 50 ||
Math.abs(ev.newContentDimensions.width - this.currentContentDimensions.width) > 50) {
var slide = this.$container;
var content = slide.find(NANO_CONTENT);
this.resizeSlide(slide, content);
this.onReadyCallback();
}
}, (pearlId) => {
return pearlId == ev.pearlId;
});
}, this);
}
listenToSlideResizeRequest() {
this.resizeRequestListenerId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 7 /* RESIZE_SLIDE */, (ev) => {
if (ev.id == this.getDescriptorId()) {
var slide = this.$container;
this.onWindowResized(slide);
}
}, this);
}
addBannerIfNeeded() {
if (this.withBanner && !this.$readerBanner && !this.readerBannerLoading) {
this.readerBannerLoading = true;
require(['app/ui/reader/banner/readerbanner'], (rb) => {
this.readerBannerLoading = false;
if (!this.isEnded) {
this.log('[SLIDE] add banner');
this.$readerBanner = new rb.readerbanner.ReaderBanner(this.sandbox);
this.readerBannerLoading = false;
this.$readerBanner.render();
this.$container.append(this.$readerBanner.$el);
this.$container.addClass('has-banner');
this.updateBannerPositionAndSize();
}
else {
this.log('[SLIDE] add banner -> isEnded');
}
});
}
}
setBannerBottom(bottom) {
this.bannerBottom = bottom;
this.updateBannerPositionAndSize();
}
updateBannerPositionAndSize() {
if (this.$readerBanner && this.bannerBottom >= Slide.MIN_BANNER_BOTTOM) {
this.log('[SLIDE] updateBannerPosition: ' + this.bannerBottom);
this.$readerBanner.$el.css('bottom', this.bannerBottom);
this.$readerBanner.resize();
}
}
}
Slide.MIN_BANNER_BOTTOM = va.values.READER_BANNER_MIN_BOTTOM;
Slide.BANNER_BOTTOM_SIZE = va.values.READER_BANNER_HEIGHT;
Slide.WAIT_TIME_BEFORE_SHOWING_LOADER = 1250; // 1 second
Slide.LOADER_MIN_DISPLAY_TIME_S = 1000; // 1 second
reader.Slide = Slide;
class SlideArray {
constructor(slidesData, loop, sandbox, withBanner) {
this.slides = $.map(slidesData, (contentDescriptor) => new Slide(contentDescriptor, sandbox, withBanner));
// loop is not correctly handled for less than 3 slides
this.loop = loop && slidesData.length >= 3;
}
getPreviousSlide(slide) {
var previousIndex = $.inArray(slide, this.slides) - 1;
if (previousIndex >= 0) {
return this.slides[previousIndex];
}
else {
if (this.loop) {
return this.slides[this.slides.length - 1];
}
return undefined;
}
}
getNextSlide(slide) {
var nextIndex = $.inArray(slide, this.slides) + 1;
if (nextIndex < this.slides.length) {
return this.slides[nextIndex];
}
else {
if (this.loop) {
return this.slides[0];
}
return undefined;
}
}
getSlides() {
return this.slides;
}
}
reader.SlideArray = SlideArray;
})(reader = exports.reader || (exports.reader = {}));
});
/*
* Swipe 2.0
*
* Brad Birdsall
* Copyright 2013, MIT License
*
*/
function Swipe(container, options) {
"use strict";
// utilities
var noop = function() {}; // simple no operation function
var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution
// check browser capabilities
var browser = {
addEventListener: !!window.addEventListener,
touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
transitions: (function(temp) {
var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
return false;
})(document.createElement('swipe'))
};
// quit if no root element
if (!container) return;
var element = container.children[0];
var slides, slidePos, width, length, moveLeft, moveRight;
options = options || {};
var index = parseInt(options.startSlide, 10) || 0;
var speed = options.speed || 300;
options.continuous = options.continuous !== undefined ? options.continuous : true;
function setup() {
// cache slides
slides = element.children;
length = slides.length;
moveRight = moveLeft = true;
// set continuous to false if only one slide
if (slides.length < 2) options.continuous = false;
//special case if two slides
if (browser.transitions && options.continuous && slides.length < 3) {
element.appendChild(slides[0].cloneNode(true));
element.appendChild(element.children[1].cloneNode(true));
slides = element.children;
}
// create an array to store current positions of each slide
slidePos = new Array(slides.length);
// determine width of each slide
width = Math.round(container.getBoundingClientRect().width || container.offsetWidth);
element.style.width = (slides.length * width) + 'px';
// stack elements
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = width + 'px';
slide.setAttribute('data-index', pos);
if (browser.transitions) {
slide.style.left = (pos * -width) + 'px';
move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
}
}
// reposition elements before and after index
if (options.continuous && browser.transitions) {
move(circle(index-1), -width, 0);
move(circle(index+1), width, 0);
}
if (!browser.transitions) element.style.left = (index * -width) + 'px';
container.style.visibility = 'visible';
}
function prev() {
if (options.continuous) slide(index-1);
else if (index) slide(index-1);
}
function next() {
if (options.continuous) slide(index+1);
else if (index < slides.length - 1) slide(index+1);
}
function circle(index) {
// a simple positive modulo using slides.length
return (slides.length + (index % slides.length)) % slides.length;
}
function slide(to, slideSpeed) {
// do nothing if already on requested slide
if (index == to) return;
if (browser.transitions) {
var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward
// get the actual position of the slide
if (options.continuous) {
var natural_direction = direction;
direction = -slidePos[circle(to)] / width;
// if going forward but to < index, use to = slides.length + to
// if going backward but to > index, use to = -slides.length + to
if (direction !== natural_direction) to = -direction * slides.length + to;
}
var diff = Math.abs(index-to) - 1;
// move all the slides between index and to in the right direction
while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);
to = circle(to);
move(index, width * direction, slideSpeed || speed);
move(to, 0, slideSpeed || speed);
if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
} else {
to = circle(to);
animate(index * -width, to * -width, slideSpeed || speed);
//no fallback for a circular continuous if the browser does not accept transitions
}
index = to;
offloadFn(options.callback && options.callback(index, slides[index]));
}
function move(index, dist, speed) {
translate(index, dist, speed);
slidePos[index] = dist;
}
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}
function animate(from, to, speed) {
// if not an animation, just reposition
if (!speed) {
element.style.left = to + 'px';
return;
}
var start = +new Date;
var timer = setInterval(function() {
var timeElap = +new Date - start;
if (timeElap > speed) {
element.style.left = to + 'px';
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
clearInterval(timer);
return;
}
element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';
}, 4);
}
// setup auto slideshow
var delay = options.auto || 0;
var interval;
function begin() {
interval = setTimeout(next, delay);
}
function stop() {
delay = 0;
clearTimeout(interval);
}
// setup initial vars
var start = {};
var delta = {};
var isScrolling;
// setup event capturing
var events = {
handleEvent: function(event) {
switch (event.type) {
case 'touchstart': this.start(event); break;
case 'touchmove': this.move(event); break;
case 'touchend': offloadFn(this.end(event)); break;
case 'webkitTransitionEnd':
case 'msTransitionEnd':
case 'oTransitionEnd':
case 'otransitionend':
case 'transitionend': offloadFn(this.transitionEnd(event)); break;
case 'resize': offloadFn(setup); break;
}
if (options.stopPropagation) event.stopPropagation();
},
start: function(event) {
var touches = event.touches[0];
// measure start values
start = {
// get initial touch coords
x: touches.pageX,
y: touches.pageY,
// store time to determine touch duration
time: +new Date
};
// used for testing first move event
isScrolling = undefined;
// reset delta and end measurements
delta = {};
// attach touchmove and touchend listeners
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
move: function(event) {
// ensure swiping with one touch and not pinching
if ( event.touches.length > 1 || event.scale && event.scale !== 1) return
if (options.disableScroll) event.preventDefault();
var touches = event.touches[0];
// measure change in x and y
delta = {
x: touches.pageX - start.x,
y: touches.pageY - start.y
}
// determine if scrolling test has run - one time test
if ( typeof isScrolling == 'undefined') {
isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
}
// if user is not trying to scroll vertically
if (!isScrolling) {
// prevent native scrolling
event.preventDefault();
// stop slideshow
stop();
// increase resistance if first or last slide
if (options.continuous) { // we don't add resistance at the end
if (!(!moveLeft && delta.x > 0 || !moveRight && delta.x < 0 )) {
translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
translate(index, delta.x + slidePos[index], 0);
translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);
}
} else {
delta.x =
delta.x /
( (!index && delta.x > 0 // if first slide and sliding left
|| index == slides.length - 1 // or if last slide and sliding right
&& delta.x < 0 // and if sliding at all
) ?
( Math.abs(delta.x) / width + 1 ) // determine resistance level
: 1 ); // no resistance if false
// translate 1:1
translate(index-1, delta.x + slidePos[index-1], 0);
translate(index, delta.x + slidePos[index], 0);
translate(index+1, delta.x + slidePos[index+1], 0);
}
}
},
end: function(event) {
// measure duration
var duration = +new Date - start.time;
// determine if slide attempt triggers next/prev slide
var isValidSlide =
Number(duration) < 250 // if slide duration is less than 250ms
&& Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
|| Math.abs(delta.x) > width/2; // or if slide amt is greater than half the width
// determine if slide attempt is past start and end
var isPastBounds =
!index && delta.x > 0 // if first slide and slide amt is greater than 0
|| index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0
if (options.continuous) isPastBounds = false;
// determine direction of swipe (true:right, false:left)
var direction = delta.x < 0;
// if not scrolling vertically
if (!isScrolling) {
if (isValidSlide && !isPastBounds) {
if (direction) {
if (moveRight) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index - 1), -width, 0);
move(circle(index + 2), width, 0);
} else {
move(index - 1, -width, 0);
}
move(index, slidePos[index] - width, speed);
move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
index = circle(index + 1);
}
} else {
if (moveLeft) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index + 1), width, 0);
move(circle(index - 2), -width, 0);
} else {
move(index + 1, width, 0);
}
move(index, slidePos[index] + width, speed);
move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
index = circle(index - 1);
}
}
options.callback && options.callback(index, slides[index]);
} else {
if (options.continuous) {
move(circle(index-1), -width, speed);
move(index, 0, speed);
move(circle(index+1), width, speed);
} else {
move(index-1, -width, speed);
move(index, 0, speed);
move(index+1, width, speed);
}
}
}
// kill touchmove and touchend event listeners until touchstart called again
element.removeEventListener('touchmove', events, false)
element.removeEventListener('touchend', events, false)
},
transitionEnd: function(event) {
if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
}
}
}
// trigger setup
setup();
// start auto slideshow if applicable
if (delay) begin();
// add event listeners
if (browser.addEventListener) {
// set touchstart event on element
if (browser.touch) element.addEventListener('touchstart', events, false);
if (browser.transitions) {
element.addEventListener('webkitTransitionEnd', events, false);
element.addEventListener('msTransitionEnd', events, false);
element.addEventListener('oTransitionEnd', events, false);
element.addEventListener('otransitionend', events, false);
element.addEventListener('transitionend', events, false);
}
// set resize event on window
window.addEventListener('resize', events, false);
} else {
window.onresize = function () { setup() }; // to play nice with old IE
}
// expose the Swipe API
return {
setup: function() {
setup();
},
slide: function(to, speed) {
// cancel slideshow
stop();
slide(to, speed);
},
prev: function() {
// cancel slideshow
stop();
prev();
},
next: function() {
// cancel slideshow
stop();
next();
},
moveRight: function(t) {
moveRight = t;
},
moveLeft: function(t) {
moveLeft = t;
},
stop: function() {
// cancel slideshow
stop();
},
getPos: function() {
// return current index position
return index;
},
getNumSlides: function() {
// return total number of slides
return length;
},
kill: function() {
// cancel slideshow
stop();
// reset element
element.style.width = '';
element.style.left = '';
// reset slides
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = '';
slide.style.left = '';
if (browser.transitions) translate(pos, 0, 0);
}
// removed event listeners
if (browser.addEventListener) {
// remove current event listeners
element.removeEventListener('touchstart', events, false);
element.removeEventListener('webkitTransitionEnd', events, false);
element.removeEventListener('msTransitionEnd', events, false);
element.removeEventListener('oTransitionEnd', events, false);
element.removeEventListener('otransitionend', events, false);
element.removeEventListener('transitionend', events, false);
window.removeEventListener('resize', events, false);
}
else {
window.onresize = null;
}
}
}
}
if ( window.jQuery || window.Zepto ) {
(function($) {
$.fn.Swipe = function(params) {
return this.each(function() {
$(this).data('Swipe', new Swipe($(this)[0], params));
});
}
})( window.jQuery || window.Zepto )
}
;
define("swipe", ["jquery"], (function (global) {
return function () {
var ret, fn;
return ret || global.Swipe;
};
}(this)));
define('text!app/objects/reader/template.html',[],function () { return '';});
define('bower_components/require-css/css!app/objects/reader/reader',[],function(){});
///
///
///
///
///
///
///
///
define('app/objects/reader/reader',["require", "exports", "./slide", "app/helper/responsive", "app/core/stats/pageview/track/actiontracker", "app/util/scrollbar/scrollbar", "jquery", "swipe", "underscore", "text!./template.html", "css!./reader.css"], function (require, exports, s, re, at, sb) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reader = void 0;
var reader;
(function (reader) {
function createAndShowFromArray(contentDescriptors, initialIndex, contentProvider, sandbox, withBanner = false, loop = false) {
var slideCollection = new s.reader.SlideArray(contentDescriptors, loop, sandbox, withBanner);
var initialSlide = slideCollection.getSlides()[initialIndex];
return createAndShowFromCollection(slideCollection, initialSlide, contentProvider, withBanner, sandbox);
}
reader.createAndShowFromArray = createAndShowFromArray;
function createAndShowFromCollection(slideCollection, initialSlide, contentProvider, withBanner, sandbox) {
return new ReaderImpl(contentProvider, slideCollection, initialSlide, withBanner, sandbox);
}
reader.createAndShowFromCollection = createAndShowFromCollection;
var MINIMUM_MOBILE_WIDTH = 1000;
var NO_MOVES_TIMER = 3000;
reader.OFFSET_SWIPE_CONTAINER = 10;
reader.READER_MAX_WIDTH = 800; //defined in css;
class ReaderImpl {
constructor(contentProvider, slideCollection, initialSlide, withBanner, sandbox) {
this.contentProvider = contentProvider;
this.slideCollection = slideCollection;
this.withBanner = withBanner;
this.sandbox = sandbox;
this.noMovesIfSmall = false;
this.canMoveLeft = true;
this.canMoveRight = true;
this.forceHideMoveLeftAndRight = false; //For sub panels
this.noMoves = false;
this.hasBeenDestroyed = false;
this.isVisible = true;
this.isClosing = false;
this.isFirstSlideLoaded = true;
this.isTransitioning = false;
this.dispatchAction = false;
this.hasAnonymousOffset = false;
this.currentSlide = initialSlide;
this.currentIndex = 0;
this.isRawData = sandbox.isRawDataMode();
this.noMovesIfSmall = sandbox.isMobile();
this.hasAnonymousOffset = sandbox.isAnonymousDesktop();
this.build();
this.updateMovementRights(false);
this.bindButtons();
}
initialize() {
if (this.hasBeenDestroyed) {
return;
}
this.listenToSlideReadyEvents();
this.listenToResizeEvent();
this.loadSlideContent(this.currentSlide, 0, true);
this.resize();
this.listenToGetCurrentReader();
this.listenToGetReaderDimensions();
}
setVisible(isVisible) {
if (isVisible) {
this.$div.show();
this.isVisible = true;
}
else {
this.$div.hide();
this.isVisible = false;
}
}
destroy() {
this.hasBeenDestroyed =
this.destroySlideContent(this.currentSlide) &&
this.destroySlideContent(this.slideCollection.getPreviousSlide(this.currentSlide)) &&
this.destroySlideContent(this.slideCollection.getNextSlide(this.currentSlide));
if (this.hasBeenDestroyed) {
this.sandbox.getEventBus().stopSubscription(this.listenerId);
this.sandbox.getEventBus().stopSubscription(this.reloadContentEventListenerId);
this.sandbox.getEventBus().stopSubscription(this.currentContentSizeChangedListenerId);
this.sandbox.getEventBus().stopSubscription(this.readerDimensionslistenerId);
// shut down the swipe lib
this.swipe.kill();
this.sandbox.getWindowManager().manageHide(this.$background);
this.sandbox.getWindowManager().manageHide(this.$div);
// remove this from the DOM
this.$div.remove();
}
return this.hasBeenDestroyed;
}
resize() {
var mainDivWidth = this.$div.width();
// height can be have invalid values when going full screen on safari
if (re.helper.getDesiredReaderHeight(this.sandbox) > 0) {
var margin = re.helper.getReaderMargin(this.sandbox, mainDivWidth);
this.getSlide().css({ 'margin-left': margin, 'margin-right': margin });
this.setSwipeContainerMargins(margin);
this.setButtonsPosition(margin);
this.setCloseButtonPosition(margin);
this.resizeElements();
this.updateMovementRights(false); //NN Swipe.js listen to window resizing to run setup that set moveleft and moveright to true
if (this.readerBanner) {
this.readerBanner.resize();
}
}
else {
}
}
updateMovability() {
var mainDivWidth = this.$div.width();
var nm = this.noMoves;
this.noMoves = this.noMovesIfSmall && mainDivWidth < MINIMUM_MOBILE_WIDTH;
if (this.noMoves != nm) {
if (this.noMoves) {
setTimeout(() => this.updateMovementRights(true), NO_MOVES_TIMER);
}
else {
this.updateMovementRights(false);
}
this.resizeElements();
}
}
setSwipeContainerMargins(sideMargin) {
// we need to offset this margin so that the other slides are not visible when resizing the window
var swipeContainer = this.$div.find('.swipe-container');
var marginWithOffset = sideMargin;
swipeContainer.css({ left: marginWithOffset, right: marginWithOffset });
}
setButtonsPosition(margin) {
if (!this.noMoves) {
var buttonsMargin = this.getButtonLateralMargin(margin);
var prev = this.getPreviousArrow();
var next = this.getNextArrow();
prev.css('left', buttonsMargin);
next.css('right', buttonsMargin);
var topMargin = re.helper.getReaderSwipePosition(this.sandbox, prev).top;
prev.css('top', topMargin);
next.css('top', topMargin);
}
}
setCloseButtonPosition(margin) {
var buttonsMargin = this.getButtonLateralMargin(margin);
var closeButton = this.getCloseButton();
//Default
var closeTopMargin = this.hasAnonymousOffset ? re.helper.anonymousMarginTopMinValue : re.helper.getHeaderPaddingTop();
if (re.helper.isMobilePhoneReader()) {
// fix position
var paddingTop = re.helper.getHeaderPaddingTop();
var paddingBottom = re.helper.getHeaderPaddingBottom();
var pTop = Math.round((paddingTop + paddingBottom) / 2);
closeTopMargin = re.helper.getDefaultReaderMarginTop(this.sandbox) + pTop;
buttonsMargin = re.helper.getHeaderPadding();
}
else if (this.getCurrentSlide() && this.getCurrentSlide().getCurrentGraphicalParameters()) {
var readerTop = this.getCurrentSlide().getCurrentGraphicalParameters().top;
if (readerTop) {
var adjust = 5;
if (this.sandbox.isMobile()) {
adjust = 3;
}
closeTopMargin = readerTop - adjust;
}
}
closeButton.css('right', buttonsMargin);
closeButton.css('top', closeTopMargin);
}
getButtonLateralMargin(margin) {
if (re.helper.isMobilePhoneReader()) {
// fix position
return 3;
}
var buttonWidth = 54;
var spaceBetweenSlideAndButtons = 20;
return Math.max(margin * 2 - buttonWidth - spaceBetweenSlideAndButtons, 0);
}
resizeElements() {
var slide = this.getSlide();
var close = this.getCloseButton();
if (this.noMoves) {
//mobile
var previous = this.getPreviousArrow();
var next = this.getNextArrow();
var retinaClass = 'sprite-r-reader-';
var normalClass = 'sprite-reader-';
var baseClass = re.helper.isRetinaScreen() ? retinaClass : normalClass;
if (re.helper.isMobilePhoneReader()) {
close
.removeClass(retinaClass + 'close')
.removeClass(normalClass + 'close')
.addClass(baseClass + 'close-small');
var margin = re.helper.getHeaderPadding() + 4;
previous
.removeClass(retinaClass + 'previous')
.removeClass(normalClass + 'previous')
.addClass(baseClass + 'previous-small');
next.removeClass(retinaClass + 'next')
.removeClass(normalClass + 'next')
.addClass(baseClass + 'next-small');
}
else {
close
.addClass(baseClass + 'close')
.removeClass(retinaClass + 'close-small')
.removeClass(normalClass + 'close-small');
previous
.addClass(baseClass + 'previous')
.removeClass(retinaClass + 'previous-small')
.removeClass(normalClass + 'previous-small');
next.addClass(baseClass + 'next')
.removeClass(retinaClass + 'next-small')
.removeClass(normalClass + 'next-small');
}
}
}
build() {
this.layout = new ReaderLayout();
this.layout.render();
var parent = $('#reader-container');
if (!parent.empty()) {
}
parent.append(this.layout.$el);
this.$div = $('#reader');
this.$background = $('#reader-and-background .background-cloak');
this.sandbox.getWindowManager().manageTopShow(this.$background, 'readerBackground');
this.sandbox.getWindowManager().manageTopShow(this.$div, 'reader');
this.resize();
var $slider = this.$div.find('#slider');
var options = {
continuous: true,
speed: 400,
callback: (index) => {
this.onSlideDisplayed(index);
},
transitionEnd: () => {
this.onTransitionEnd();
},
};
var sliderEl = $slider.get(0);
this.swipe = Swipe(sliderEl, options);
this.swipe.moveLeft(false);
this.swipeSlideCount = $slider.find('.swipe-wrap').children().length;
this.updateMovability();
}
getCurrentSlide() {
return this.currentSlide;
}
isCurrentSlideResizable() {
return this.contentProvider.isResizeRequired(this.getCurrentSlide().getContentDescriptor());
}
changeAndRefreshCurrentSlideContent(newContent, withoutSubSlide) {
var currentContent = this.currentSlide.getContent();
if (currentContent) {
currentContent.clearView();
}
if (withoutSubSlide) {
this.currentSlide.changeCurrentContent(newContent);
}
else {
this.currentSlide.addSubContent(newContent);
}
this.refreshCurrentSlideContent(newContent);
this.currentSlide.onContentReadyToDisplay();
return this.currentSlide;
}
swipeLeft() {
if (this.isVisible && this.canMoveLeft) {
if (!re.helper.isMobilePhoneReader()) {
this.getCloseButton().hide();
}
this.isTransitioning = true;
this.swipe.prev();
return true;
}
return false;
}
swipeRight() {
if (this.isVisible && this.canMoveRight) {
if (!re.helper.isMobilePhoneReader()) {
this.getCloseButton().hide();
}
this.isTransitioning = true;
this.swipe.next();
return true;
}
return false;
}
swipeTo(contentDescriptor) {
var previousSlide = this.slideCollection.getPreviousSlide(this.currentSlide);
if (previousSlide && this.areSameDesciptor(previousSlide.getContentDescriptor(), contentDescriptor)) {
this.getCloseButton().hide();
this.isTransitioning = true;
this.swipe.prev();
return true;
}
else {
var nextSlide = this.slideCollection.getNextSlide(this.currentSlide);
if (nextSlide && this.areSameDesciptor(nextSlide.getContentDescriptor(), contentDescriptor)) {
this.getCloseButton().hide();
this.isTransitioning = true;
this.swipe.next();
return true;
}
else {
return false;
}
}
}
areSameDesciptor(d1, d2) {
if (d1 && d1.isEqualTo) {
return d1.isEqualTo(d2);
}
return JSON.stringify(d1) === JSON.stringify(d2);
}
setCloseAnimation(closeAnimation) {
this.closeAnimation = closeAnimation;
}
close(callback, stopModuleToGoBack) {
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 24 /* READER_WILL_CLOSE */);
if (this.closeAnimation) {
if (callback) {
this.closeAnimation.close(callback, stopModuleToGoBack);
}
else {
this.closeAnimation.close(this.defaultOnCloseAction, stopModuleToGoBack);
}
}
else {
if (callback) {
callback();
}
else if (this.defaultOnCloseAction) {
this.defaultOnCloseAction();
}
}
if (this.dispatchAction) {
at.actiontracker.trackAction({
fromPlace: 7 /* READER_MAP */,
toPlace: 0 /* COLLECTION */,
supposedEventType: [0 /* MOUSE_DOWN */, 4 /* KEYBOARD */],
additionalUrl: '?closecurrentSlide',
});
}
}
setDefaultOnCloseAction(action) {
this.defaultOnCloseAction = action;
}
bindButtons() {
if (re.helper.isMobilePhoneReader()) {
this.getTouchPreviousArrow().click((event) => {
this.swipeLeft();
});
this.getTouchNextArrow().click((event) => {
this.swipeRight();
});
this.getTouchCloseButton().click((event) => {
this.closeCurrentSlide();
});
}
else {
this.getPreviousArrow().click((event) => {
this.swipeLeft();
});
this.getNextArrow().click((event) => {
this.swipeRight();
});
this.getCloseButton().click((event) => {
this.closeCurrentSlide();
});
}
this.$div.find('.background').click((event) => {
this.onClickOnBackground();
});
}
onClickOnBackground() {
// For comments in MyNetwork: display content related to the comments instead of simply closing the card
var currentContent = this.currentSlide.getContent();
if (!this.currentSlide.hasPreviousContent() &&
!!(currentContent === null || currentContent === void 0 ? void 0 : currentContent.allowGoBackToAssociatedContent) && (currentContent === null || currentContent === void 0 ? void 0 : currentContent.allowGoBackToAssociatedContent())) {
return this.goBackToMainContent();
}
this.closeCurrentSlide();
}
closeCurrentSlide() {
if (this.currentSlide.hasPreviousContent()) {
at.actiontracker.trackAction({
fromPlace: 7 /* READER_MAP */,
toPlace: 9 /* READER_OTHER_MAP */,
supposedEventType: [0 /* MOUSE_DOWN */],
additionalUrl: '?closecurrentSlide',
});
this.goBackToMainContent();
}
else {
this.close();
}
}
goBackToMainContent(callback) {
var currentContent = this.currentSlide.getContent();
if (currentContent) {
if (!currentContent.onBeforeDestroy()) {
this.sandbox.logger.i('content destruction prevented');
return;
}
currentContent.destroy();
}
this.currentSlide.goBackToPreviousContent((backContent) => {
if (!backContent) {
this.close(callback);
return;
}
backContent.loadModel((contentDimensions) => {
this.contentProvider.modifyContentDimensions(this.getCurrentSlide().getContentDescriptor(), contentDimensions);
backContent.buildView(this);
this.refreshCurrentSlideContent(backContent);
});
this.currentSlide.setContent(backContent);
});
}
// trigger the loading of a slide content, and add it to the specified container when available
loadSlideContent(slide, index, loadAdjacentSlides = false) {
if (!slide) {
return;
}
slide.loadContent(this.getDivAtIndex(index), this.contentProvider, () => {
this.onSlideContentLoaded(slide, index, loadAdjacentSlides);
}, () => {
this.onSlideReady(index);
});
}
onSlideContentLoaded(slide, index, loadAdjacentSlides) {
if (this.hasBeenDestroyed) {
}
else {
this.addSlideContentToContainerAtIndex(slide.getContent(), index);
if (this.currentIndex === index) {
if (this.isFirstSlideLoaded) {
var content = this.currentSlide.getContent();
if (content) {
var scroll = {
scroller: content.getView(this).$el.children(),
scrollee: content.getView(this).$el.find('.reader-content'),
type: 1 /* READER */,
clearScroll: true,
};
this.sandbox
.getEventBus()
.publish(37 /* SCROLLER_CATCHER_CHANNEL */, 1 /* NOTIFY_SCROLLING_COMPONENT */, scroll);
}
this.isFirstSlideLoaded = false;
}
this.enableSlideContent(slide);
}
if (loadAdjacentSlides) {
this.loadAdjacentSlides(slide, index);
}
}
}
onSlideReady(index) {
if (this.currentIndex === index) {
var curr = this.currentSlide[this.currentIndex];
var is = curr && curr.isScrollableContent();
var event = {
idx: this.currentIndex,
isScrollable: is,
};
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 5 /* NEW_SLIDE_READY */, event);
clearTimeout(this.showCloseButtonID);
this.showCloseButtonID = setTimeout(() => {
this.showCloseButton();
}, 400);
}
}
refreshCurrentSlideContent(content) {
this.addSlideContentToContainerAtIndex(content, this.currentIndex);
// '[READER] changeAndRefreshCurrentSlideContent slide ' + this.currentSlide.getContentDescriptor() + ' at index ' + this.currentIndex
// );
this.enableSlideContent(this.currentSlide);
this.notifyNewScrollingComponent(content);
if (this.currentSlide.hasPreviousContent()) {
this.hideArrowsForSubPanel();
}
else {
this.showArrowsIfNeeded();
}
this.showCloseButton();
}
addSlideContentToContainerAtIndex(content, index) {
var container = this.getDivAtIndex(index);
var view = content.getView(this);
container.append(view.$el);
content.onAdded();
if (this.sandbox.isAnonymousMode() && !this.sandbox.isEmbedMode() && !this.sandbox.isMobile()) {
sb.scrollbar.changeScrollbarScale(container, re.helper.anonymousMarginTopMinValue, this.sandbox);
}
}
// called when a slide is now the current one
enableSlideContent(slide) {
if (slide && slide.getContainer()) {
var slideContainer = slide.getContainer();
var nanoContainer = slideContainer.find(re.helper.NANO_CONTENT);
var readerContentContainer = slideContainer.find(re.helper.READER_CONTENT);
if (nanoContainer.length > 0 && readerContentContainer.length > 0) {
nanoContainer.on('click', (e) => {
var shouldClose = true;
if ($(e.target).is('input')) {
shouldClose = false;
}
if ($(e.target).parents('.pinterest').length || $(e.target).parents('#tui-image-editor-container').length) {
shouldClose = false;
}
if (shouldClose) {
this.closeCurrentSlide();
}
});
readerContentContainer.on('click', (e) => {
if ($(e.target).is('input')) {
return true;
}
if ($(e.target).parents('.pinterest').length || $(e.target).parents('#tui-image-editor-container').length) {
return true;
}
return false;
});
}
slide.enableContent();
//FIXME: interface with getId()
var currentContent = this.getCurrentSlide().getContentDescriptor();
var currentContentId;
if (currentContent['pearl']) {
currentContentId = currentContent['pearl'].id;
}
else if (currentContent['data']) {
currentContentId = currentContent['data'].id;
}
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 4 /* NEW_SLIDE_ENABLED */, { idx: currentContentId });
if (slide.isReady()) {
var event = {
idx: this.currentIndex,
height: 1500,
isScrollable: slide.isScrollableContent(),
};
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 5 /* NEW_SLIDE_READY */, event);
}
}
}
// called when a slide has gone out of the screen
disableSlideContent(slide) {
if (slide) {
slide.disableContent();
}
}
getIsTransitioning() {
return this.isTransitioning;
}
// called when a slide is no longer necessary : it should release all resources
destroySlideContent(slide) {
if (slide) {
return slide.destroyContent();
}
return true;
}
// called when a slide has been displayed, be it after a click on a swipe arrow or after a touch gesture, or even first load
// it updates the mutable state of the reader, notably currentIndex and currentSlide, and perform the necessary unload/load operations
onTransitionEnd() {
this.isTransitioning = false;
}
onSlideDisplayed(index) {
var formerIndex = this.currentIndex;
var formerSlide = this.currentSlide;
this.currentIndex = index;
var slideToDestroy;
var indexToDestroy;
var indexDelta = (index + this.swipeSlideCount - formerIndex) % this.swipeSlideCount;
if (indexDelta === 1) {
// it was a next slide movement
//this.log('has moved to next');
slideToDestroy = this.slideCollection.getPreviousSlide(formerSlide);
indexToDestroy = formerIndex - 1;
this.currentSlide = this.slideCollection.getNextSlide(this.currentSlide);
}
else if (indexDelta === this.swipeSlideCount - 1) {
// it was a previous slide movement
//this.log('has moved to previous');
slideToDestroy = this.slideCollection.getNextSlide(formerSlide);
indexToDestroy = formerIndex + 1;
this.currentSlide = this.slideCollection.getPreviousSlide(this.currentSlide);
}
else {
}
this.updateMovementRights(false);
this.enableSlideContent(this.currentSlide);
this.destroySlideContent(slideToDestroy);
this.disableSlideContent(formerSlide);
this.loadAdjacentSlides(this.currentSlide, index);
if (this.currentSlide.hasPreviousContent()) {
this.hideArrowsForSubPanel();
}
else {
this.showArrowsIfNeeded();
}
if (this.currentSlide.isReady()) {
clearTimeout(this.showCloseButtonID);
this.showCloseButtonID = setTimeout(() => {
this.showCloseButton();
}, 400);
}
var content = this.currentSlide.getContent();
if (content) {
this.manuallyTrackViewIfNeeded(content);
this.notifyNewScrollingComponent(content);
}
else {
this.sandbox.logger.e('[READER] not current slide content');
}
}
manuallyTrackViewIfNeeded(content) {
if (typeof content.getReaderContext === 'function') {
var context = content.getReaderContext();
if (context != null) {
var contextType = context.getType();
if (contextType == 1 /* MY_NETWORK */ || contextType == 2 /* DISCOVER */) {
this.sandbox.getEventBus().publish(50 /* HITSENDER_CHANNEL */, 1 /* VIEW_IN_READER */, content.getPearlId());
}
}
}
}
showCloseButton() {
var mainDivWidth = this.$div.width();
var margin = re.helper.getReaderMargin(this.sandbox, mainDivWidth);
this.setCloseButtonPosition(margin);
this.getCloseButton().show();
}
notifyNewScrollingComponent(content) {
var scroll = {
scroller: content.getView(this).$el.children(),
scrollee: content.getView(this).$el.find('.reader-content'),
type: 1 /* READER */,
clearScroll: true,
forcePanel: content.clearReaderScroll && content.clearReaderScroll() ? true : undefined,
};
if (content.isContentReady()) {
scroll.notifyHeight = scroll.scroller.children().outerHeight(true);
}
this.sandbox.getEventBus().publish(37 /* SCROLLER_CATCHER_CHANNEL */, 1 /* NOTIFY_SCROLLING_COMPONENT */, scroll);
}
// trigger the loading of the slides adjacent to the specified one
loadAdjacentSlides(slide, index) {
var previousSlide = this.slideCollection.getPreviousSlide(slide);
if (previousSlide) {
this.loadSlideContent(previousSlide, this.getPreviousIndex(index));
}
var nextSlide = this.slideCollection.getNextSlide(slide);
if (nextSlide) {
this.loadSlideContent(nextSlide, this.getNextIndex(index));
}
}
// return the slide div at the specified index
getDivAtIndex(index) {
return this.$div.find('#slider').find('.swipe-wrap > div[data-index="' + index + '"] > .slide');
}
// allow to get the previous/next index following a circular pattern
getPreviousIndex(index) {
return (index - 1 + this.swipeSlideCount) % this.swipeSlideCount;
}
getNextIndex(index) {
return (index + 1) % this.swipeSlideCount;
}
// update the visibility of the previous and next arrows depending on the state of the slide collection
updateMovementRights(withFade) {
var noLeftSlide = this.slideCollection.getPreviousSlide(this.currentSlide) === undefined;
var noRightSlide = this.slideCollection.getNextSlide(this.currentSlide) === undefined;
if (noLeftSlide && noRightSlide && this.swipe) {
//NN swipe.js set moveleft and moveright to true when window resize. to prevent it, we killed it beforehand.
this.swipe.kill();
}
if (noLeftSlide) {
this.setCanMoveLeft(false, withFade);
}
else {
this.setCanMoveLeft(true, withFade);
}
if (noRightSlide) {
this.setCanMoveRight(false, withFade);
}
else {
this.setCanMoveRight(true, withFade);
}
}
setCanMoveLeft(b, withFade) {
this.canMoveLeft = b;
var previous = this.getPreviousArrow();
if (b && !this.forceHideMoveLeftAndRight) {
previous.show();
}
else {
previous.hide();
}
if (this.swipe) {
this.swipe.moveLeft(b);
}
}
setCanMoveRight(b, withFade) {
this.canMoveRight = b;
var next = this.getNextArrow();
if (b && !this.forceHideMoveLeftAndRight) {
next.show();
}
else {
next.hide();
}
if (this.swipe) {
this.swipe.moveRight(b);
}
}
hideArrowsForSubPanel() {
this.forceHideMoveLeftAndRight = true;
this.getPreviousArrow().hide();
this.getNextArrow().hide();
}
showArrowsIfNeeded() {
this.forceHideMoveLeftAndRight = false;
this.setCanMoveLeft(this.canMoveLeft, false);
this.setCanMoveRight(this.canMoveRight, false);
}
// getter for swipe arrows and close button
getPreviousArrow() {
return this.$div.find('.previous');
}
getNextArrow() {
return this.$div.find('.next');
}
getTouchPreviousArrow() {
return this.$div.find('.touch-previous-button');
}
getTouchNextArrow() {
return this.$div.find('.touch-next-button');
}
getCloseButton() {
return this.$div.find('.close');
}
getTouchCloseButton() {
return this.$div.find('.touch-close-button');
}
getSlide() {
return this.$div.find('.slide');
}
listenToSlideReadyEvents() {
this.subId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 6 /* IS_CURRENT_SLIDE_READY */, (cb) => {
var curr = this.currentSlide[this.currentIndex];
if (curr && curr.isReady()) {
cb(curr.isScrollableContent());
}
else {
this.sandbox.getEventBus().subscribeOnce(3 /* READER_CHANNEL */, 5 /* NEW_SLIDE_READY */, (ev) => {
cb(ev.isScrollable);
}, this);
}
}, this);
}
listenToResizeEvent() {
this.reloadContentEventListenerId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 14 /* RELOAD_CONTENT */, () => {
var currentContent = this.getCurrentSlide().getContent();
if (currentContent) {
currentContent.invalidateModel();
currentContent.loadModel((contentDimensions) => {
this.contentProvider.modifyContentDimensions(this.getCurrentSlide().getContentDescriptor(), contentDimensions);
this.refreshCurrentSlideContent(currentContent);
});
}
}, this);
}
setDispatchActionWhenClosed() {
this.dispatchAction = true;
}
listenToGetCurrentReader() {
this.listenerId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 17 /* GET_CURRENT_READER */, (cb) => {
cb(this);
}, this);
}
listenToGetReaderDimensions() {
this.readerDimensionslistenerId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 21 /* GET_READER_DIMENSIONS */, (cb) => {
var currentSlide = this.getCurrentSlide();
var currentReaderContent = currentSlide.getContainer().find(re.helper.READER_CONTENT);
var currentContentDescriptor = currentSlide.getContentDescriptor();
var adaptReaderSize = this.contentProvider.isResizeRequired(currentContentDescriptor);
var contentHeight;
var params;
if (adaptReaderSize) {
var currentSlideContainer = currentSlide.getContainer();
contentHeight = this.contentProvider.getContentHeight(currentContentDescriptor, currentSlideContainer);
params = re.helper.getResizedReaderGraphicalParameters(this.sandbox, contentHeight, currentSlideContainer);
}
else {
params = re.helper.getDefaultReaderGraphicalParameters(this.sandbox);
}
var readerContentHeight = params.height;
if (currentReaderContent.length > 0) {
readerContentHeight = currentReaderContent.height();
}
cb(params.top, readerContentHeight, params.bottom, this.withBanner);
}, this);
}
}
class ReaderLayout extends Marionette.Layout {
constructor() {
super({
template: require('text!./template.html'),
});
}
}
})(reader = exports.reader || (exports.reader = {}));
});
///
///
///
///
define('app/objects/reader/content',["require", "exports", "app/ui/nodeaction/nodeaction", "app/core/navigation/description", "app/core/navigation/navigationclient"], function (require, exports, na, nd, nm) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reader = void 0;
var reader;
(function (reader_1) {
// TODO : move this elsewhere, improve abstraction
class SimpleContent {
constructor(sandbox) {
this.additionalActions = {};
this.sandbox = sandbox;
this.withNavigation = false;
}
setWithNavigation(v) {
this.withNavigation = v;
}
getView(reader) {
if (this.layout) {
return this.layout;
}
this.buildView(reader);
return this.layout;
}
buildView(reader) {
throw 'To be implemented';
}
withAdditionalAction(additionalActions) {
this.additionalActions = additionalActions;
}
handleAdditionnalActions(reader) {
if (!this.additionalActions) {
return;
}
var actions = [];
if (this.additionalActions.navigate) {
actions.push(new na.nodeaction.ClientNodeAction('Navigate', () => this.onClickNavigateInternal(reader)));
}
this.commonHelper.withAdditionnalNodeActions(actions);
}
getNavTreeId() {
return 0;
}
onClickNavigateInternal(reader) {
reader.close(() => {
var desc = nd.navigation.makeTreeNavigation(this.getNavTreeId());
nm.navigation.getManager(this.sandbox).goTo(desc);
});
}
onAdded() { }
enable() { }
loadModel(onModelLoaded) {
if (onModelLoaded) {
onModelLoaded();
}
else {
this.sandbox.logger.w('onModelLoaded is not defined.');
}
}
invalidateModel() {
return false;
}
initPosition(pos) { }
onBeforeDestroy() {
return true;
}
disable() { }
clearView() {
if (this.layout) {
this.layout.close();
}
this.layout = null;
}
isDestroyed() {
return this.isEnded;
}
destroy() {
this.isEnded = true;
this.clearView();
}
isScrollableContent() {
return false;
}
isContentReady() {
return this.isReady;
}
}
reader_1.SimpleContent = SimpleContent;
})(reader = exports.reader || (exports.reader = {}));
});
define('text!app/ui/reader/dailymotion/template.html',[],function () { return '';});
///
///
define('app/ui/reader/dailymotion/dailymotion',["require", "exports", "jquery", "text!./template.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dailymotion = void 0;
///
///
var dailymotion;
(function (dailymotion) {
var DAILYMOTION_PATTERN = 'http(?:s?)://(?:(?:www\\.)?)dailymotion\\.com/video/(.+)';
function getDailymotionVideoId(url) {
var dailymotionRegex = new RegExp(DAILYMOTION_PATTERN, 'g');
var result = dailymotionRegex.exec(url);
if (result) {
return result[1];
}
return undefined;
}
dailymotion.getDailymotionVideoId = getDailymotionVideoId;
function createPlayer(element, videoID, callback) {
if (BrowserDetect.browser == 'Firefox') {
var player = DM.player(element, {
video: videoID,
params: {
api: 1,
logo: 0,
related: 0,
html: 1,
},
});
player.addEventListener('apiready', () => {
callback(player);
});
}
else {
var player = DM.player(element, {
video: videoID,
params: {
api: 1,
logo: 0,
related: 0,
},
});
player.addEventListener('apiready', () => {
callback(player);
});
}
}
dailymotion.createPlayer = createPlayer;
function getTemplate() {
return require('text!./template.html');
}
dailymotion.getTemplate = getTemplate;
class DailymotionPlayer {
static doWhenDailymotionApiIsLoaded(callback) {
if (DailymotionPlayer.DAILYMOTION_API_LOADING_DEFERRED) {
DailymotionPlayer.DAILYMOTION_API_LOADING_DEFERRED.done(() => callback());
}
else {
DailymotionPlayer.DAILYMOTION_API_LOADING_DEFERRED = $.Deferred();
DailymotionPlayer.DAILYMOTION_API_LOADING_DEFERRED.done(() => callback());
DailymotionPlayer.loadDailymotionAPI(DailymotionPlayer.DAILYMOTION_API_LOADING_DEFERRED);
}
}
static loadDailymotionAPI(deferred) {
window[DailymotionPlayer.DAILYMOTION_PLAYER_API_CALLBACK] = () => {
window[DailymotionPlayer.DAILYMOTION_PLAYER_API_CALLBACK] = () => { };
deferred.resolve();
};
var tag = document.createElement('script');
tag.async = true;
tag.src = '//api.dmcdn.net/all.js';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
DailymotionPlayer.DAILYMOTION_PLAYER_API_CALLBACK = 'dmAsyncInit';
dailymotion.DailymotionPlayer = DailymotionPlayer;
})(dailymotion = exports.dailymotion || (exports.dailymotion = {}));
});
define('text!app/ui/reader/gmaps/gmaps.html',[],function () { return '';});
///
///
define('app/ui/reader/gmaps/gmaps',["require", "exports", "app/configuration/configuration", "text!app/ui/reader/gmaps/gmaps.html"], function (require, exports, cf) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.gmaps = void 0;
//TODO Please refactor me
var gmaps;
(function (gmaps) {
var GOOGLE_API_KEY = '?key=' + cf.configuration.getConfig().getGoogleMapsApiKey();
var MAPS_API_URL = 'https://www.google.com/maps/embed/v1/';
var MAPS_PLACE_PREFIX = 'place';
var MAPS_SEARCH_PREFIX = 'search';
var MAPS_VIEW_PREFIX = 'view';
var MAPS_DIRECTIONS_PREFIX = 'directions';
var MAPS_QUERY_KEY = '&q=';
var MAPS_ORIGIN_KEY = '&origin=';
var MAPS_DESTINATION_KEY = '&destination=';
var MAPS_WAYPOINTS_KEY = '&waypoints=';
var MAPS_MODE_KEY = '&mode=';
var MAPS_UNITS_KEY = '&units=';
var MAPS_SEARCH_AROUND = '+near+';
var MAPS_CENTER_KEY = '¢er=';
var MAPS_ZOOM_KEY = '&zoom=';
var MAPS_SATELLITE = '&maptype=satellite';
var MAPS_SATELLITE_DEFAULT_ZOOM = '&zoom=16';
var MAPS_SEARCH_DEFAULT_ZOOM = '&zoom=14';
var MAPS_OLD_URL_PATTERN = '(http(?:s?)://(?:(?:www\\.)?)maps\\.google\\.(?:[a-z\\.]+)/maps\\?\\S+)';
var MAPS_NEW_URL_PATTERN = '(?:http(?:s?)://(?:(?:www\\.)?)google\\.(?:[a-z\\.]+)/maps/(?:(\\w+)/)?(?:(\\S+)))';
var MAPS_OPTIONS_PATTERN = '@((?:[-+]?\\d{1,2}(?:[\\.]\\d+)?),(?:[-+]?\\d{1,3}(?:[\\.]\\d+)?)),(\\d+)(\\w+)';
var MAPS_DATA_PATTERN = '(?:data=\\.+)';
/** COMMON TO OLD AND NEW URLS **/
function processGmapsURL(url) {
if (url.match(MAPS_OLD_URL_PATTERN)) {
/* if url has pattern https://maps.google.fr/maps? */
return proccessGmapsOldUrl(1 /* OLD */, url);
}
else if (url.match(MAPS_NEW_URL_PATTERN)) {
/* if url has pattern https://www.google.fr/maps/[MAPMODE] */
return proccessGmapsNewUrl(2 /* NEW */, url);
}
return null;
}
gmaps.processGmapsURL = processGmapsURL;
function getEmbedUrl(urlType, urlParams, embedType) {
if (urlType == 2 /* NEW */) {
if (embedType == 1 /* PLACE */) {
return MAPS_API_URL + MAPS_PLACE_PREFIX + GOOGLE_API_KEY + urlParams;
}
else if (embedType == 2 /* SEARCH */) {
return MAPS_API_URL + MAPS_SEARCH_PREFIX + GOOGLE_API_KEY + urlParams;
}
else if (embedType == 3 /* VIEW */) {
return MAPS_API_URL + MAPS_VIEW_PREFIX + GOOGLE_API_KEY + urlParams;
}
else if (embedType == 4 /* DIRECTIONS */) {
return MAPS_API_URL + MAPS_DIRECTIONS_PREFIX + GOOGLE_API_KEY + urlParams;
}
}
else if (urlType == 1 /* OLD */) {
if (embedType == 1 /* PLACE */) {
return MAPS_API_URL + MAPS_PLACE_PREFIX + GOOGLE_API_KEY + urlParams;
}
else if (embedType == 2 /* SEARCH */) {
return MAPS_API_URL + MAPS_SEARCH_PREFIX + GOOGLE_API_KEY + urlParams;
}
else if (embedType == 4 /* DIRECTIONS */) {
return MAPS_API_URL + MAPS_DIRECTIONS_PREFIX + GOOGLE_API_KEY + urlParams;
}
}
return null;
}
gmaps.getEmbedUrl = getEmbedUrl;
function getTemplate() {
return require('text!app/ui/reader/gmaps/gmaps.html');
}
gmaps.getTemplate = getTemplate;
/** COMMON TO OLD AND NEW URLS **/
/** OLD URLS PROCESSING **/
function parseQueryString(url) {
return url.split('?')[1].split('&');
}
gmaps.parseQueryString = parseQueryString;
function getQueryVariable(key, urlParams, searchMode) {
for (var cpt = 0; cpt < urlParams.length; cpt++) {
var queryString = urlParams[cpt].split('=');
if (queryString[0] == key && queryString[1]) {
if (searchMode) {
return true;
}
return queryString[1];
}
}
return false;
}
gmaps.getQueryVariable = getQueryVariable;
function getOptionalParams(urlParams, embedType) {
var urlParam = '';
if (getQueryVariable('t', urlParams, true)) {
var mapType = getQueryVariable('t', urlParams);
if (mapType == 'k' || mapType == 'h') {
urlParam += MAPS_SATELLITE;
}
}
if (getQueryVariable('z', urlParams, true) && embedType != 4 /* DIRECTIONS */) {
urlParam += MAPS_ZOOM_KEY + getQueryVariable('z', urlParams);
}
if (!getQueryVariable('z', urlParams, true) && embedType != 4 /* DIRECTIONS */ && embedType != 1 /* PLACE */) {
//TODO Determine best zoom level
urlParam += MAPS_SEARCH_DEFAULT_ZOOM;
}
return urlParam;
}
gmaps.getOptionalParams = getOptionalParams;
function getDirectionsUnits(urlParams) {
if (getQueryVariable('doflg', urlParams, true)) {
var units = getQueryVariable('doflg', urlParams);
if (units == 'ptk') {
return MAPS_UNITS_KEY + 'metric';
}
else if (units == 'ptm') {
return MAPS_UNITS_KEY + 'imperial';
}
}
return '';
}
gmaps.getDirectionsUnits = getDirectionsUnits;
function getDirectionsMode(urlParams) {
if (getQueryVariable('dirflg', urlParams, true)) {
var modeParam = getQueryVariable('dirflg', urlParams);
if (modeParam == 'r') {
return MAPS_MODE_KEY + 'transit';
}
else if (modeParam == 'w') {
return MAPS_MODE_KEY + 'walking';
}
else if (modeParam == 'b') {
return MAPS_MODE_KEY + 'bicycling';
}
else {
return MAPS_MODE_KEY + 'driving';
}
}
return '';
}
gmaps.getDirectionsMode = getDirectionsMode;
function getDirectionsWaypoints(route) {
var waypoints = '';
var limit = route.length - 1;
for (var cpt = 0; cpt < limit; cpt++) {
if (cpt < limit - 1) {
waypoints += route[cpt] + '|';
}
else {
waypoints += route[cpt];
}
}
return waypoints ? MAPS_WAYPOINTS_KEY + waypoints : '';
}
gmaps.getDirectionsWaypoints = getDirectionsWaypoints;
function getDirectionsDestination(parsedString) {
var route = getQueryVariable('daddr', parsedString).split('+to:');
var destination = route[route.length - 1];
if (route.length > 1) {
destination += getDirectionsWaypoints(route);
}
return MAPS_DESTINATION_KEY + destination;
}
gmaps.getDirectionsDestination = getDirectionsDestination;
function getDirectionsOrigin(parsedString) {
return MAPS_ORIGIN_KEY + getQueryVariable('saddr', parsedString);
}
gmaps.getDirectionsOrigin = getDirectionsOrigin;
function getDirections(parsedString) {
var urlParams = '';
urlParams += getDirectionsOrigin(parsedString);
urlParams += getDirectionsDestination(parsedString);
urlParams += getDirectionsMode(parsedString);
urlParams += getDirectionsUnits(parsedString);
return urlParams;
}
gmaps.getDirections = getDirections;
function getStartingPoint(parsedString) {
if (getQueryVariable('sll', parsedString, true)) {
return getQueryVariable('sll', parsedString);
}
else if (getQueryVariable('ll', parsedString, true)) {
return getQueryVariable('ll', parsedString);
}
return null;
}
gmaps.getStartingPoint = getStartingPoint;
function proccessGmapsOldUrl(urlType, url) {
var uri_dec = decodeURIComponent(url);
var parsedString = parseQueryString(uri_dec);
if (getQueryVariable('q', parsedString, true)) {
var query = getQueryVariable('q', parsedString);
// Can be place or business search around position
var mapType = 1 /* PLACE */;
var urlParams = query ? MAPS_QUERY_KEY + query : '';
var start = getStartingPoint(parsedString);
if (!getQueryVariable('cid', parsedString, true)) {
mapType = 2 /* SEARCH */;
//TODO find a more accurate method to determine map type
var parseQuery = query.split(',');
if (parseQuery.length == 1) {
/* if the query does not match a specific place we must specify center parameter */
urlParams += start ? MAPS_CENTER_KEY + start : '';
}
}
else {
/* If cid is present then its a map markers to a business */
urlParams += start ? MAPS_SEARCH_AROUND + start : '';
}
urlParams += getOptionalParams(parsedString, mapType);
return getEmbedUrl(urlType, urlParams, mapType);
}
else if (getQueryVariable('saddr', parsedString, true) && getQueryVariable('daddr', parsedString, true)) {
var urlParams = getDirections(parsedString);
urlParams += getOptionalParams(parsedString, 4 /* DIRECTIONS */);
return getEmbedUrl(urlType, urlParams, 4 /* DIRECTIONS */);
}
return null;
}
gmaps.proccessGmapsOldUrl = proccessGmapsOldUrl;
/** OLD URLS PROCESSING **/
/** NEW URLS PROCESSING **/
function containsData(url) {
return url.match(MAPS_DATA_PATTERN);
}
gmaps.containsData = containsData;
function containsOptions(url) {
return url.match(MAPS_OPTIONS_PATTERN);
}
gmaps.containsOptions = containsOptions;
function getZoom(urlParam) {
return urlParam ? MAPS_ZOOM_KEY + urlParam : '';
}
gmaps.getZoom = getZoom;
function getOrigin(urlParam, embedType) {
var origin = '';
if (embedType == 1 /* PLACE */) {
origin = MAPS_CENTER_KEY + urlParam;
}
else if (embedType == 2 /* SEARCH */) {
origin = MAPS_CENTER_KEY + urlParam;
}
else if (embedType == 3 /* VIEW */) {
origin = MAPS_CENTER_KEY + urlParam;
}
return origin ? origin : '';
}
gmaps.getOrigin = getOrigin;
function getOptions(urlParams, embedType) {
var optionsRegex = new RegExp(MAPS_OPTIONS_PATTERN, 'g');
var options = optionsRegex.exec(urlParams);
if (options) {
var urlParam = getOrigin(options[1], embedType);
if (options[3] == 'm') {
urlParam += MAPS_SATELLITE;
if (embedType != 4 /* DIRECTIONS */) {
urlParam += MAPS_SATELLITE_DEFAULT_ZOOM;
}
}
else if (options[3] == 'z' && embedType != 4 /* DIRECTIONS */) {
urlParam += getZoom(options[2]);
}
return urlParam;
}
return null;
}
gmaps.getOptions = getOptions;
function getPlace(urlParam) {
return MAPS_QUERY_KEY + urlParam;
}
gmaps.getPlace = getPlace;
function getRouteFromUrl(parsedString) {
var routeParam = [];
for (var cpt = 0; cpt < parsedString.length - 1; cpt++) {
if (!containsOptions(parsedString[cpt]) && !containsData(parsedString[cpt])) {
routeParam.push(parsedString[cpt]);
}
}
return routeParam;
}
gmaps.getRouteFromUrl = getRouteFromUrl;
function getRouteWaypoints(route) {
if (route.length > 1) {
var waypoints = '';
var limit = route.length - 1;
for (var cpt = 0; cpt <= limit; cpt++) {
waypoints += route[cpt];
if (cpt < limit) {
waypoints += '|';
}
}
return MAPS_WAYPOINTS_KEY + waypoints;
}
return MAPS_WAYPOINTS_KEY + route[route.length - 1];
}
gmaps.getRouteWaypoints = getRouteWaypoints;
function getRouteDestination(route) {
return MAPS_DESTINATION_KEY + route.pop();
}
gmaps.getRouteDestination = getRouteDestination;
function getRouteOrigin(route) {
return MAPS_ORIGIN_KEY + route.shift();
}
gmaps.getRouteOrigin = getRouteOrigin;
function getRouteParam(parsedString) {
var routeParam = getRouteFromUrl(parsedString);
if (routeParam.length > 1) {
if (!routeParam[0] && routeParam[1]) {
routeParam[0] = routeParam[1];
}
else if (!routeParam[1] && routeParam[0]) {
routeParam[1] = routeParam[0];
}
}
var urlParam = getRouteOrigin(routeParam);
urlParam += getRouteDestination(routeParam);
if (routeParam.length > 0) {
urlParam += getRouteWaypoints(routeParam);
}
return urlParam;
}
gmaps.getRouteParam = getRouteParam;
function proccessGmapsNewUrl(urlType, url) {
var gmapsRegex = new RegExp(MAPS_NEW_URL_PATTERN, 'g');
/* [0] is https://www.google.fr/maps/
* [1] is map mode
* [2] is query-string
*/
var uri_dec = decodeURIComponent(url);
var result = gmapsRegex.exec(uri_dec);
if (result) {
var mapMode = result[1];
var parsedString = result[2].split('/');
if (mapMode == 'place') {
var urlParams = getPlace(parsedString.shift());
if (containsOptions(parsedString[0])) {
urlParams += getOptions(parsedString[0], 1 /* PLACE */);
}
return getEmbedUrl(urlType, urlParams, 1 /* PLACE */);
}
else if (mapMode == 'search') {
var urlParams = getPlace(parsedString.shift());
if (containsOptions(parsedString[0])) {
urlParams += getOptions(parsedString[0], 2 /* SEARCH */);
}
return getEmbedUrl(urlType, urlParams, 2 /* SEARCH */);
}
else if (mapMode == 'dir') {
var urlParams = getRouteParam(parsedString);
for (var cpt = 0; cpt < parsedString.length - 1; cpt++) {
if (containsOptions(parsedString[cpt])) {
urlParams += getOptions(parsedString[cpt], 4 /* DIRECTIONS */);
}
}
return getEmbedUrl(urlType, urlParams, 4 /* DIRECTIONS */);
}
else if (containsOptions(parsedString[0])) {
var urlParams = getOptions(parsedString[0], 3 /* VIEW */);
return getEmbedUrl(urlType, urlParams, 3 /* VIEW */);
}
return null;
}
return null;
}
gmaps.proccessGmapsNewUrl = proccessGmapsNewUrl;
/** NEW URLS PROCESSING **/
})(gmaps = exports.gmaps || (exports.gmaps = {}));
});
define('text!app/ui/reader/ina/embed.html',[],function () { return '';});
///
define('app/ui/reader/ina/ina',["require", "exports", "jquery", "text!app/ui/reader/ina/embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ina = void 0;
///
///
var ina;
(function (ina) {
var INA_PATTERN = 'http(?:s?)://(?:(?:www\\.)?)ina\\.fr/(?:video|audio)/(\\w+)';
var INA_EMBED_PREFIX = 'http://player.ina.fr/player/embed/';
var INA_EMBED_SUFFIX = '/1/1b0bd203fbcd702f9bc9b10ac3d0fc21';
function getInaElementId(url) {
var inaRegex = new RegExp(INA_PATTERN, 'g');
var result = inaRegex.exec(url);
if (result) {
return result[1];
}
else {
return undefined;
}
}
ina.getInaElementId = getInaElementId;
function getEmbedUrl(videoId) {
return INA_EMBED_PREFIX + videoId + INA_EMBED_SUFFIX;
}
ina.getEmbedUrl = getEmbedUrl;
function getTemplate() {
return require('text!app/ui/reader/ina/embed.html');
}
ina.getTemplate = getTemplate;
class Ina {
}
ina.Ina = Ina;
})(ina = exports.ina || (exports.ina = {}));
});
define('text!app/ui/reader/instagram/embed.html',[],function () { return '';});
///
///
define('app/ui/reader/instagram/instagram',["require", "exports", "app/helper/urlhelper", "text!app/ui/reader/instagram/embed.html"], function (require, exports, uh) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.instagram = void 0;
var instagram;
(function (instagram) {
var INSTAGRAM_API_URL = '//api.instagram.com/oembed';
var INSTAGRAM_PATTERN = '(http(?:s?)://(?:(?:www\\.)?)instagram.com/p/(?:\\S+))';
function isValidInstagramURL(url) {
var instagramRegex = new RegExp(INSTAGRAM_PATTERN, 'g');
var result = instagramRegex.exec(url);
if (result) {
return result[1];
}
else {
return undefined;
}
}
instagram.isValidInstagramURL = isValidInstagramURL;
function getTemplate() {
return require('text!app/ui/reader/instagram/embed.html');
}
instagram.getTemplate = getTemplate;
function instagramAPIRequest(url, callback) {
$.support.cors = true;
$.ajax({
type: 'GET',
url: INSTAGRAM_API_URL,
dataType: 'jsonp',
data: {
url: url,
},
success: function (json) {
var imgLink = json.thumbnail_url;
callback(imgLink);
},
error: function (jqXHR, textStatus, errorThrow) {
callback(uh.urlhelper.getAssetUrl('images/file/default/thumb-square.jpg'));
},
crossDomain: true,
timeout: 5000,
});
}
instagram.instagramAPIRequest = instagramAPIRequest;
})(instagram = exports.instagram || (exports.instagram = {}));
});
///
///
define('app/external/facebooksdk',["require", "exports", "app/gen/service/user"], function (require, exports, u) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.facebook = void 0;
var facebook;
(function (facebook) {
var DEFERRED;
function doWhenFacebookSdkInitialized(callback) {
if (DEFERRED) {
DEFERRED.done(() => callback());
}
else {
DEFERRED = $.Deferred();
DEFERRED.done(() => callback());
init(DEFERRED);
}
}
facebook.doWhenFacebookSdkInitialized = doWhenFacebookSdkInitialized;
function init(deferred) {
window.fbAsyncInit = function () {
FB.init({
appId: PearltreesEnvParams.facebookAppId,
version: 'v3.3',
});
deferred.resolve();
};
// copy pasted from FB doc
// cf https://developers.facebook.com/docs/plugins/embedded-posts
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
var localeString = getLocaleString();
js.src = '//connect.facebook.net/' + localeString + '/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'facebook-jssdk');
}
function renewFacebookTokenInBackground(sandbox) {
FB.getLoginStatus(function (response) {
if (response.status === 'connected' && response.authResponse && response.authResponse.accessToken) {
var shortTermToken = response.authResponse.accessToken;
sendShortTermFacebookToken(sandbox, shortTermToken);
}
});
}
facebook.renewFacebookTokenInBackground = renewFacebookTokenInBackground;
function sendShortTermFacebookToken(sandbox, shortTermToken) {
if (shortTermToken && shortTermToken.length > 0) {
u.User.updateFacebookToken(sandbox, shortTermToken, (res) => {
});
}
}
function getLocaleString() {
if (PearltreesEnvParams.locale && PearltreesEnvParams.locale == 1) {
return 'fr_FR';
}
else {
return 'en_US';
}
}
})(facebook = exports.facebook || (exports.facebook = {}));
});
///
define('app/ui/reader/page/embed',["require", "exports", "app/ui/reader/common", "app/helper/responsive", "app/core/stats/abtest/abtesthelper", "app/ui/reader/page/contentsize", "app/util/loader/spinloader"], function (require, exports, co, rs, ab, cs, sl) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reader = void 0;
var reader;
(function (reader) {
var embedIndex = 0;
class EmbedView extends Marionette.ItemView {
constructor(sandbox, template, model, ready, pearlId, marginBottomNeeded = false, skipFitToHeight = false) {
super({
model: model,
template: template,
className: 'embed',
id: 'embed' + embedIndex++,
});
this.isViewClosed = false;
this.marginBottomNeeded = false;
this.defaultMarginBottom = 50;
this.onCloseCallbacks = [];
this.ui = {
iframeplayer: '.player',
};
this.pearlId = pearlId;
this.marginBottomNeeded = marginBottomNeeded;
this.sandbox = sandbox;
this.resizeSubscriptionId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 8 /* RESIZE_CONTENT */, (ev) => {
if (ev.id == this.pearlId) {
this.resize();
}
}, this);
this.ready = ready;
this.skipFitToHeight = skipFitToHeight;
}
setOnAddedCallback(onAdded) {
this.onAddedCall = onAdded;
}
addOnCloseCallback(onClose) {
this.onCloseCallbacks.push(onClose);
}
onAdded() {
if (this.onAddedCall) {
this.onAddedCall();
}
this.resize();
this.ready();
}
disable() { }
getEmbedElement() {
if (!this.isViewClosed) {
return this.$el.get(0);
}
return undefined;
}
resize() {
var extract = this.$el.parent();
this.marginBottom = this.marginBottomNeeded ? this.defaultMarginBottom : 0;
if (!this.skipFitToHeight) {
co.reader.fitToHeight(this.sandbox, extract, this.marginBottom);
}
this.notifyHeight();
}
onClose() {
this.sandbox.getEventBus().stopSubscription(this.resizeSubscriptionId);
this.isViewClosed = true;
for (var i = 0; i < this.onCloseCallbacks.length; i++) {
this.onCloseCallbacks[i]();
}
this.onCloseCallbacks = [];
}
notifyHeight() {
var $scrollContainer = this.$el.closest('.nano-content').children();
if (ab.abTestHelper.get(this.sandbox).hasRightCol()) {
var publishNewHeight = {
height: $scrollContainer.outerHeight(true),
type: 1 /* READER */,
scroller: this.$el.closest('.reader').children(),
};
this.sandbox.getEventBus().publish(37 /* SCROLLER_CATCHER_CHANNEL */, 0 /* NEW_HEIGHT */, publishNewHeight);
}
}
}
reader.EmbedView = EmbedView;
class PlayableMediaEmbedView extends EmbedView {
setPlayer(player) {
this.player = player;
this.resize();
}
disable() {
if (this.player) {
this.player.pause();
}
}
onBeforeClose() {
if (this.player) {
this.player.pause();
}
}
}
reader.PlayableMediaEmbedView = PlayableMediaEmbedView;
/* For embed with playback control (Youtube/Dailymotion/Vimeo/Soundcloud/MediaElementJS) */
class MediaWithPlaybackControlView extends PlayableMediaEmbedView {
constructor(sandbox, template, model, ready, pearlId, marginBottomNeeded, withRatio, readerContext, contentDimensions, skipFitToHeight = false) {
super(sandbox, template, model, ready, pearlId, false, skipFitToHeight);
this.withRatio = false;
if (this.model) {
this.listenTo(this.model, 'change', this.render);
}
this.withRatio = withRatio;
this.marginBottomNeeded = marginBottomNeeded;
this.contentDimensions = contentDimensions;
this.readerContext = readerContext;
}
getEmbedElement() {
if (!this.isViewClosed) {
return this.$('.player').get(0);
}
return undefined;
}
getRatio() {
return MediaWithPlaybackControlView.RATIO;
}
resize() {
var extract = this.$el.parent();
this.marginBottom = this.marginBottomNeeded ? this.defaultMarginBottom : 0;
var isReaderResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
if (isReaderResizable) {
var readerContent = this.$el.closest(rs.helper.READER_CONTENT);
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.contentDimensions, rs.helper.getReaderTitleHeight(readerContent));
var player = this.$('.player');
player.width(contentSize.width);
player.height(contentSize.height);
/* Special case for player mediaelementjs */
player.attr('width', contentSize.width);
player.attr('height', contentSize.height);
if (!this.contentDimensions.embedInfo.hasDetail) {
var readerContentContainer = this.$('.player').closest(rs.helper.READER_CONTENT);
if (readerContentContainer.length > 0) {
readerContentContainer.addClass('magnified');
readerContentContainer.addClass('withBackground');
}
}
}
else if (this.withRatio) {
co.reader.fitToHeightWithRatio(this.sandbox, extract, this.$('.player'), this.getRatio(), this.marginBottom);
}
else {
co.reader.fitToHeight(this.sandbox, extract, this.marginBottom);
}
this.notifyHeight();
}
}
MediaWithPlaybackControlView.RATIO = 16 / 9;
reader.MediaWithPlaybackControlView = MediaWithPlaybackControlView;
class PlyrView extends MediaWithPlaybackControlView {
constructor() {
super(...arguments);
this.isAudio = false;
}
configurePlayer(isAudio) {
this.isAudio = isAudio;
return this;
}
getRatio() {
return this.isAudio ? 16 / 5 : super.getRatio();
}
getEmbedElement() {
if (!this.isViewClosed) {
return this.$('.player-tag').get(0);
}
return undefined;
}
}
reader.PlyrView = PlyrView;
/* For media embed with no api methods (TED/Slideshare/TheatreVideo/Ina/Vine) */
class MediaWithNoPlaybackControlView extends EmbedView {
constructor(sandbox, template, model, ready, pearlId, marginBottomNeeded, withRatio, readerContext, contentDimensions) {
super(sandbox, template, model, ready, pearlId);
this.withRatio = false;
if (this.model) {
this.listenTo(this.model, 'change', this.render);
}
this.withRatio = withRatio;
this.marginBottomNeeded = marginBottomNeeded;
this.contentDimensions = contentDimensions;
this.readerContext = readerContext;
}
setEmbedElement() {
this.resize();
}
withLoader() {
var spinLoader = new sl.loader.SpinLoader(this.$('.spinloader'), 2 /* HUGE */, true);
spinLoader.show();
setTimeout(() => {
spinLoader.hide();
this.$('.spinloader').hide();
}, 500);
}
onRender() {
//super.onRender();
if (this.withRatio) {
this.$el.children().addClass('player');
}
}
// override : when disabling this view, we remove it from the dom so the video/audio is stopped
disable() {
if (!this.isViewClosed) {
this.$el.children().remove();
}
return undefined;
}
getRatio() {
return MediaWithNoPlaybackControlView.RATIO;
}
resize() {
var extract = this.$el.parent();
this.marginBottom = this.marginBottomNeeded ? this.defaultMarginBottom : 0;
var isReaderResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
if (isReaderResizable) {
var readerContent = this.$el.closest(rs.helper.READER_CONTENT);
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.contentDimensions, rs.helper.getReaderTitleHeight(readerContent));
var player = this.$('.player');
player.width(contentSize.width);
player.height(contentSize.height);
/* Special case for player mediaelementjs */
player.attr('width', contentSize.width);
player.attr('height', contentSize.height);
if (!this.contentDimensions.embedInfo.hasDetail) {
var readerContentContainer = this.$('.player').closest(rs.helper.READER_CONTENT);
if (readerContentContainer.length > 0) {
readerContentContainer.addClass('magnified');
readerContentContainer.addClass('withBackground');
}
}
}
else if (this.withRatio) {
co.reader.fitToHeightWithRatio(this.sandbox, extract, this.$('.player'), this.getRatio(), this.marginBottom);
}
else {
co.reader.fitToHeight(this.sandbox, extract, this.marginBottom);
}
this.notifyHeight();
}
}
MediaWithNoPlaybackControlView.RATIO = 16 / 9;
reader.MediaWithNoPlaybackControlView = MediaWithNoPlaybackControlView;
class PinterestEmbedView extends EmbedView {
constructor(sandbox, template, model, ready, pearlId, readerContext, contentDimensions) {
super(sandbox, template, model, ready, pearlId, false, true);
this.oldHeight = 0;
this.contentDimensions = contentDimensions;
this.readerContext = readerContext;
this.modelType = model.get('dataPinDo');
}
onRender() {
this.$el.addClass('pinterest');
/* var canObserveMutation = 'MutationObserver' in window;
if (canObserveMutation) {
var observer = new MutationObserver((mutations, observer) => {
this.$el.waitForImages({
finished: () => {
this.resize();
},
})
});
observer.observe(this.el, {
subtree: true,
attributes: true
});
} */
if (this.modelType == 'embedPin') {
this.checkForEmbedHeightModification();
}
}
checkForEmbedHeightModification() {
this.checkForEmbedHeightModificationInternal(0);
}
checkForEmbedHeightModificationInternal(tryCount) {
tryCount++;
var height = this.$el.height();
if (this.oldHeight != height) {
this.resize();
}
else if (tryCount <= 50) {
setTimeout(() => this.checkForEmbedHeightModificationInternal(tryCount), 100);
}
}
resize() {
/* TO DO: MOVE THIS PART ELSEWHERE */
var embedMarkup = this.$el.children();
var isResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
if (isResizable) {
var readerContent = this.$el.closest(rs.helper.READER_CONTENT);
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.contentDimensions, rs.helper.getReaderTitleHeight(readerContent));
var availableHeight = contentSize.scrollableHeight - rs.helper.getHeaderPaddingBottom();
}
else if (this.marginBottomNeeded) {
var extract = this.$el.parent();
var availableHeight = co.reader.getAvailableHeight(this.sandbox, extract, this.defaultMarginBottom) - rs.helper.getHeaderPaddingBottom();
}
else {
var extract = this.$el.parent();
var availableHeight = co.reader.getAvailableHeight(this.sandbox, extract) - rs.helper.getHeaderPaddingBottom();
}
embedMarkup.attr('data-pin-scale-height', availableHeight - 45 - 31 - 2 * 10); //45 and 31 are respectively header and footer height in the pinterest embed
embedMarkup.attr('data-pin-scale-width', 130);
/* */
super.resize();
}
}
reader.PinterestEmbedView = PinterestEmbedView;
class ResizableEmbedView extends MediaWithNoPlaybackControlView {
constructor(sandbox, template, model, ready, pearlId, readerContext, contentDimensions) {
super(sandbox, template, model, ready, pearlId, false, false, readerContext, contentDimensions);
this.readerContext = readerContext;
this.contentDimensions = contentDimensions;
}
resize() {
var extract = this.$el.parent();
var readerContent = this.$el.closest(rs.helper.READER_CONTENT);
var isReaderResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
if (isReaderResizable && !this.contentDimensions.embedInfo.hasDetail) {
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.contentDimensions, rs.helper.getReaderTitleHeight(readerContent));
extract.height(contentSize.scrollableHeight);
var readerContentContainer = extract.closest(rs.helper.READER_CONTENT);
if (readerContentContainer.length > 0) {
readerContentContainer.addClass('magnified');
readerContentContainer.addClass('withBackground');
}
this.notifyHeight();
}
else {
super.resize();
}
}
disable() { }
}
reader.ResizableEmbedView = ResizableEmbedView;
class CodeEmbedView extends MediaWithNoPlaybackControlView {
constructor(sandbox, template, model, ready, pearlId, readerContext, contentDimensions) {
super(sandbox, template, model, ready, pearlId, false, true, readerContext, contentDimensions);
this.readerContext = readerContext;
this.contentDimensions = contentDimensions;
}
getRatio() {
return 16 / 10;
}
disable() { }
}
reader.CodeEmbedView = CodeEmbedView;
class QcmEmbedView extends MediaWithNoPlaybackControlView {
constructor(sandbox, template, model, ready, pearlId, readerContext, contentDimensions) {
super(sandbox, template, model, ready, pearlId, true, true, readerContext, contentDimensions);
this.iframeHeight = 0;
this.readerContext = readerContext;
this.contentDimensions = contentDimensions;
}
disable() { }
getIframeContentWindow() {
var iframe = this.$el.find('iframe');
if (iframe.length > 0 && iframe.get(0).contentWindow) {
return iframe.get(0).contentWindow;
}
return null;
}
// update body max size on resize
resize() {
var h = this.$el.height();
super.resize();
if (h != this.$el.height()) {
this.limitBodyHeight();
}
}
setEmbedElement() {
super.setEmbedElement();
if (this.$el.find('iframe').attr('src')) {
this.$el.find('iframe').on('load', () => {
this.preventScrollOnHashChange();
this.limitBodyHeight();
});
}
// this.updateIframeHeight();
}
limitBodyHeight() {
var cwin = this.getIframeContentWindow();
if (cwin) {
$(cwin.document).find('body').css('maxHeight', this.$el.height());
$(cwin.document).find('html').css('overflow-y', 'scroll');
}
}
preventScrollOnHashChange() {
var contentWindow = this.getIframeContentWindow();
$(contentWindow.document)
.find('a[href^=#]')
.on('click', function (event) {
event.preventDefault();
contentWindow.history.pushState({}, '', this.href);
var newEvent = new HashChangeEvent('hashchange'); //, {newURL : event.newURL, oldURL: event.oldURL});
contentWindow.dispatchEvent(newEvent);
});
}
getRatio() {
return 16 / 10;
}
}
reader.QcmEmbedView = QcmEmbedView;
class ShtmlEmbedView extends MediaWithNoPlaybackControlView {
constructor(sandbox, template, model, ready, pearlId, readerContext, contentDimensions) {
super(sandbox, template, model, ready, pearlId, true, true, readerContext, contentDimensions);
}
getRatio() {
return 1.3;
}
withLoader() {
var spinLoader = new sl.loader.SpinLoader(this.$('.spinloader'), 2 /* HUGE */, true);
spinLoader.show();
const iframe = this.$('#iframe');
iframe.css('visibility', 'hidden');
setTimeout(() => {
spinLoader.hide();
this.$('.spinloader').hide();
iframe.css('visibility', 'visible');
}, 700);
}
}
reader.ShtmlEmbedView = ShtmlEmbedView;
class GeogebraEmbedView extends MediaWithNoPlaybackControlView {
constructor(sandbox, template, model, ready, pearlId, readerContext, contentDimensions) {
super(sandbox, template, model, ready, pearlId, true, false, readerContext, contentDimensions);
this.defaultMarginBottom = 100;
this.readerContext = readerContext;
this.contentDimensions = contentDimensions;
}
resize() {
var extract = this.$el.parent();
var readerContent = this.$el.closest(rs.helper.READER_CONTENT);
var isReaderResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
if (isReaderResizable && !this.contentDimensions.embedInfo.hasDetail) {
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.contentDimensions, rs.helper.getReaderTitleHeight(readerContent));
extract.height(contentSize.scrollableHeight);
var readerContentContainer = extract.closest(rs.helper.READER_CONTENT);
if (readerContentContainer.length > 0) {
readerContentContainer.addClass('magnified');
readerContentContainer.addClass('withBackground');
}
this.notifyHeight();
}
else {
super.resize();
}
}
disable() { }
}
reader.GeogebraEmbedView = GeogebraEmbedView;
})(reader = exports.reader || (exports.reader = {}));
});
define('text!app/ui/reader/facebook/embed.html',[],function () { return '';});
///
///
define('app/ui/reader/facebook/facebook',["require", "exports", "app/external/facebooksdk", "app/ui/reader/page/embed", "app/ui/reader/page/contentsize", "app/util/whenready", "app/helper/responsive", "text!./embed.html"], function (require, exports, fb, em, cs, wr, re) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.facebook = void 0;
var facebook;
(function (facebook) {
function getTemplate() {
return require('text!./embed.html');
}
facebook.getTemplate = getTemplate;
class FacebookEmbedView extends em.reader.EmbedView {
constructor(sandbox, template, model, ready, pearlId) {
super(sandbox, template, model, ready, pearlId, false, true);
}
onAdded() {
super.onAdded();
var htmlElement = this.$el.get(0);
fb.facebook.doWhenFacebookSdkInitialized(() => FB.XFBML.parse(htmlElement));
wr.whenready.cancelAction(this.whenreadyId);
this.whenreadyId = wr.whenready.doWhenReady(() => this.isEmbedReady(), () => this.resizeAndPublishContentSize());
}
resize() {
if (this.isEmbedReady()) {
var readerWidth = re.helper.getDefaultReaderGraphicalParameters(this.sandbox).width;
var padding = re.helper.getHeaderPadding();
var width = readerWidth - 2 * padding - 1;
this.$el.find('.fb-post span').css('width', width);
this.$el.find('.fb-post iframe').css('width', width);
var height = this.getHeight();
this.$el.parent().height(height);
this.notifyHeight();
}
else {
super.resize();
}
}
isEmbedReady() {
this.logInfo();
var embed = this.$el.find('.fb-post');
var state = embed.attr('fb-xfbml-state');
return state === 'rendered';
}
logInfo() {
var embed = this.$el.find('.fb-post');
var embedHeight = embed.height();
var insideSpan = this.$el.find('.fb-post span');
var insideSpanHeight = insideSpan.height();
var insideSpanCssHeight = insideSpan.css('height');
var iframe = this.$el.find('.fb-post span iframe');
var iframeHeight = iframe.height();
var iframeCssHeight = iframe.css('height');
var state = embed.attr('fb-xfbml-state');
}
resizeAndPublishContentSize() {
this.resize();
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 9 /* FINAL_CONTENT_SIZE_CHANGED */, {
newContentDimensions: this.getEmbedContentDimensions(),
pearlId: this.model.get('pearlId'),
});
}
getEmbedContentDimensions() {
var embed = this.$el.find('.fb-post');
var height = this.getHeight();
var cd = cs.contentSize.createContentDimensions(height, embed.width(), null, false);
cd.embedInfo = {
embedInfoType: 17 /* FACEBOOK */,
};
return cd;
}
getHeight() {
var embed = this.$el.find('.fb-post');
var embedHeight = embed.height();
var bottomMargin = 30;
return embedHeight + bottomMargin;
}
}
facebook.FacebookEmbedView = FacebookEmbedView;
})(facebook = exports.facebook || (exports.facebook = {}));
});
define('text!app/ui/reader/flickr/embed.html',[],function () { return '';});
///
///
define('app/ui/reader/flickr/flickr',["require", "exports", "jquery", "text!./embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flickr = void 0;
///
///
var flickr;
(function (flickr) {
var FLICKR_PATTERN = '(http(?:s?)://(?:(?:(?:www|secure)\\.)?)flickr\\.com/photos/(?:[a-zA-Z0-9@_-]+/(?!(?!sets|collections)/)\\d+(?:/in/\\S+)?/?))';
var FLICKR_ALBUM_PATTERN = '(http(?:s?)://(?:(?:(?:www|secure)\\.)?)flickr\\.com/photos/[a-zA-Z0-9@_-]+/(?:albums|sets)/\\d+(?:/in/\\S+)?/?)';
var FLICKR_USER_PATTERN = '(http(?:s?)://(?:(?:(?:www|secure)\\.)?)flickr\\.com/photos/[a-zA-Z0-9@_-]+/$)';
var FLICKR_EMBED_SUFFIX = 'player';
function isEmbeddableFlickrURL(url) {
var flickrRegex = new RegExp(FLICKR_PATTERN, 'g');
var result = flickrRegex.exec(url);
if (result) {
return result[1];
}
else {
var flickrRegex2 = new RegExp(FLICKR_ALBUM_PATTERN, 'g');
var result2 = flickrRegex2.exec(url);
if (result2) {
return result2[1];
}
else {
var flickrRegex3 = new RegExp(FLICKR_USER_PATTERN, 'g');
var result3 = flickrRegex3.exec(url);
if (result) {
return result[1];
}
else {
return undefined;
}
}
}
}
flickr.isEmbeddableFlickrURL = isEmbeddableFlickrURL;
function getEmbedUrl(url) {
if (url.indexOf('http:') == 0) {
url = url.substring(5);
}
if (url.indexOf('/albums/') > 0) {
url = url.replace('/albums/', '/sets/');
}
if (url.indexOf('/', url.length - 1) == -1) {
return url + '/' + FLICKR_EMBED_SUFFIX;
}
return url + FLICKR_EMBED_SUFFIX;
}
flickr.getEmbedUrl = getEmbedUrl;
function getTemplate() {
return require('text!./embed.html');
}
flickr.getTemplate = getTemplate;
})(flickr = exports.flickr || (exports.flickr = {}));
});
///
define('app/ui/reader/mediaplayer/plyr',["require", "exports", "browserdetect"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.plyr = void 0;
var plyr;
(function (plyr) {
plyr.isNewPlayer = BrowserDetect.browser == 'Firefox' ||
BrowserDetect.browser == 'Chrome' ||
BrowserDetect.browser == 'Safari' ||
BrowserDetect.browser == 'Edge';
})(plyr = exports.plyr || (exports.plyr = {}));
});
define('text!app/ui/reader/mediaplayer/playeraudio.html',[],function () { return '';});
define('text!app/ui/reader/mediaplayer/playervideo.html',[],function () { return '';});
define('text!app/ui/reader/mediaplayer/oldplayeraudio.html',[],function () { return '';});
define('text!app/ui/reader/mediaplayer/oldplayervideo.html',[],function () { return '';});
define('bower_components/require-css/css!vendor/plyr/plyr',[],function(){});
///
///
///
///
///
define('app/ui/reader/mediaplayer/mediaplayer',["require", "exports", "app/helper/urlhelper", "app/ui/reader/page/contentsize", "./plyr", "browserdetect", "text!app/ui/reader/mediaplayer/playeraudio.html", "text!app/ui/reader/mediaplayer/playervideo.html", "text!app/ui/reader/mediaplayer/oldplayeraudio.html", "text!app/ui/reader/mediaplayer/oldplayervideo.html", "css!vendor/plyr/plyr.css"], function (require, exports, uh, cs, pl) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mediaPlayer = void 0;
var mediaPlayer;
(function (mediaPlayer) {
mediaPlayer.isNewPlayer = pl.plyr.isNewPlayer;
function getVideoTemplate() {
return require(mediaPlayer.isNewPlayer ? 'text!app/ui/reader/mediaplayer/playervideo.html' : 'text!app/ui/reader/mediaplayer/oldplayervideo.html');
}
mediaPlayer.getVideoTemplate = getVideoTemplate;
function getAudioTemplate() {
return require(mediaPlayer.isNewPlayer ? 'text!app/ui/reader/mediaplayer/playeraudio.html' : 'text!app/ui/reader/mediaplayer/oldplayeraudio.html');
}
mediaPlayer.getAudioTemplate = getAudioTemplate;
function isIE() {
return BrowserDetect.browser === 'Explorer' ? true : false;
}
mediaPlayer.isIE = isIE;
function createPlayer(el, embedId, medialUrl, mediaPoster, type, isAudio, callback) {
if (mediaPlayer.isNewPlayer) {
if (isAudio) {
var controls = `
`;
var player = new Plyr(el, {
controls,
});
player.on('loadeddata', () => {
$(el).show();
});
$(el).show();
callback(player);
}
else {
var player = new Plyr(el, {
controls: ['play-large', 'play', 'progress', 'current-time', 'duration', 'mute', 'volume', 'fullscreen'],
});
$(el).show();
player.on('loadeddata', () => {
$(el).show();
});
callback(player);
}
}
else {
jwplayer.key = 'SQEP3N+ScfTIQdiSh8gXXPJ5uRqJwCTHL5khDg==';
jwplayer(embedId).setup({
flashplayer: uh.urlhelper.getStaticContentUrl() + 'v2/vendor/jwplayer/jwplayer.flash.swf',
file: medialUrl,
width: '100%',
height: '100%',
type: type,
preload: 'none',
abouttext: 'Pearltrees',
aboutlink: window.location,
skin: {
name: 'bekle',
},
});
jwplayer(embedId).on('ready', function () {
callback(this);
});
}
}
mediaPlayer.createPlayer = createPlayer;
function getMimeTypeFromExtension(fileExtension) {
return cs.contentSize.getMimeTypeFromExtension(fileExtension);
}
mediaPlayer.getMimeTypeFromExtension = getMimeTypeFromExtension;
function getTypeFromExtension(fileExtension) {
return cs.contentSize.getTypeFromExtension(fileExtension);
}
mediaPlayer.getTypeFromExtension = getTypeFromExtension;
function canPlayMediaType(mediaType) {
return cs.contentSize.canPlayMediaType(mediaType);
}
mediaPlayer.canPlayMediaType = canPlayMediaType;
class MediaPlayer {
static getVideoPoster() {
return uh.urlhelper.getAssetUrl('images/file/video/' + MediaPlayer.DEFAULT_POSTER_VIDEO);
}
static getAudioPoster() {
return uh.urlhelper.getAssetUrl('images/file/audio/' + MediaPlayer.DEFAULT_POSTER_AUDIO);
}
static doWhenMediaPlayerIsLoaded(callback) {
MediaPlayer.loadMediaPlayer(callback);
}
static loadMediaPlayer(callback) {
require([mediaPlayer.isNewPlayer ? 'plyr' : 'jwplayer'], (player) => {
if (!mediaPlayer.isNewPlayer) {
window.jwplayer = player;
}
callback(player);
});
}
}
MediaPlayer.DEFAULT_POSTER_VIDEO = 'thumb-video-mediaplayer.png';
MediaPlayer.DEFAULT_POSTER_AUDIO = 'thumb-audio-mediaplayer.png';
mediaPlayer.MediaPlayer = MediaPlayer;
})(mediaPlayer = exports.mediaPlayer || (exports.mediaPlayer = {}));
});
///
///
///
define('app/ui/reader/page/cursorsaver',["require", "exports", "jquery", "marionette", "underscore"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cursorSaver = void 0;
///
///
///
var cursorSaver;
(function (cursorSaver) {
class CursorSaver {
constructor(isForEditor) {
this.isForEditor = isForEditor;
}
getScreenYForReader(y, $scrap) {
var titleHeight = $scrap.closest('.reader-content').find('.header').height();
var paddingTop = parseFloat($scrap.closest('.nano-content').css('padding-top'));
return y - 7;
}
getScreenYForEditor(y, $scrap) {
var titleHeight = $scrap.closest('.reader-content').find('.header').height();
var paddingTop = parseFloat($scrap.closest('.nano-content').css('padding-top'));
return y;
}
getScrollForReader($editor, $target, cursorPos) {
var titleHeight = $editor.closest('.reader-content').find('.header').height();
var screenHeight = $editor.closest('.nano-content').height();
var scroll = $target.offset().top + cursorPos.screenY + 7 - screenHeight / 2;
return scroll <= titleHeight ? 0 : scroll;
}
getScrollForEditor($editor, $target, cursorPos) {
//var titleHeight = $editor.closest(".reader-content").find(".header").height();
//var paddingTop: number = parseFloat($editor.closest(".nano-content").css("padding-top"));
//return $target.offset().top - cursorPos.screenY + titleHeight + paddingTop + cursorPos.ratioInPara * $target.closest(this.getMainScrapSelector() + " > *").height();
var screenHeight = $editor.height();
return $target.offset().top + cursorPos.screenY - screenHeight / 2;
}
computeFromMiddleScreenReader($scrollContainer, $scrapContainer) {
var editorHeight = $scrapContainer.closest('.reader').height();
var scroll = $scrollContainer.scrollTop();
var middleEditor = scroll + editorHeight / 2;
var $scrapChild = $scrapContainer.find(this.getMainScrapSelector() + ' > *');
var target = null;
var offsetTarget = 0;
var foundTarget = false;
$scrapChild.each((index, elem) => {
var $elem = $(elem);
var offset = $elem.offset().top;
var height = $elem.height();
if (offset <= middleEditor && middleEditor <= offset + height) {
target = $elem;
offsetTarget = offset;
foundTarget = true;
}
else if (!target || (!foundTarget && Math.abs(middleEditor - offset) <= Math.abs(middleEditor - offsetTarget))) {
target = $elem;
offsetTarget = offset;
}
});
if (target) {
var pos = this.computeFromElement(target);
if (pos) {
pos.screenY = middleEditor - offsetTarget;
}
return pos;
}
}
computeFromElement($target) {
var clickPos = null;
var $scrap = $target.closest(this.isForEditor ? 'body' : '.scrap-selection-container');
var targetText = $target.text();
var targetWords = this.inWords(targetText);
if (targetText && targetWords.length >= 1) {
clickPos = this.computeTargetPos($scrap, $target);
}
else {
var $nextTarget = $target.closest(this.isForEditor ? 'body > *' : '.scrap-selection-container > *');
var $previous = $nextTarget.prev();
var $next = $nextTarget.next();
var offset = 1;
var testIfValid = ($el) => {
var nextTargetText = $el.text();
var nextTargetWords = this.inWords(nextTargetText);
return !($el.length == 0) && nextTargetText && nextTargetWords.length >= 1;
};
if (testIfValid($nextTarget)) {
clickPos = this.computeTargetPos($scrap, $nextTarget);
}
else {
var count = 0;
while (count <= 10000 && ($previous.length > 0 || $next.length > 0) && !testIfValid($previous) && !testIfValid($next)) {
$previous = $previous.prev();
$next = $next.next();
offset++;
count++;
}
if (testIfValid($next)) {
clickPos = this.computeTargetPos($scrap, $next);
clickPos.offset = offset;
}
else if (testIfValid($previous)) {
clickPos = this.computeTargetPos($scrap, $previous);
clickPos.offset = -offset;
}
}
}
return clickPos;
}
getMainScrapSelector() {
return this.isForEditor ? 'body' : '.scrap-selection-container';
}
equals(a, compareTo) {
if (!compareTo || a.length != compareTo.length) {
return false;
}
for (var i = 0; i < a.length; ++i) {
if (a[i] !== compareTo[i]) {
return false;
}
}
return true;
}
computeFromCursor(event) {
var clickPos = null;
if (event.target) {
var target = event.target;
var $target = $(target);
var ratioToDiv = 0;
if ($target.is(this.getMainScrapSelector())) {
var child = null;
var offset = 0;
$target.children().each((index, elem) => {
var cChild = $(elem);
if (cChild.length == 0) {
return;
}
var v1 = cChild.get(0).offsetTop - event.offsetY;
var v2 = cChild.get(0).offsetTop + cChild.height() - event.offsetY;
var cOff = Math.abs(v1) <= Math.abs(v2) ? v1 : v2;
if (!child) {
child = cChild;
offset = cOff;
}
else if (Math.abs(cOff) <= Math.abs(offset)) {
child = cChild;
offset = cOff;
}
});
if (child) {
$target = child;
ratioToDiv = offset < 0 ? 1 : 0;
}
}
var $scrap = $target.closest(this.getMainScrapSelector());
clickPos = this.computeFromElement($target);
if (clickPos.offset != 0) {
ratioToDiv = offset < 0 ? 1 : 0;
}
else if (this.equals($(target), $target)) {
var $parent = $target;
var offset = event.offsetY;
var count = 0;
while (!$parent.is(this.getMainScrapSelector() + ' > *') && count <= 1000) {
offset += $parent.get(0).offsetTop;
$parent = $parent.parent();
count++;
}
ratioToDiv = Math.max(Math.min(1, offset / $parent.height()));
}
clickPos.screenY = this.isForEditor
? this.getScreenYForEditor(event.clientY, $scrap)
: this.getScreenYForReader(event.clientY, $scrap);
clickPos.ratioInPara = ratioToDiv;
}
return clickPos;
}
computeTargetPos($scrap, $target) {
var targetText = $target.text();
var targetWords = this.inWords(targetText);
var targetPos;
var info = this.searchForString($scrap, $target, targetText);
targetPos = {
target: targetText,
index: info.index,
};
var fullTextSplit = $scrap.text().split(targetText);
var wordsPositions = [];
var findLastPost = (word) => {
var wordPos = null;
_.each(wordsPositions, (cPos) => {
if (cPos.target == word) {
wordPos = cPos;
}
});
return wordPos;
};
var countWord = (word) => {
var lastPos = findLastPost(word);
if (lastPos) {
return lastPos.index + 1;
}
var count = 0;
for (var i = 0; i < fullTextSplit.length; i++) {
if (i >= info.index) {
break;
}
count += this.countWordInString(word, fullTextSplit[i]);
if (i > 0) {
count += this.countWordInString(word, targetText);
}
}
return count + 1;
};
_.each(targetWords, (word) => {
var index = countWord(word);
wordsPositions.push({
target: word,
index: index,
});
});
var pos = {
fullString: targetPos,
wordPositions: wordsPositions,
offset: 0,
screenY: 0,
ratioInPara: 0,
};
return pos;
}
countWordInString(word, text) {
var words = this.inWords(text);
var count = 0;
_.each(words, (tWord) => {
if (tWord == word) {
count++;
}
});
return count;
}
inWords(words) {
var n = words.split(/[\s,]+/);
return n;
}
searchForString($el, $target, str) {
var count = 0;
var index = null;
var equals = (a, compareTo) => {
if (!compareTo || a.length != compareTo.length) {
return false;
}
for (var i = 0; i < a.length; ++i) {
if (a[i] !== compareTo[i]) {
return false;
}
}
return true;
};
var searchForStringInternal = ($elInternal, alreadyCounted) => {
var hasCounted = false;
if ($elInternal.text() == str && !alreadyCounted) {
count++;
hasCounted = true;
}
if (equals($elInternal, $target)) {
index = count;
}
$elInternal.children().each((indexChild, child) => {
searchForStringInternal($(child), hasCounted);
});
};
searchForStringInternal($el, false);
return {
count: count,
index: index,
};
}
computeHTMLElementFromPosition($scrap, cursorPos) {
if (!cursorPos) {
return null;
}
var target = null;
var searchForStringInternal = ($elInternal, str, count, index, alreadyCounted) => {
var hasCounted = false;
var countInternal = 0;
if ($elInternal.text() == str && !alreadyCounted) {
countInternal++;
hasCounted = true;
}
if ($elInternal.text() == str && count + countInternal == index) {
target = $elInternal;
}
$elInternal.children().each((indexChild, child) => {
countInternal += searchForStringInternal($(child), str, count + countInternal, index, hasCounted);
});
return countInternal;
};
searchForStringInternal($scrap, cursorPos.fullString.target, 0, cursorPos.fullString.index, false);
var searchForWordInternal = ($elInternal, word, count, index) => {
var hasCounted = false;
var wordCountInElement = 0;
var countInternal = 0;
var result = null;
if ($elInternal.contents().length == 0) {
wordCountInElement = this.countWordInString(word, $elInternal.text());
}
if (count <= index && index <= count + wordCountInElement && wordCountInElement > 0) {
result = $elInternal;
}
countInternal += wordCountInElement;
$elInternal.contents().each((indexChild, child) => {
var childResult = searchForWordInternal($(child), word, count + countInternal, index);
countInternal += childResult.count;
if (!result && childResult.element) {
result = childResult.element;
}
});
return {
count: countInternal,
element: result,
};
};
var equals = (a, compareTo) => {
if (!compareTo || a.length != compareTo.length) {
return false;
}
for (var i = 0; i < a.length; ++i) {
if (a[i] !== compareTo[i]) {
return false;
}
}
return true;
};
var elements = [];
_.each(cursorPos.wordPositions, (word) => {
var result = searchForWordInternal($scrap, word.target, 0, word.index);
if (result && result.element) {
if (!elements || elements.length == 0) {
elements.push({
element: result.element,
count: 1,
});
}
else {
var newElement = null;
_.each(elements, (el) => {
if (equals(el.element, result.element)) {
el.count++;
}
else {
newElement = {
element: result.element,
count: 1,
};
}
});
if (newElement) {
elements.push(newElement);
}
}
}
});
var bestGuessWords = null;
_.each(elements, (el) => {
if (!bestGuessWords) {
bestGuessWords = el;
}
else if (bestGuessWords.count <= el.count) {
bestGuessWords = el;
}
});
/* if (target) {
target.css("background-color", "red");
}
if (bestGuessWords) {
bestGuessWords.element.closest((this.isForEditor ? "body" : ".scrap-selection-container") + " > *").css("color", "blue");
} */
var finalResult = null;
if (target) {
finalResult = target;
}
else if (bestGuessWords) {
finalResult = bestGuessWords.element.closest((this.isForEditor ? 'body' : '.scrap-selection-container') + ' > *');
}
if (finalResult && cursorPos.offset != 0) {
finalResult = finalResult.closest((this.isForEditor ? 'body' : '.scrap-selection-container') + ' > *');
var curOffset = 0;
if (cursorPos.offset > 0) {
var $previous = finalResult;
var count = 0;
while (curOffset != cursorPos.offset && $previous.length > 0 && count <= 10000) {
$previous = $previous.prev();
if ($previous.contents().length > 0) {
curOffset++;
}
count++;
}
finalResult = $previous;
}
else {
var $next = finalResult;
var count = 0;
while (curOffset != cursorPos.offset && $next.length > 0 && count <= 10000) {
$next = $next.next();
if ($next.contents().length > 0) {
curOffset--;
}
count++;
}
finalResult = $next;
}
//finalResult.css("border", "1px solid green");
}
return finalResult;
}
}
cursorSaver.CursorSaver = CursorSaver;
})(cursorSaver = exports.cursorSaver || (exports.cursorSaver = {}));
});
///
///
///
///
///
///
define('app/ui/reader/page/scrap',["require", "exports", "app/core/stats/abtest/abtesthelper", "app/ui/reader/common", "app/ui/reader/animations/animationhelper", "app/ui/reader/readeraccelerator/readeraccelerator", "app/helper/responsive", "app/util/scrollbar/scrollbar", "app/util/domutil", "app/core/stats/pageview/track/actiontracker", "app/ui/reader/page/contentsize", "app/ui/values", "app/helper/urlhelper", "app/helper/imagecontent", "app/ui/values", "jquerydotdotdot", "i18n!../../../../locales"], function (require, exports, ab, rcm, ah, ra, rs, sb, du, at, cs, va, uh, ic, val) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.page = void 0;
var page;
(function (page) {
var i18next = require('i18next');
var MIN_HEIGHT_FOR_SCRAP = 600;
let ActionType;
(function (ActionType) {
ActionType[ActionType["PEARL_CONTENT"] = 0] = "PEARL_CONTENT";
ActionType[ActionType["OR"] = 1] = "OR";
ActionType[ActionType["HASH"] = 2] = "HASH";
ActionType[ActionType["SCRAP"] = 3] = "SCRAP";
})(ActionType = page.ActionType || (page.ActionType = {}));
class ScrapView extends Marionette.ItemView {
constructor(sandbox, hasHeaderView, pearlId, readerInfo, ready, isBelowEmbed, readerContext, contentDimensions, onScrapClicked, temporaryImageUrl) {
super({
model: new ScrapModel(sandbox, pearlId, readerInfo.urlId, isBelowEmbed),
className: 'scrap',
template: require('text!./scrap.html'),
events: {
'click span .link': 'onClickAnchor',
click: 'onClickScrap',
'click .link': 'stopPropagation',
'click .no-click-zone': 'stopPropagation',
'click .scrap-separator': 'stopPropagation',
mousedown: 'updateSelectionState',
},
modelEvents: {
change: 'render',
},
});
this.waitForImages = false;
this.hasSelectedText = false;
this.sandbox = sandbox;
this.containerView = hasHeaderView;
this.initialImageUrl = temporaryImageUrl;
this.readerInfo = readerInfo;
this.ui = {
contentContainer: '.scrap-text-container',
textContainer: '.scrap-selection-container',
noClickZone: '.no-click-zone',
scrapSeparator: '.scrap-separator',
};
this.ready = ready;
this.cropDetail = readerInfo.detailInfo.shouldCropDetail == 1 && this.sandbox.isAnonymousDesktop();
this.onClick = readerInfo.onClick;
this.onScrapClicked = onScrapClicked;
this.isBelowEmbed = isBelowEmbed;
this.readerContext = readerContext;
this.contentDimensions = contentDimensions;
this.pearlId = pearlId;
this.pearlTitle = readerInfo.title;
this.pearlType = readerInfo.onClick && readerInfo.onClick.pearlReaderType;
this.subscribeId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 8 /* RESIZE_CONTENT */, (ev) => {
if (ev.id == this.pearlId) {
this.resize();
}
}, this);
}
onRender() {
$('.annotation').attr('alt', 'annotation_' + this.subscribeId);
this.ui.textContainer.hide();
this.ui.noClickZone.hide();
this.ui.scrapSeparator.hide();
//var isReaderResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
//if (isReaderResizable) {
// var readerContentContainer: JQuery = this.$el.closest(rs.helper.READER_CONTENT);
// if (readerContentContainer) {
// readerContentContainer.addClass("magnified");
// }
//}
if (this.isBelowEmbed) {
this.$el.css('marginTop', 20 + 'px');
this.$el.addClass('bellowEmbed');
}
var scrap = this.model.get('scrap');
if (scrap) {
//seo
du.DomUtil.hideLinksHref(this.ui.textContainer, true, () => {
at.actiontracker.trackAction({
fromPlace: 7 /* READER_MAP */,
toPlace: 16 /* OUT_OF_APP */,
supposedEventType: [0 /* MOUSE_DOWN */],
additionalUrl: '?t=scraplinkclicked',
}, this.sandbox);
});
this.waitForImages = true;
var timeoutId = setTimeout(() => {
this.waitForImages = false;
this.onImagesLoaded();
}, 2000);
var that = this;
this.ui.textContainer.waitForImages({
finished: () => {
clearTimeout(timeoutId);
this.onImagesLoaded();
},
each: function (loaded, count, success) {
//NN this must be a javascript function and not a typescript one.
if (!success) {
$(this).css('display', 'none');
}
else {
that.notifyNewHeight(true);
}
},
});
}
}
giveTemporaryInitialImageIfNeeded() {
if (this.readerInfo.rights.canLaunchImageEditor == 5 /* NOT_READY */ && this.initialImageUrl) {
const key = 'img[id="' + val.tag.ptPearlContentImage + '"]';
var $pearlContent = $(key, this.ui.textContainer); // you could have a copy of your pearlcontent image
$pearlContent.attr('src', this.initialImageUrl);
}
}
onImagesLoaded() {
if (!this.isClosed) {
this.waitForImages = false;
this.ui.textContainer.find('img').attr('alt', 'img_scrap' + this.subscribeId);
this.giveTemporaryInitialImageIfNeeded();
this.resetLegacyHeight();
this.resizeBefore();
this.ui.textContainer.show();
this.resize('onImagesLoaded');
this.displaySeparatorIfNeeded();
this.cleanEmptyParagraph();
this.notifyNewHeight();
this.ready();
}
else {
}
}
cleanEmptyParagraph() {
this.$el.find('p').each(function (i, el) {
if ($(el).html().trim().length == 0) {
$(el).remove();
}
});
}
resetLegacyHeight() {
var extract = this.$el.parent();
extract.css('height', 'auto');
}
onAdded() {
this.resize('on Scrap Added');
}
resizeBefore() {
if (this.ui.textContainer) {
if (rs.helper.isMobilePhoneReader()) {
this.ui.textContainer.addClass('scrap-small');
}
else {
this.ui.textContainer.removeClass('scrap-small');
}
}
}
resize(log) {
if (this.$el) {
var isReaderResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
this.resizeBefore();
var padding = isReaderResizable ? 40 : rs.helper.adaptDimensionsToDevice(5, 15);
if (this.hasBanner && (!this.cropDetail || this.isBelowEmbed || rs.helper.isMobilePhoneReader())) {
padding = 80;
}
this.ui.textContainer.css('padding-bottom', padding);
if (this.model.isLoaded()) {
if (!this.isBelowEmbed) {
var extract = this.$el.parent();
if (!isReaderResizable) {
rcm.reader.fitToHeightIfNeeded(this.sandbox, extract, true);
}
if (this.cropDetail) {
this.adjustFirstImageHeightInsideScrap();
}
else {
var firstImage = this.$getFirstImage();
firstImage.removeAttr('style');
firstImage.css('width', 'initial');
if (rs.helper.isMobilePhoneReader()) {
firstImage.css('width', '100%');
}
else {
var shownImageWidth = Math.min(this.getScrapContentWidth(), 1.5 * firstImage.outerWidth());
firstImage.css('width', shownImageWidth);
}
}
this.cropTextIfNeeded(isReaderResizable, log);
}
else {
this.notifyNewHeight();
}
}
if (isReaderResizable) {
//After we finish resizing we publish the new height
var height = this.getScrapContentHeight();
if (this.cropDetail) {
height = this.$el.parent().height();
}
else {
var firstImageHeight = this.$getFirstImage().outerHeight();
if (firstImageHeight && firstImageHeight >= height - 5) {
height += 30;
}
}
this.changeContentSizeIfNeeded(height, this.getScrapContentWidth());
}
else {
this.changeContentSizeIfNeeded(this.contentDimensions.height, this.getScrapContentWidth());
}
}
}
getScrapContentHeight() {
if (this.readerInfo.contentDimensions.embedInfo.embedInfoType == 0 /* VIDEO */) {
return cs.contentSize.getResizedVideoContentSize(this.sandbox, 16 / 9).height + this.ui.contentContainer.height();
}
return this.ui.contentContainer.height();
}
getScrapContentWidth() {
return this.ui.contentContainer.width();
}
changeContentSizeIfNeeded(newHeight, newWidth) {
var newContentDimensions = this.createNewContentDimensions(newHeight, newWidth);
var contentSizeChanged = newContentDimensions.height != this.contentDimensions.height || newContentDimensions.width != this.contentDimensions.width;
if (contentSizeChanged) {
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 9 /* FINAL_CONTENT_SIZE_CHANGED */, {
newContentDimensions: newContentDimensions,
pearlId: this.pearlId,
});
}
this.contentDimensions = newContentDimensions;
}
createNewContentDimensions(contentHeight, contentWidth) {
return cs.contentSize.createContentDimensions(contentHeight, contentWidth, 0 /* DETAIL_AND_SYNTHESIS */, false);
}
disable() { }
onClose() {
this.sandbox.getEventBus().stopSubscription(this.subscribeId);
this.sandbox.getEventBus().stopSubscription(this.resizeSubscriptionId);
}
stopPropagation() {
return false;
}
onClickScrap(event) {
var _a;
var target = event.target;
var hasEncodedMediaParam = target && target.attributes['data-original-url'];
if (hasEncodedMediaParam) {
var mediaType = this.retrieveMediaParamType(target.attributes['data-original-url'].value);
if (this.isOpenableSubcontent(mediaType)) {
if (this.isNotReadyImageFromWeb(target, mediaType)) {
window.open(target.attributes['src'].value, '_blank');
}
else {
this.openSubcontentWithMediaParam(target);
}
return false;
}
}
else if (((_a = target.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase()) == 'IMG' && !target.classList.contains('annotation')) {
window.open(target.attributes['src'], '_blank');
return false;
}
var isImage = target && target.tagName && target.tagName.toLowerCase() === 'img' && !target.classList.contains('annotation');
if (this.onScrapClicked) {
if (!isImage && (this.hasSelectedText || (window.getSelection() != null && window.getSelection().toString().length != 0))) {
return false;
}
this.onScrapClicked(event);
}
else if (this.onClick.url && this.pearlType != 0 /* IMAGE */) {
rcm.reader.openUrl(this.onClick.url, this.onClick.inlined > 0);
}
return false;
}
isNotReadyImageFromWeb(target, mediaType) {
var _a, _b;
var targetUrl = target.attributes['src'].value;
var isWebImage = targetUrl && !ic.imagecontent.isLocalOrPearltreesImage(targetUrl);
return isWebImage && ((_b = (_a = this.readerInfo) === null || _a === void 0 ? void 0 : _a.rights) === null || _b === void 0 ? void 0 : _b.canLaunchImageEditor) == 5 /* NOT_READY */ && mediaType == ActionType.PEARL_CONTENT;
}
isOpenableSubcontent(mediaType) {
return (mediaType != null &&
(this.pearlType == 5 /* NOTE */ || this.pearlType == 0 /* IMAGE */ || mediaType != ActionType.PEARL_CONTENT));
}
openSubcontentWithMediaParam(target) {
window.open(uh.urlhelper.getWebsiteUrl() +
's/image/view/' +
encodeURIComponent(this.pearlTitle) +
'?p=' +
this.pearlId +
'&m=' +
target.attributes['data-original-url'].value);
}
retrieveMediaParamType(encodedMediaParam) {
const PATTERN = /(?:media|logo)%2F([a-zA-Z]+)%2F/;
const array = PATTERN.exec(encodedMediaParam);
var action = array[1];
switch (action) {
case 'pearlContent':
return ActionType.PEARL_CONTENT;
case 'or':
return ActionType.OR;
case 'hash':
return ActionType.HASH;
case 'scrap':
return ActionType.SCRAP;
default:
return null;
}
}
updateSelectionState() {
if (window.getSelection() != null && window.getSelection().toString().length != 0) {
this.hasSelectedText = true;
}
else {
this.hasSelectedText = false;
}
}
cropTextIfNeeded(isReaderResizable, log) {
if (this.cropDetail && this.$el && this.model.get('scrap')) {
this.$el.toggleClass('cut', true);
var textContainer = this.ui.textContainer;
if (textContainer && textContainer.height && textContainer.height() > 0) {
this.ui.textContainer.remove('.ellipsis');
var extract = this.$el.parent();
var availHeight = rcm.reader.getAvailableHeight(this.sandbox, extract);
var heightToResize = availHeight - 45; //space needed for ellipsis
extract.css({ 'max-height': availHeight, overflow: 'hidden' });
if (rs.helper.isMobilePhoneReader()) {
heightToResize = heightToResize * 2;
if (heightToResize < MIN_HEIGHT_FOR_SCRAP) {
heightToResize = MIN_HEIGHT_FOR_SCRAP;
}
}
else if (!isReaderResizable) {
rcm.reader.fitToHeight(this.sandbox, extract);
}
if (this.$getFirstImage() && this.$getFirstImage().length > 0) {
var storedWidthCss = this.$getFirstImage().get(0).style.width;
var storedHeightCss = this.$getFirstImage().get(0).style.height;
this.$getFirstImage().css('width', this.$getFirstImage().width()).css('height', this.$getFirstImage().height());
}
textContainer.dotdotdot({
height: heightToResize,
callback: () => {
this.appendEllipsis();
textContainer.change(() => {
this.cropTextIfNeeded(isReaderResizable, ' textContainer changed');
});
this.notifyNewHeight();
},
});
this.$getFirstImage().css('width', storedWidthCss).css('height', storedHeightCss);
}
}
else {
this.notifyNewHeight();
}
}
notifyNewHeight(dontClearScroll) {
var $scrollContainer = this.$el.closest('.nano-content').children();
if (ab.abTestHelper.get(this.sandbox).hasRightCol()) {
var height = $scrollContainer.outerHeight(true);
var publishNewHeight = {
height: height,
type: 1 /* READER */,
scroller: this.$el.closest('.reader').children(),
dontClearScroll: dontClearScroll,
};
this.sandbox.getEventBus().publish(37 /* SCROLLER_CATCHER_CHANNEL */, 0 /* NEW_HEIGHT */, publishNewHeight);
}
else {
var $scrollContainer = this.$el.closest('.has-scrollbar');
sb.scrollbar.refreshScrollbar($scrollContainer);
}
}
$getFirstImage() {
var result = this.$el.find('#ptSynthesisImg');
if (result.length == 0) {
result = this.$el.find('.ptSynthesisImg');
}
return result;
}
isFirstImageWrapped() {
var result = this.$el.find('.wrapped');
return result.length > 0;
}
appendEllipsis() {
this.ui.textContainer.append(ScrapView.getEllipsis());
}
static getEllipsis() {
var readmoreText = i18next.t('app.readmore.reader');
var result = '' + readmoreText + '';
return result;
}
adjustFirstImageHeightInsideScrap() {
// for handsets, we don't want to resize the first image (same behavior on iphone)
var header = this.containerView.getHeaderRegion();
var param = {
useDefaultReader: false,
headerHeight: header.$el.height(),
contentDimensions: this.contentDimensions,
};
if (!rs.helper.isMobilePhoneReader()) {
ah.animation.getReaderSizeAndAbsolutePosition(this.sandbox, param, (readerPosition) => {
var header = this.containerView.getHeaderRegion();
var headerHeight = header.$el.height();
if (this.cropDetail) {
this.adjustFirstImageHeightInsideScrapInternal(readerPosition.height, headerHeight);
}
});
}
}
// at least a few lines of the scrap should be visible, so we resize the first image if needed
adjustFirstImageHeightInsideScrapInternal(readerHeight, headerHeight) {
var $synthesisImage = this.$getFirstImage();
if ($synthesisImage.length > 0) {
if (!$synthesisImage.hasClass('wrapped')) {
var isThumbshot = false;
var $resizeableElement = $synthesisImage;
if ($synthesisImage.hasClass('meaningless')) {
// thumbshots
var parentP = $synthesisImage.parent('p');
if (parentP) {
isThumbshot = true;
$resizeableElement = parentP;
}
}
var synthesisImageMaxHeight = this.getMaxHeightForSynthesis(readerHeight, headerHeight, isThumbshot);
$synthesisImage.removeAttr('style');
$resizeableElement.removeAttr('style'); // allows to measure the size the image would take if we didn't constrain it
var currentWidth = $synthesisImage.width();
var currentHeight = $synthesisImage.height();
var ratio = currentWidth / currentHeight;
if (currentHeight > synthesisImageMaxHeight) {
if (!isThumbshot) {
// image
var maxWidth = this.ui.textContainer.width();
var constrainedRatio = Math.min(maxWidth / currentWidth, synthesisImageMaxHeight / currentHeight);
$synthesisImage.css('height', currentHeight * constrainedRatio + 'px');
$synthesisImage.css('width', currentWidth * constrainedRatio + 'px');
}
else {
// thumbshot
$resizeableElement.css('max-height', synthesisImageMaxHeight + 'px');
$resizeableElement.css('overflow', 'hidden');
$synthesisImage.css('max-width', '100%');
var $border = $resizeableElement.find('.bottom-border');
if (!$border.length) {
$resizeableElement.css('position', 'relative');
$resizeableElement.append($(''));
}
}
}
}
else {
$synthesisImage.removeAttr('style');
$synthesisImage.parent().toggleClass('wrapped-paragraph', true);
}
}
}
getMaxHeightForSynthesis(readerHeight, headerHeight, isThumbshot) {
var result;
var height = readerHeight - headerHeight;
if (rcm.reader.hasReaderBanner(this.sandbox)) {
// additionnal space because of the reader banner
height -= va.values.READER_BANNER_MIN_TOP;
}
if (isThumbshot) {
result = 0.6 * height;
}
else {
result = 0.75 * height;
}
result = Math.round(result);
return Math.max(0, result);
}
setHasBanner(has) {
this.hasBanner = has;
}
displaySeparatorIfNeeded() {
if (!this.isBelowEmbed) {
// if (this.$getFirstImage() == null || this.$getFirstImage().length == 0) {
if (!this.isFirstImageWrapped()) {
this.ui.noClickZone.show();
var padding = rs.helper.getHeaderPadding();
var width = rs.helper.computeReaderWidthAndLeft(this.sandbox, 0, 0, 0, false).width;
this.ui.scrapSeparator.css('width', width);
this.ui.scrapSeparator.css('left', -padding);
this.ui.scrapSeparator.show();
}
}
}
}
page.ScrapView = ScrapView;
class ScrapModel extends Backbone.Model {
constructor(sandbox, pearlId, urlId, withoutFirstImage) {
super({
scrap: '',
});
this.sandbox = sandbox;
this.obtainScrap(pearlId, urlId, withoutFirstImage);
}
obtainScrap(pearlId, urlId, withoutFirstImage) {
this.isOk = false;
var startTime = new Date().getTime();
ra.readerAccelerator.getDetailForPearl(this.sandbox, pearlId, false, this.sandbox.isAnonymousMode(), withoutFirstImage, (content) => this.onScrapReceived(content), () => this.onError());
}
isLoaded() {
return this.isOk;
}
onScrapReceived(content) {
this.isOk = true;
this.set({ scrap: content });
}
onError() {
this.sandbox.logger.w('scrap not found...');
this.onScrapReceived(' ');
}
}
})(page = exports.page || (exports.page = {}));
});
define('text!app/ui/reader/page/synthesis.html',[],function () { return '';});
///
define('app/ui/reader/page/synthesis',["require", "exports", "app/ui/reader/common", "app/helper/responsive", "app/helper/urlhelper", "app/ui/reader/page/contentsize", "app/ui/reader/page/colorThief", "app/util/scrollbar/scrollbar", "app/core/stats/abtest/abtesthelper", "app/helper/responsive", "text!./synthesis.html"], function (require, exports, rcm, re, uh, cs, cf, sb, ab, rs) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.page = void 0;
var page;
(function (page) {
var BOTTOM_MARGIN_MIN = 5;
var BOTTOM_MARGIN_MAX = 20;
var IMG_MAX_SCALE_FACTOR = 2.5;
class SynthesisView extends Marionette.ItemView {
constructor(sandbox, imageUrl, pearlReaderInfo, pearlId, onClick, ready, readerContext, noWaitForImage = false) {
super({
model: new Backbone.Model({ imageUrl: imageUrl }),
className: 'synthesis-container',
template: require('text!./synthesis.html'),
events: {
'click .synthesis': 'openUrl',
},
modelEvents: {
change: 'render',
},
});
this.MINIMUM_DIMENSION_TO_ALLOW_EXTENSION = 250;
this.srcImgWidth = 0;
this.srcImgHeight = 0;
this.noWaitForImage = true;
this.showError = false;
this.ui = {
synthesis: '.synthesis',
};
this.sandbox = sandbox;
this.pearlReaderInfo = pearlReaderInfo;
this.pearlId = pearlId;
this.onClick = onClick;
this.ready = ready;
this.noWaitForImage = noWaitForImage;
this.readerContext = readerContext;
this.resizeSubscriptionId = this.sandbox.getEventBus().subscribeTo(3 /* READER_CHANNEL */, 8 /* RESIZE_CONTENT */, (ev) => {
if (ev.id == this.pearlReaderInfo.medals.pearlId) {
this.resize();
}
}, this);
}
onRender() {
var _a, _b;
this.$el.hide();
var sprite = new Image();
this.sprite = sprite;
this.ui.synthesis.attr('alt', 'img_syn' + this.srcImgHeight);
var firstImageHtmlId = (_a = this === null || this === void 0 ? void 0 : this.pearlReaderInfo) === null || _a === void 0 ? void 0 : _a.firstImageHtmlId;
if (firstImageHtmlId) {
this.ui.synthesis.attr('id', firstImageHtmlId);
}
var originalUrl = (_b = this === null || this === void 0 ? void 0 : this.pearlReaderInfo) === null || _b === void 0 ? void 0 : _b.dataOriginalUrl;
if (originalUrl) {
this.ui.synthesis.attr('data-original-url', originalUrl);
}
//var firstImageHtmlId = this?.ori?.firstImageHtmlId;
var timeoutId = setTimeout(() => {
if (sprite.height !== 0 && sprite.width !== 0) {
this.originalImageHeight = sprite.height;
this.originalImageWidth = sprite.width;
}
this.showFinalImageContent();
}, 6000);
sprite.crossOrigin = 'anonymous';
sprite.src = this.model.get('imageUrl');
this.waitForImageGetFullSize(sprite, () => {
clearTimeout(timeoutId);
this.originalImageHeight = sprite.height;
this.originalImageWidth = sprite.width;
this.showFinalImageContent();
});
sprite.onerror = () => {
clearTimeout(timeoutId);
this.tryImageLoadWithoutCORS();
};
this.checkOnClick();
// this.preventClickOnImageWhen404();
}
tryImageLoadWithoutCORS() {
var sprite = new Image();
this.sprite = sprite;
var timeoutId = setTimeout(() => {
if (sprite.height !== 0 && sprite.width !== 0) {
this.originalImageHeight = sprite.height;
this.originalImageWidth = sprite.width;
}
this.showFinalImageContent();
}, 6000);
sprite.src = this.model.get('imageUrl');
this.waitForImageGetFullSize(sprite, () => {
clearTimeout(timeoutId);
this.originalImageHeight = sprite.height;
this.originalImageWidth = sprite.width;
this.showFinalImageContent();
});
sprite.onerror = () => {
this.showError = true;
var fallbackImgSrc = uh.urlhelper.getAssetUrl('images/file/default/thumb-square.jpg');
this.$el.find('.synthesis').attr('src', fallbackImgSrc);
sprite.src = fallbackImgSrc;
};
}
getBackgroundColor(sprite) {
if (!this.sandbox.isMobile() && !this.sandbox.isEmbedMode() && sprite) {
var color = cf.ColorThief.getColor(sprite, 10);
if (color) {
var colorRGB = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
this.$el.css('background-color', colorRGB);
}
}
}
getOriginalContentDimensions() {
return cs.contentSize.createContentDimensions(this.originalImageHeight, this.originalImageWidth, 2 /* SYNTHESIS_FORMATTED */, this.showError);
}
notifyNewHeight() {
var $scrollContainer = this.$el.closest('.nano-content').children();
if (ab.abTestHelper.get(this.sandbox).hasRightCol()) {
var publishNewHeight = {
height: $scrollContainer.outerHeight(true),
type: 1 /* READER */,
scroller: this.$el.closest('.reader').children(),
};
this.sandbox.getEventBus().publish(37 /* SCROLLER_CATCHER_CHANNEL */, 0 /* NEW_HEIGHT */, publishNewHeight);
}
else {
var $scrollContainer = this.$el.closest('.has-scrollbar');
sb.scrollbar.refreshScrollbar($scrollContainer);
}
}
waitForImageGetFullSize(sprite, callback) {
if (this.noWaitForImage) {
var interval = 220;
var currentHeight = 0;
var done = false;
var imageSizePoller = setInterval(() => {
var newHeight = sprite.height;
if (newHeight != currentHeight) {
currentHeight = newHeight;
}
else if (newHeight > 0) {
this.srcImgHeight = newHeight;
this.srcImgWidth = sprite.width;
callback();
done = true;
clearInterval(imageSizePoller);
}
}, interval);
setTimeout(() => {
if (!done) {
clearInterval(imageSizePoller);
callback();
done = true;
}
}, 3000);
}
else {
sprite.onerror = sprite.onload = () => {
callback();
};
}
}
waitForImageShownInBrowserToLoad(imageContainer, callback) {
imageContainer.each(function () {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function () {
callback.apply(this);
});
}
});
}
showFinalImageContent() {
var isReaderResizable = this.isReaderResizable();
this.publishContentSizeChangedIfNeeded(isReaderResizable);
this.resize();
this.$el.show();
if (isReaderResizable) {
var readerContentContainer = this.$el.closest(re.helper.READER_CONTENT);
this.waitForImageShownInBrowserToLoad(this.$el.find('.synthesis'), () => {
readerContentContainer.addClass('magnified');
});
}
this.isShown = true;
this.dispatchReady();
this.notifyNewHeight();
}
resize() {
this.resizeWithImageFullyLoaded();
this.notifyNewHeight();
}
isReaderResizable() {
return !this.showError && cs.contentSize.isReaderResizable(this.sandbox, this.getOriginalContentDimensions(), this.readerContext);
}
onAdded() {
this.isAdded = true;
}
dispatchReady() {
if (this.isShown && this.isAdded) {
this.ready();
}
}
resizeWithImageFullyLoaded() {
var isReaderResizable = !this.showError && cs.contentSize.isReaderResizable(this.sandbox, this.getOriginalContentDimensions(), this.readerContext);
if (!isReaderResizable) {
var extract = this.$el.parent();
rcm.reader.fitToHeight(this.sandbox, extract, this.getBottomMargin());
}
this.resizeImageOrError(isReaderResizable);
}
resizeImageOrError(isReaderResizable) {
var isReaderResizable = !this.showError && cs.contentSize.isReaderResizable(this.sandbox, this.getOriginalContentDimensions(), this.readerContext);
if (this.showError) {
this.$el.find('.synthesis').css({ width: '100%', height: 'auto', 'max-height': 'none' });
this.$el.css({ overflow: 'hidden' });
}
else if (!isReaderResizable) {
this.extendImageIfNeeded();
var readerContentContainer = this.$el.closest(re.helper.READER_CONTENT);
if (readerContentContainer && readerContentContainer.length > 0) {
readerContentContainer.addClass('default');
}
}
else {
var extract = this.$el.parent();
extract.css('height', 'auto');
var readerContentContainer = this.$el.closest(re.helper.READER_CONTENT);
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.getOriginalContentDimensions(), rs.helper.getReaderTitleHeight(readerContentContainer));
if (contentSize && readerContentContainer && readerContentContainer.length > 0) {
var synthesisContainer = this.$el.closest('.synthesis-container');
synthesisContainer.css('height', contentSize.scrollableHeight);
var img = this.ui.synthesis;
img.height(contentSize.height);
img.width(contentSize.width);
img.css('left', contentSize.left);
img.css('top', contentSize.top);
// contentSize.isColorBackgroundRequired = false;
if (contentSize.isColorBackgroundRequired) {
this.getBackgroundColor(this.sprite);
}
// else {
// this.$el.css('background-color', 'black');
// }
}
}
}
publishContentSizeChangedIfNeeded(isReaderResizable) {
var contentSizeDifferentFromServerData = isReaderResizable &&
this.pearlReaderInfo.contentDimensions &&
(this.pearlReaderInfo.contentDimensions.height != this.originalImageHeight ||
this.pearlReaderInfo.contentDimensions.width != this.originalImageWidth);
var notifyContentChanged = this.showError || contentSizeDifferentFromServerData;
if (notifyContentChanged) {
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 9 /* FINAL_CONTENT_SIZE_CHANGED */, {
newContentDimensions: this.getOriginalContentDimensions(),
pearlId: this.pearlId,
});
}
}
extendImageIfNeeded() {
var img = this.$el.find('.synthesis');
var maxWidth = this.$el.width();
var maxHeight = this.$el.height();
var ratioX = 0;
var ratioY = 0;
var width = img.width();
var height = img.height();
if ((this.srcImgHeight > 0 && this.srcImgWidth > 0) || (width > 0 && height > 0)) {
if (this.srcImgHeight == 0 && this.srcImgWidth == 0) {
this.srcImgHeight = height;
this.srcImgWidth = width;
}
ratioX = maxWidth / this.srcImgWidth;
ratioY = maxHeight / this.srcImgHeight;
var maxRatio = 1;
if (ratioX > ratioY) {
if (ratioY > IMG_MAX_SCALE_FACTOR) {
maxRatio = IMG_MAX_SCALE_FACTOR / ratioY;
}
img.height(maxHeight * maxRatio);
img.width(this.srcImgWidth * ratioY * maxRatio);
}
else {
if (ratioX > IMG_MAX_SCALE_FACTOR) {
maxRatio = IMG_MAX_SCALE_FACTOR / ratioX;
}
img.width(maxWidth * maxRatio);
img.height(this.srcImgHeight * ratioX * maxRatio);
}
}
}
disable() { }
onClose() {
this.sandbox.getEventBus().stopSubscription(this.resizeSubscriptionId);
}
/** Callback of Marionette event -> it is used, do ctrl+F */
openUrl(event) {
var _a, _b, _c, _d, _e, _f;
var isTextbookPearl = (_b = (_a = this.pearlReaderInfo.medals) === null || _a === void 0 ? void 0 : _a.textbook) === null || _b === void 0 ? void 0 : _b.textbookId;
var targetElement = event.target;
if (!isTextbookPearl && ((_c = this.onClick) === null || _c === void 0 ? void 0 : _c.pearlReaderType) != 2) {
if ((_d = this.onClick) === null || _d === void 0 ? void 0 : _d.url) {
rcm.reader.openUrl(this.onClick.url, this.onClick.inlined > 0);
}
else if (((_e = this.pearlReaderInfo.rights) === null || _e === void 0 ? void 0 : _e.canLaunchImageEditor) == 5 /* NOT_READY */) {
// for not ready image from computer
window.open(uh.urlhelper.getServicesUrl() + 'media/pearlContent/' + this.pearlId, '_blank');
}
else if (((_f = this.onClick) === null || _f === void 0 ? void 0 : _f.pearlReaderType) == 5 && this.pearlReaderInfo.synthesisUrl) {
// for NOTE pearl
rcm.reader.openUrl(this.pearlReaderInfo.synthesisUrl, false);
}
}
}
getBottomMargin() {
return re.helper.adaptDimensionsToDevice(BOTTOM_MARGIN_MIN, BOTTOM_MARGIN_MAX);
}
checkOnClick() {
if (!this.onClick || !this.onClick.url) {
this.ui.synthesis.css('cursor', 'default');
}
}
preventClickOnImageWhen404() {
//NN this is not supposed to happen. I only seen this in Dev with image uploaded previously using Prod
var isImageUrlOnClick = this.onClick && this.onClick.url && this.onClick.url.indexOf('/s/pic/or/') >= 0;
if (isImageUrlOnClick) {
var testImg = new Image();
testImg.onerror = () => {
this.onClick.url = this.model.get('imageUrl');
};
testImg.src = this.onClick.url;
}
}
}
page.SynthesisView = SynthesisView;
})(page = exports.page || (exports.page = {}));
});
define('text!app/ui/reader/page/thumbshot.html',[],function () { return '';});
///
define('app/ui/reader/page/thumbshot',["require", "exports", "app/ui/reader/common", "app/helper/urlhelper", "app/helper/responsive", "app/core/stats/abtest/abtesthelper", "app/ui/reader/page/contentsize", "text!./thumbshot.html"], function (require, exports, rcm, uh, rs, ab, cs) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.page = void 0;
var page;
(function (page) {
class ThumbshotView extends Marionette.ItemView {
constructor(sandbox, imageUrl, onClick, readerContext, contentDimensions, pearlId, ready) {
super({
model: new Backbone.Model({ imageUrl: imageUrl }),
className: 'thumbshot-container',
template: require('text!./thumbshot.html'),
});
this.ui = {
thumbshot: '.thumbshot',
bottom: '.bottom-border',
};
this.sandbox = sandbox;
this.ready = ready;
this.onClick = onClick;
this.contentDimensions = contentDimensions;
this.readerContext = readerContext;
this.pearlId = pearlId;
this.resizeSubscriptionId = this.sandbox
.getEventBus()
.subscribeTo(5 /* STAGE_CHANNEL */, 0 /* SIZE_CHANGED */, () => this.resize(), this);
}
bindUIElements() {
super.bindUIElements();
if (rs.helper.isMobilePhoneReader()) {
this.ui.bottom.css('height', '2px');
}
else {
this.ui.bottom.css('height', '191px');
}
if (!this.onClick || !this.onClick.url) {
this.ui.thumbshot.css('cursor', 'default');
}
}
onRender() {
this.$el.hide();
var sprite = new Image();
this.ui.thumbshot.attr('alt', 'thumbshot_' + this.pearlId);
var timeoutId = setTimeout(() => this.resize(), 5000);
sprite.onload = () => {
this.$el.show(0, () => {
clearTimeout(timeoutId);
if (sprite.height !== 0 && sprite.width !== 0) {
this.originalImageHeight = sprite.height;
this.originalImageWidth = sprite.width;
}
this.isShown = true;
this.resize();
});
};
sprite.onerror = () => {
var fallbackImgSrc = uh.urlhelper.getAssetUrl('images/file/default/thumb-square.jpg');
this.$el.find('.thumbshot').attr('src', fallbackImgSrc);
sprite.src = fallbackImgSrc;
};
sprite.src = this.model.get('imageUrl');
if (!this.onClick || !this.onClick.url) {
this.$el.find('.thumbshot').css('cursor', 'default');
}
}
shouldCrop() {
return this.sandbox.isAnonymousDesktop();
}
changeContentSizeIfNeeded(newHeight, newWidth) {
var newContentDimensions = this.createNewContentDimensions(newHeight, newWidth);
var contentSizeChanged = newContentDimensions.height != this.contentDimensions.height || newContentDimensions.width != this.contentDimensions.width;
if (contentSizeChanged) {
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 9 /* FINAL_CONTENT_SIZE_CHANGED */, {
newContentDimensions: newContentDimensions,
pearlId: this.pearlId,
});
}
this.contentDimensions = newContentDimensions;
}
createNewContentDimensions(contentHeight, contentWidth) {
var dimensions = cs.contentSize.createContentDimensions(contentHeight, contentWidth, 1 /* SYNTHESIS_ONLY */, false);
dimensions.embedInfo = this.contentDimensions.embedInfo;
if (this.shouldCrop()) {
dimensions.width = rs.helper.getDefaultReaderGraphicalParameters(this.sandbox).width;
dimensions.height = rcm.reader.getAvailableHeight(this.sandbox, this.$el.parent());
}
return dimensions;
}
onAdded() {
this.isAdded = true;
this.resize();
}
resize() {
var isReaderResizable = cs.contentSize.isReaderResizable(this.sandbox, this.contentDimensions, this.readerContext);
var extract = this.$el.parent();
extract.toggleClass('cut', true);
if (this.ui.content && this.ui.content.css) {
var padding = rs.helper.getHeaderPadding();
this.ui.thumbshot.css('padding-left', padding + 'px');
this.ui.thumbshot.css('padding-right', padding + 'px');
}
if (!isReaderResizable) {
rcm.reader.fitToHeight(this.sandbox, extract, cs.contentSize.THUMBSHOT_BOTTOM_MARGIN);
}
else {
var readerContentContainer = this.$el.closest(rs.helper.READER_CONTENT);
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.contentDimensions, rs.helper.getReaderTitleHeight(readerContentContainer));
if (contentSize && readerContentContainer && readerContentContainer.length > 0) {
readerContentContainer.addClass('magnified');
}
if (this.originalImageWidth) {
this.changeContentSizeIfNeeded(this.originalImageHeight, this.originalImageWidth);
if (this.shouldCrop()) {
var extract = this.$el.parent();
extract.css('max-height', rcm.reader.getAvailableHeight(this.sandbox, extract));
}
}
}
this.dispatchReady();
}
disable() { }
onClose() {
this.sandbox.getEventBus().stopSubscription(this.resizeSubscriptionId);
}
dispatchReady() {
if (this.isShown && this.isAdded) {
var $scrollContainer = this.$el.closest('.nano-content').children();
if (ab.abTestHelper.get(this.sandbox).hasRightCol()) {
var height = $scrollContainer.outerHeight(true);
var publishNewHeight = {
height: height,
type: 1 /* READER */,
scroller: this.$el.closest('.reader').children(),
};
this.sandbox.getEventBus().publish(37 /* SCROLLER_CATCHER_CHANNEL */, 0 /* NEW_HEIGHT */, publishNewHeight);
}
this.ready();
}
}
}
page.ThumbshotView = ThumbshotView;
})(page = exports.page || (exports.page = {}));
});
var getAcrobatInfo = function() {
var getBrowserName = function() {
return this.name = this.name || function() {
var userAgent = navigator ? navigator.userAgent.toLowerCase() : "other";
if(userAgent.indexOf("chrome") > -1) return "chrome";
else if(userAgent.indexOf("safari") > -1) return "safari";
else if(userAgent.indexOf("msie") > -1) return "ie";
else if(userAgent.indexOf("firefox") > -1) return "firefox";
return userAgent;
}();
};
var getActiveXObject = function(name) {
try { return new ActiveXObject(name); } catch(e) {}
};
var getNavigatorPlugin = function(name) {
for(key in navigator.plugins) {
var plugin = navigator.plugins[key];
if(plugin.name == name) return plugin;
}
};
var getPDFPlugin = function() {
return this.plugin = this.plugin || function() {
if(getBrowserName() == 'ie') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
}
else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF');
}
}();
};
var isAcrobatInstalled = function() {
return !!getPDFPlugin();
};
var getAcrobatVersion = function() {
try {
var plugin = getPDFPlugin();
if(getBrowserName() == 'ie') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if(plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch(e) {
return null;
}
}
//
// The returned object
//
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
define("app/util/browserdetect/detectpdfsuport", function(){});
define('text!app/ui/reader/pdf/templateembed.html',[],function () { return '';});
define('text!app/ui/reader/pdf/template.html',[],function () { return '';});
define('bower_components/require-css/css!app/ui/reader/pdf/pdfembed',[],function(){});
///
///
define('app/ui/reader/pdf/pdfembed',["require", "exports", "app/ui/reader/common", "app/core/stats/pageview/track/actiontracker", "app/helper/responsive", "app/ui/reader/page/contentsize", "waitforimages", "app/util/browserdetect/detectpdfsuport", "text!./templateembed.html", "text!./template.html", "css!./pdfembed.css"], function (require, exports, rcm, at, re, cs) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pdfembed = void 0;
var pdfembed;
(function (pdfembed) {
var template = require('text!./template.html');
var templateEmbed = require('text!./templateembed.html');
class PdfEmbedView extends Marionette.ItemView {
constructor(pearlReaderInfo, sandbox, ready, showEmbed) {
super({
model: new Backbone.Model({
thumbshotUrl: pearlReaderInfo.synthesisUrl,
originalUrl: pearlReaderInfo.embedInfo.data,
}),
});
this.ui = _.extend(this.ui || {}, {
image: '.pdf-thumbshot-img',
});
this.$el.addClass('pdf-embed');
this.pearlReaderInfo = pearlReaderInfo;
this.sandbox = sandbox;
this.ready = ready;
this.shouldShowEmbed = showEmbed;
this.resizeSubscriptionId = this.sandbox
.getEventBus()
.subscribeTo(5 /* STAGE_CHANNEL */, 0 /* SIZE_CHANGED */, () => this.resize(), this);
}
getTemplate() {
return this.shouldShowEmbed ? templateEmbed : template;
}
onAdded() {
this.resize();
this.isAdded = true;
this.dispatchReady();
}
resize() {
this.$el.closest(re.helper.READER_CONTENT).addClass('magnified');
var extract = this.$el.parent();
extract.css('height', 'auto'); // we want file pearls synthesis representation to behave like images representation (no white space below the thumbshot)
//rcm.reader.fitToHeight(this.sandbox, extract, 0);
var readerContentContainer = this.$el.closest(re.helper.READER_CONTENT);
var contentSize = cs.contentSize.getResizedContentSize(this.sandbox, this.pearlReaderInfo.contentDimensions ? this.pearlReaderInfo.contentDimensions : {}, re.helper.getReaderTitleHeight(readerContentContainer));
if (contentSize && readerContentContainer && readerContentContainer.length > 0) {
var img = this.ui.image;
img.height(contentSize.height);
img.width(contentSize.width);
img.css('left', contentSize.left);
img.css('top', contentSize.top);
}
}
disable() { }
onRender() {
if (!this.shouldShowEmbed) {
this.$el.hide();
this.ui.image.attr('alt', 'pdf-thumbshot_' + this.resizeSubscriptionId);
this.ui.image.waitForImages({
finished: () => {
this.$el.show();
this.isShown = true;
this.dispatchReady();
},
each: (loaded, count, success) => { },
waitForAll: true,
});
}
}
onClose() {
this.sandbox.getEventBus().stopSubscription(this.resizeSubscriptionId);
}
displayOrOpenPdf() {
if (getAcrobatInfo().acrobat == 'installed') {
this.shouldShowEmbed = true;
this.render();
at.actiontracker.trackAction({
fromPlace: 7 /* READER_MAP */,
toPlace: 19 /* BROWSER_ACTION */,
supposedEventType: [0 /* MOUSE_DOWN */],
additionalUrl: '?openpdf',
}, this.sandbox);
}
else {
rcm.reader.openUrl(this.model.get('originalUrl'));
}
}
dispatchReady() {
if (this.isShown && this.isAdded) {
this.ready();
}
}
}
pdfembed.PdfEmbedView = PdfEmbedView;
})(pdfembed = exports.pdfembed || (exports.pdfembed = {}));
});
define('text!app/ui/reader/pinterest/embed.html',[],function () { return '';});
///
///
define('app/ui/reader/pinterest/pinterest',["require", "exports", "jquery", "text!./embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pinterest = void 0;
var pinterest;
(function (pinterest) {
var PINTEREST_PIN_PATTERN = 'http(?:s?)://(?:(?:(?:[A-Za-z]{2,3})\\.)?)pinterest\\.(?:com|ca|fr)/pin/\\d+/?';
var PINTEREST_PROFILE_PATTERN = 'http(?:s?)://(?:(?:(?:[A-Za-z]{2,3})\\.)?)pinterest\\.(?:com|ca|fr)/(?:(?!join|popular|login|gifts|videos|places|all|pin|explore)(\\w+)/$)';
var PINTEREST_BOARD_PATTERN = 'http(?:s?)://(?:(?:(?:[A-Za-z]{2,3})\\.)?)pinterest\\.(?:com|ca|fr)/(?!join|popular|login|gifts|videos|places|all|pin)(?:\\w+/)(\\S+)';
function getPinterestEmbedType(url) {
if (url.match(PINTEREST_PROFILE_PATTERN)) {
return 'embedUser';
}
else if (url.match(PINTEREST_BOARD_PATTERN)) {
return 'embedBoard';
}
else if (url.match(PINTEREST_PIN_PATTERN)) {
return 'embedPin';
}
return null;
}
pinterest.getPinterestEmbedType = getPinterestEmbedType;
function getTemplate() {
return require('text!./embed.html');
}
pinterest.getTemplate = getTemplate;
class EmbedPinterest {
static loadPinterestAPI(callback) {
//if (!EmbedPinterest.PINTEREST_API_ADDED) {
$.ajax({
url: '//assets.pinterest.com/js/pinit_main.js',
dataType: 'script',
success: () => {
if (callback && callback != null) {
callback();
}
},
fail: () => {
//TODO
},
});
EmbedPinterest.PINTEREST_API_ADDED = true;
//}
/*}
else {
if (!window[EmbedPinterest.PINTEREST_API_BUILD]) {
//document.addEventListener("pinitMain", () => {
console.log("pinitmain loaded");
//callback();
//});
}
else {
callback();
}
}*/
}
}
EmbedPinterest.PINTEREST_API_ADDED = false;
EmbedPinterest.PINTEREST_API_LOADED = false;
EmbedPinterest.PINTEREST_API_BUILD = 'pinterestBuild';
pinterest.EmbedPinterest = EmbedPinterest;
})(pinterest = exports.pinterest || (exports.pinterest = {}));
});
///
///
///
///
///
///
///
define('app/ui/reader/player',["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reader = void 0;
var reader;
(function (reader) {
class Player {
pause() { }
}
reader.Player = Player;
class YoutubeWrapper extends Player {
constructor(player) {
super();
this.player = player;
}
pause() {
this.player.pauseVideo();
}
}
reader.YoutubeWrapper = YoutubeWrapper;
class DailymotionWrapper extends Player {
constructor(player) {
super();
this.player = player;
}
pause() {
this.player.pause();
}
}
reader.DailymotionWrapper = DailymotionWrapper;
class VimeoWrapper extends Player {
constructor(player) {
super();
this.player = player;
}
pause() {
this.player.api('pause');
}
}
reader.VimeoWrapper = VimeoWrapper;
class SoundcloudWrapper extends Player {
constructor(player) {
super();
this.player = player;
}
pause() {
this.player.pause();
}
}
reader.SoundcloudWrapper = SoundcloudWrapper;
class FlashPlayer extends Player {
constructor(id) {
super();
this.id = id;
}
pause() {
try {
var flashObject = swfobject.getObjectById(this.id);
if (flashObject) {
flashObject.StopPlay();
}
}
catch (e) { }
}
}
reader.FlashPlayer = FlashPlayer;
class MediaElementPlayerWrapper extends Player {
constructor(player) {
super();
this.player = player;
}
pause() {
this.player.pause();
}
}
reader.MediaElementPlayerWrapper = MediaElementPlayerWrapper;
class JWPlayerWrapper extends Player {
constructor(player) {
super();
this.player = player;
}
pause() {
this.player.pause(true);
}
}
reader.JWPlayerWrapper = JWPlayerWrapper;
})(reader = exports.reader || (exports.reader = {}));
});
define('text!app/ui/reader/slideshare/embed.html',[],function () { return '';});
///
define('app/ui/reader/slideshare/slideshare',["require", "exports", "jquery", "text!./embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.slideshare = void 0;
///
///
var slideshare;
(function (slideshare) {
var SLIDESHARE_API_URL = '//www.slideshare.net/api/oembed/2';
var SLIDESHARE_PATTERN = '(http(?:s?)://(?:(?:(?:www|\\w+)\\.?)?)slideshare\\.net/(?!search|upload|terms|privacy|about|signup|login|business)\\S+/[A-Za-z0-9-_]+)';
var SLIDESHARE_EMBED_PREFIX = '//www.slideshare.net/slideshow/embed_code/';
var SLIDESHARE_EMBED_SUFFIX = '?rel=0';
function checkSlideshareEmbed(url) {
var slideshareRegex = new RegExp(SLIDESHARE_PATTERN, 'g');
var result = slideshareRegex.exec(url);
if (result) {
return result[1];
}
return undefined;
}
slideshare.checkSlideshareEmbed = checkSlideshareEmbed;
function getEmbedURL(slideshowID) {
if (slideshowID) {
return SLIDESHARE_EMBED_PREFIX + slideshowID + SLIDESHARE_EMBED_SUFFIX;
}
return SLIDESHARE_EMBED_PREFIX;
}
slideshare.getEmbedURL = getEmbedURL;
function slideshareAPIRequest(url, callback) {
/* necessary for IE8 */
$.support.cors = true;
$.ajax({
type: 'GET',
url: SLIDESHARE_API_URL,
dataType: 'jsonp',
data: {
url: url,
format: 'jsonp',
},
success: function (json) {
var slideshowID = json.slideshow_id;
callback(slideshowID);
},
error: function (jqXHR, textStatus, errorThrow) {
callback(undefined);
},
crossDomain: true,
timeout: 20000,
});
}
slideshare.slideshareAPIRequest = slideshareAPIRequest;
function getTemplate() {
return require('text!./embed.html');
}
slideshare.getTemplate = getTemplate;
})(slideshare = exports.slideshare || (exports.slideshare = {}));
});
define('text!app/ui/reader/soundcloud/embed.html',[],function () { return '';});
///
///
define('app/ui/reader/soundcloud/soundcloud',["require", "exports", "jquery", "text!./embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.soundcloud = void 0;
///
///
var soundcloud;
(function (soundcloud) {
var SOUNDCLOUD_API_URL = '//soundcloud.com/oembed';
var SOUNDCLOUD_PATTERN = '(http(?:s?)://(?:(?:www\\.)?)soundcloud\\.com/(?!stream|explore|settings|pages|terms-of-use|jobs|pro|search|login)(?![A-Za-z0-9-]+/(?:following|followers|likes|comments|groups)).+)';
var SOUNDCLOUD_API_LOADED = false;
function isValidSoundcloudURL(url) {
var soundcloudRegex = new RegExp(SOUNDCLOUD_PATTERN, 'g');
var result = soundcloudRegex.exec(url);
if (result) {
return result[1];
}
else {
return undefined;
}
}
soundcloud.isValidSoundcloudURL = isValidSoundcloudURL;
function createPlayer(element, callback) {
var widget = SC.Widget(element);
callback(widget);
}
soundcloud.createPlayer = createPlayer;
function loadSoundcloudAPI(callback) {
if (!SOUNDCLOUD_API_LOADED) {
var tag = document.createElement('script');
tag.src = '//w.soundcloud.com/player/api.js';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
tag.addEventListener('load', () => {
SOUNDCLOUD_API_LOADED = true;
callback();
});
}
else {
callback();
}
}
soundcloud.loadSoundcloudAPI = loadSoundcloudAPI;
function soundcloudAPIRequest(url, callback) {
/* necessary for IE8 */
$.support.cors = true;
$.ajax({
type: 'GET',
url: SOUNDCLOUD_API_URL,
dataType: 'jsonp',
data: {
url: url,
format: 'js',
show_comments: false,
iframe: true,
},
success: function (json) {
var embedURL = $(json.html).attr('src');
callback(embedURL);
},
error: function (jqXHR, textStatus, errorThrow) {
if (jqXHR.status == 0) {
callback('error');
}
},
crossDomain: true,
timeout: 5000,
});
}
soundcloud.soundcloudAPIRequest = soundcloudAPIRequest;
function getTemplate() {
return require('text!./embed.html');
}
soundcloud.getTemplate = getTemplate;
})(soundcloud = exports.soundcloud || (exports.soundcloud = {}));
});
define('text!app/ui/reader/ted/embed.html',[],function () { return '';});
///
define('app/ui/reader/ted/ted',["require", "exports", "jquery", "text!./embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ted = void 0;
///
///
var ted;
(function (ted) {
var TED_PATTERN = 'http(?:s?)://(?:(?:www\\.)?)ted\\.com/((?=(?:talks|playlists)(?!/browse)/?)[A-Za-z0-9/-_]+)(?:\\.html)?';
var TED_SUBTITLES = '\\/(lang\\/\\w+)\\/';
var TED_EMBED_PREFIX = '//embed.ted.com/';
var TED_EMBED_SUFFIX = '.html';
function getTedEmbedURL(url) {
var tedRegex = new RegExp(TED_PATTERN, 'g');
var result = tedRegex.exec(url);
if (result) {
var url = result[1];
if (containsSubtitleString(url)) {
return createSubtitlesUrl(url);
}
return url;
}
return undefined;
}
ted.getTedEmbedURL = getTedEmbedURL;
function containsSubtitleString(url) {
return url.match(TED_SUBTITLES);
}
ted.containsSubtitleString = containsSubtitleString;
function createSubtitlesString(langUrl) {
var sub = langUrl.split('/');
var subtitlesString = '';
if (sub) {
var langKey = sub.shift();
var tmp = sub[0].split('_');
var isoCode = tmp.pop();
subtitlesString = langKey + '/' + isoCode;
return subtitlesString;
}
return langUrl;
}
ted.createSubtitlesString = createSubtitlesString;
function createSubtitlesUrl(url) {
var subtitlesRegex = new RegExp(TED_SUBTITLES, 'g');
var result = subtitlesRegex.exec(url);
if (result) {
var subtitlesString = createSubtitlesString(result[1]);
return url.replace(result[1], subtitlesString);
}
return url;
}
ted.createSubtitlesUrl = createSubtitlesUrl;
function removeLanguageURL(url) {
return url.replace(/\/lang\/\w+\//gi, '/');
}
ted.removeLanguageURL = removeLanguageURL;
function getEmbedURL(url) {
return TED_EMBED_PREFIX + url + TED_EMBED_SUFFIX;
}
ted.getEmbedURL = getEmbedURL;
function getTemplate() {
return require('text!./embed.html');
}
ted.getTemplate = getTemplate;
})(ted = exports.ted || (exports.ted = {}));
});
define('text!app/ui/reader/theatrevideo/embed.html',[],function () { return '';});
///
define('app/ui/reader/theatrevideo/theatrevideo',["require", "exports", "jquery", "text!./embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.theatrevideo = void 0;
///
///
var theatrevideo;
(function (theatrevideo) {
var THEATREVIDEO_API_URL = '//www.theatre-video.net/oembed';
var THEATREVIDEO_PATTERN = '(http(?:s?)://(?:(?:(?:www)\\.?)?)theatre-video\\.net/video/.+)';
function isValidTheatreVideoURL(url) {
var theatrevideoRegex = new RegExp(THEATREVIDEO_PATTERN, 'g');
var result = theatrevideoRegex.exec(url);
if (result) {
return result[1];
}
else {
return undefined;
}
}
theatrevideo.isValidTheatreVideoURL = isValidTheatreVideoURL;
function theatrevideoAPIRequest(url, callback) {
/* necessary for IE8 */
$.support.cors = true;
$.ajax({
type: 'GET',
url: THEATREVIDEO_API_URL,
dataType: 'jsonp',
data: {
url: url,
format: 'jsonp',
},
success: function (json) {
var embedURL = $(json.html).attr('src');
callback(embedURL);
},
error: function (jqXHR, textStatus, errorThrow) {
callback(undefined);
},
crossDomain: true,
timeout: 20000,
});
}
theatrevideo.theatrevideoAPIRequest = theatrevideoAPIRequest;
function getTemplate() {
return require('text!./embed.html');
}
theatrevideo.getTemplate = getTemplate;
})(theatrevideo = exports.theatrevideo || (exports.theatrevideo = {}));
});
define('text!app/ui/reader/twitter/embed.html',[],function () { return '';});
///
define('app/ui/reader/twitter/twitter',["require", "exports", "app/ui/reader/page/contentsize", "app/core/stats/abtest/abtesthelper", "jquery", "text!./embed.html"], function (require, exports, cs, ab) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twitter = void 0;
var twitter;
(function (twitter) {
var TWITTER_PATTERN = 'http(?:s?)://(?:(?:www.)?)twitter.com/([a-zA-Z0-9_]+)(/status/|/timelines/|/lists/|/likes)?([a-zA-Z0-9_-]+)?';
function getTwitterId(url) {
var twitterRegex;
var result;
twitterRegex = RegExp(TWITTER_PATTERN);
result = twitterRegex.exec(url);
if (result) {
return result[3];
}
else {
return undefined;
}
}
twitter.getTwitterId = getTwitterId;
function getScreenName(url) {
var twitterRegex;
var result;
var isTimeline = EmbedTwitter.checkEmbedTwitterType(url);
if (isTimeline) {
twitterRegex = RegExp(TWITTER_PATTERN);
result = twitterRegex.exec(url);
if (result) {
return result[1];
}
}
return undefined;
}
twitter.getScreenName = getScreenName;
function getTimelineType(url) {
var twitterRegex;
var result;
var isTimeline = EmbedTwitter.checkEmbedTwitterType(url);
if (isTimeline) {
twitterRegex = RegExp(TWITTER_PATTERN);
result = twitterRegex.exec(url);
if (result) {
return result[2];
}
}
return undefined;
}
twitter.getTimelineType = getTimelineType;
function getTemplate() {
return require('text!./embed.html');
}
twitter.getTemplate = getTemplate;
class EmbedTwitter {
constructor(sb, element, url, pearlId) {
this.isTimeline = false;
this.sandbox = sb;
this.element = element;
this.$container = $(element);
this.$container.css('opacity', 0);
this.twitterId = getTwitterId(url);
this.screenName = getScreenName(url);
this.isTimeline = EmbedTwitter.checkEmbedTwitterType(url);
this.timelineType = getTimelineType(url);
this.pearlId = pearlId;
}
static checkEmbedTwitterType(url) {
if (url && url.indexOf('status') == -1 && url.indexOf('statuses') == -1) {
return true;
}
else {
return false;
}
}
static doWhenTwitterApiIsLoaded(callback) {
EmbedTwitter.loadTwitterAPI(callback);
}
static loadTwitterAPI(callback) {
var cspOnMeta = $('head').find("meta[name='twitter:widgets:csp']");
if (cspOnMeta.length == 0) {
$('head').append("");
}
require(['twitterWidget'], (twitterEmbed) => {
callback(twitterEmbed);
});
}
createTwitterEmbed() {
// TODO : unbind this callback
window['twttr'].events.bind('rendered', (event) => this.onEmbedLoaded(event));
window['twttr'].ready(() => {
if (this.isTimeline) {
EmbedTwitter.createTwitterTimeline(this.element, this.screenName, this.timelineType, this.twitterId);
}
else {
EmbedTwitter.createTwitterTweet(this.element, this.twitterId);
}
window['twttr'].widgets.load(this.element); //this is recommended to use on dynamic elements (twitter API's documentation)
});
}
static createTwitterTimeline(element, screenName, timelineType, timelineId) {
switch (timelineType) {
case undefined:
window['twttr'].widgets.createTimeline({
sourceType: 'profile',
screenName: screenName,
}, element);
break;
case '/lists/':
if (screenName != 'i') {
window['twttr'].widgets.createTimeline({
sourceType: 'list',
ownerScreenName: screenName,
slug: timelineId,
}, element);
}
else {
window['twttr'].widgets.createTimeline({
sourceType: 'list',
id: timelineId,
}, element);
}
break;
case '/timelines/':
window['twttr'].widgets.createTimeline({
sourceType: 'collection',
id: timelineId,
}, element);
break;
case '/likes':
window['twttr'].widgets.createTimeline({
sourceType: 'likes',
screenName: screenName,
}, element);
break;
}
}
static createTwitterTweet(element, tweetId) {
window['twttr'].widgets.createTweet(tweetId, element,
/* () => {
//this.onEmbedLoaded(element);
},*/
{
align: 'left',
conversation: 'none',
});
}
publishContentSizeChangedIfNeeded() {
if (this.$embed) {
var height = this.$embed.height();
if (!this.embedHeight || (this.embedHeight && this.embedHeight != height)) {
this.embedHeight = height;
var cd = cs.contentSize.createContentDimensions(height, this.$embed.width(), null, false);
cd.embedInfo = {
embedInfoType: 6 /* TWITTER */,
};
cd.isTemporary = 0;
this.sandbox.getEventBus().publish(3 /* READER_CHANNEL */, 9 /* FINAL_CONTENT_SIZE_CHANGED */, {
newContentDimensions: cd,
pearlId: this.pearlId,
});
var $scrollContainer = this.$container.closest('.nano-content').children();
if (ab.abTestHelper.get(this.sandbox).hasRightCol()) {
var publishNewHeight = {
height: $scrollContainer.outerHeight(true),
type: 1 /* READER */,
scroller: this.$container.closest('.reader').children(),
};
this.sandbox
.getEventBus()
.publish(37 /* SCROLLER_CATCHER_CHANNEL */, 0 /* NEW_HEIGHT */, publishNewHeight);
}
}
}
}
checkForEmbedHeightModification() {
this.checkForEmbedHeightModificationInternal(0);
}
checkForEmbedHeightModificationInternal(tryCount) {
tryCount++;
var oldHeight = this.embedHeight;
var height = this.$embed.height();
if (oldHeight != height) {
this.publishContentSizeChangedIfNeeded();
}
else if (tryCount <= 50) {
setTimeout(() => this.checkForEmbedHeightModificationInternal(tryCount), 100);
}
}
onEmbedLoaded(ebd) {
var isEmbedLoaded;
if (!this.isTimeline) {
isEmbedLoaded = ebd && ebd.target && ebd.target.firstChild && ebd.target.firstChild.id; //the tweet event .target.firstChild refers to the added iframe
}
else {
isEmbedLoaded = ebd && ebd.target && ebd.target.id; //the timeline event .target refers to the iframe
}
var twitterFrame = this.$container.find('iframe').first();
var isIFrameLoadaed = twitterFrame && twitterFrame.length > 0 && twitterFrame.get(0) && twitterFrame.get(0).id;
if (isEmbedLoaded && isIFrameLoadaed) {
var embeddedIframeId = this.isTimeline ? ebd.target.id : ebd.target.firstChild.id;
var isRightEmbed = embeddedIframeId == this.$container.find('iframe').first().get(0).id; //NN check right embed twitter in case plural ones are loaded simultaneously
if (!isRightEmbed) {
return;
}
var embed = this.isTimeline ? $(ebd.target.parentElement) : $(ebd.target);
if (this.isTimeline) {
embed.css('height', '100%');
}
embed.css('width', '100%');
embed.css('max-width', 'none');
embed.css('margin-top', 0);
embed.css('margin-bottom', 0);
embed.css('place-content', 'center');
//centers the tweet frame
twitterFrame.css('flex-grow', '0');
var contents = null;
try {
contents = embed.contents();
}
catch (e) {
this.$container.css({
opacity: 1,
overflow: '',
});
this.sandbox.logger.e('Twitter crash after load ' + e);
}
if (contents && contents.length) {
var head = contents.find('head');
if (head.length) {
if (!this.isTimeline) {
head.append('');
}
else {
head.append('');
}
}
this.$embed = embed;
setTimeout(() => {
this.$container.css({
opacity: 1,
overflow: '',
});
this.publishContentSizeChangedIfNeeded();
setTimeout(() => this.checkForEmbedHeightModification(), 500);
}, 500);
}
}
}
}
twitter.EmbedTwitter = EmbedTwitter;
})(twitter = exports.twitter || (exports.twitter = {}));
});
define('text!app/ui/reader/page/video.html',[],function () { return '';});
///
///
///
define('app/ui/reader/vimeo/vimeo',["require", "exports", "jquery", "text!app/ui/reader/page/video.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.vimeo = void 0;
///
///
var vimeo;
(function (vimeo) {
var VIMEO_PATTERN = 'http://vimeo\\.com/(\\d+)';
var VIMEO_EMBED_PREFIX = '//player.vimeo.com/video/';
var VIMEO_EMBED_SUFFIX = '?api=1&autopause=1&portrait=0&byline=0&badge=0&portrait=0&title=0';
var VIMEO_API_LOADING_DEFERRED;
function getVimeoVideoId(url) {
var vimeoRegex = new RegExp(VIMEO_PATTERN, 'g');
var result = vimeoRegex.exec(url);
if (result) {
return result[1];
}
else {
return undefined;
}
}
vimeo.getVimeoVideoId = getVimeoVideoId;
function getEmbedUrl(videoId) {
return VIMEO_EMBED_PREFIX + videoId + VIMEO_EMBED_SUFFIX;
}
vimeo.getEmbedUrl = getEmbedUrl;
function createPlayer(el, callback) {
var player = $f(el);
$f(el).addEvent('ready', function () {
callback(player);
});
}
vimeo.createPlayer = createPlayer;
function getTemplate() {
return require('text!app/ui/reader/page/video.html');
}
vimeo.getTemplate = getTemplate;
function doWhenVimeoApiIsLoaded(callback) {
loadVimeoAPI(callback);
}
vimeo.doWhenVimeoApiIsLoaded = doWhenVimeoApiIsLoaded;
function loadVimeoAPI(callback) {
require(['froogaloop'], (froogaloop) => {
callback(froogaloop);
});
}
vimeo.loadVimeoAPI = loadVimeoAPI;
})(vimeo = exports.vimeo || (exports.vimeo = {}));
});
define('text!app/ui/reader/vine/embed.html',[],function () { return '';});
///
///
define('app/ui/reader/vine/vine',["require", "exports", "text!app/ui/reader/vine/embed.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.vine = void 0;
///
var vine;
(function (vine) {
var VINE_PATTERN = '(http(?:s?)://(?:(?:www\\.)?)vine\\.co/v/\\w+)';
// /embed/[simple|postcard]?audio
var VINE_EMBED_SUFFIX = 'embed/simple';
function isValidVineURL(url) {
return url.match(VINE_PATTERN);
}
vine.isValidVineURL = isValidVineURL;
function getTemplate() {
return require('text!app/ui/reader/vine/embed.html');
}
vine.getTemplate = getTemplate;
function getEmbedUrl(url) {
return url + VINE_EMBED_SUFFIX;
}
vine.getEmbedUrl = getEmbedUrl;
function doWhenVineApiIsLoaded(callback) {
loadVineAPI(callback);
}
vine.doWhenVineApiIsLoaded = doWhenVineApiIsLoaded;
function loadVineAPI(callback) {
require(['vineWidget'], (apiloaded) => {
callback(apiloaded);
});
}
vine.loadVineAPI = loadVineAPI;
})(vine = exports.vine || (exports.vine = {}));
});
///
///
///
define('app/ui/reader/youtube/youtube',["require", "exports", "jquery", "browserdetect", "text!app/ui/reader/page/video.html"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.youtube = void 0;
///
///
///
var youtube;
(function (youtube) {
var YOUTUBE_PATTERN = 'http://www\\.youtube\\.com/watch\\?v=(.+)';
var YOUTUBE_WEBKIT_PREFIX = 'https:';
var YOUTUBE_EMBED_PREFIX = '//www.youtube.com/embed/';
var YOUTUBE_EMBED_SUFFIX = '?enablejsapi=1&modestbranding=1&rel=0&showinfo=0&html5=1';
// modestbranding => no youtube logo
// rel => no related video at the end
// showinfo => less ui on player
// html5 => prevent a bug with the flash player in firefox
function getYoutubeVideoId(url) {
var youtubeRegex = new RegExp(YOUTUBE_PATTERN, 'g');
var result = youtubeRegex.exec(url);
if (result) {
return result[1];
}
return undefined;
}
youtube.getYoutubeVideoId = getYoutubeVideoId;
function getEmbedUrl(videoId) {
var browser = BrowserDetect.browser;
// on chrome or safari, not using the https prefix causes this strange bug for users logged on youtube
// http://stackoverflow.com/q/20063255/982187
if (browser === 'Chrome' || browser === 'Safari') {
return YOUTUBE_WEBKIT_PREFIX + YOUTUBE_EMBED_PREFIX + videoId + YOUTUBE_EMBED_SUFFIX;
}
// on firefox using the https prefix prevents the user from using the html5 player
return YOUTUBE_EMBED_PREFIX + videoId + YOUTUBE_EMBED_SUFFIX;
}
youtube.getEmbedUrl = getEmbedUrl;
function getTemplate() {
return require('text!app/ui/reader/page/video.html');
}
youtube.getTemplate = getTemplate;
// el can be either a DOM element or a string id
function createPlayer(el, callback) {
var player = new YT.Player(el, {
events: {
onReady: (event) => {
callback(player);
},
onStateChange: (event) => { },
},
});
}
youtube.createPlayer = createPlayer;
class YoutubePlayer {
static doWhenYoutubeApiIsLoaded(callback) {
if (YoutubePlayer.YOUTUBE_API_LOADING_DEFERRED) {
YoutubePlayer.YOUTUBE_API_LOADING_DEFERRED.done(() => callback());
}
else {
YoutubePlayer.YOUTUBE_API_LOADING_DEFERRED = $.Deferred();
YoutubePlayer.YOUTUBE_API_LOADING_DEFERRED.done(() => callback());
YoutubePlayer.loadYoutubeAPI(YoutubePlayer.YOUTUBE_API_LOADING_DEFERRED);
}
}
static loadYoutubeAPI(deferred) {
window[YoutubePlayer.YOUTUBE_PLAYER_API_CALLBACK] = () => {
window[YoutubePlayer.YOUTUBE_PLAYER_API_CALLBACK] = () => { };
deferred.resolve();
};
var tag = document.createElement('script');
tag.src = '//www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
YoutubePlayer.YOUTUBE_PLAYER_API_CALLBACK = 'onYouTubeIframeAPIReady';
youtube.YoutubePlayer = YoutubePlayer;
})(youtube = exports.youtube || (exports.youtube = {}));
});
define('text!app/ui/reader/flash/flashembed.html',[],function () { return '