_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q54900
|
train
|
function (sheet, selector, rule) {
var index;
if (sheet.insertRule) {
return sheet.insertRule(selector + '{' + rule + '}', sheet.cssRules.length);
} else {
index = sheet.addRule(selector, rule, sheet.rules.length);
if (index < 0) {
index = sheet.rules.length - 1;
}
return index;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54901
|
train
|
function () {
var style,
px,
testSize = 10000,
div = document.createElement('div');
div.style.display = 'block';
div.style.position = 'absolute';
div.style.width = testSize + 'pt';
document.body.appendChild(div);
style = util.getComputedStyle(div);
if (style && style.width) {
px = parseFloat(style.width) / testSize;
} else {
// @NOTE: there is a bug in Firefox where `getComputedStyle()`
// returns null if called in a hidden (`display:none`) iframe
// (https://bugzilla.mozilla.org/show_bug.cgi?id=548397), so we
// fallback to a default value if this happens.
px = DEFAULT_PT2PX_RATIO;
}
document.body.removeChild(div);
return px;
}
|
javascript
|
{
"resource": ""
}
|
|
q54902
|
train
|
function (str, token) {
var total = 0, i;
while ((i = str.indexOf(token, i) + 1)) {
total++;
}
return total;
}
|
javascript
|
{
"resource": ""
}
|
|
q54903
|
train
|
function (template, data) {
var p;
for (p in data) {
if (data.hasOwnProperty(p)) {
template = template.replace(new RegExp('\\{\\{' + p + '\\}\\}', 'g'), data[p]);
}
}
return template;
}
|
javascript
|
{
"resource": ""
}
|
|
q54904
|
isSubpixelRenderingSupported
|
train
|
function isSubpixelRenderingSupported() {
// Test if subpixel rendering is supported
// @NOTE: jQuery.support.leadingWhitespace is apparently false if browser is IE6-8
if (!$.support.leadingWhitespace) {
return false;
} else {
//span #1 - desired font-size: 12.5px
var span = $(util.template(TEST_SPAN_TEMPLATE, { size: 12.5 }))
.appendTo(document.documentElement).get(0);
var fontsize1 = $(span).css('font-size');
var width1 = $(span).width();
$(span).remove();
//span #2 - desired font-size: 12.6px
span = $(util.template(TEST_SPAN_TEMPLATE, { size: 12.6 }))
.appendTo(document.documentElement).get(0);
var fontsize2 = $(span).css('font-size');
var width2 = $(span).width();
$(span).remove();
// is not mobile device?
// @NOTE(plai): Mobile WebKit supports subpixel rendering even though the browser fails the following tests.
// @NOTE(plai): When modifying these tests, make sure that these tests will work even when the browser zoom is changed.
// @TODO(plai): Find a better way of testing for mobile Safari.
if (!('ontouchstart' in window)) {
//font sizes are the same? (Chrome and Safari will fail this)
if (fontsize1 === fontsize2) {
return false;
}
//widths are the same? (Firefox on Windows without GPU will fail this)
if (width1 === width2) {
return false;
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54905
|
train
|
function (el) {
if (!subpixelRenderingIsSupported) {
if (document.body.style.zoom !== undefined) {
var $wrap = $('<div>').addClass(CSS_CLASS_SUBPX_FIX);
$(el).wrap($wrap);
}
}
return el;
}
|
javascript
|
{
"resource": ""
}
|
|
q54906
|
train
|
function (url) {
var parsedURL = this.parse(url);
if (!parsedLocation) {
parsedLocation = this.parse(this.getCurrentURL());
}
// IE7 does not properly parse relative URLs, so the hostname is empty
if (!parsedURL.hostname) {
return false;
}
return parsedURL.protocol !== parsedLocation.protocol ||
parsedURL.hostname !== parsedLocation.hostname ||
parsedURL.port !== parsedLocation.port;
}
|
javascript
|
{
"resource": ""
}
|
|
q54907
|
train
|
function (url) {
var parsed = document.createElement('a'),
pathname;
parsed.href = url;
// @NOTE: IE does not automatically parse relative urls,
// but requesting href back from the <a> element will return
// an absolute URL, which can then be fed back in to get the
// expected result. WTF? Yep!
if (browser.ie && url !== parsed.href) {
url = parsed.href;
parsed.href = url;
}
// @NOTE: IE does not include the preceding '/' in pathname
pathname = parsed.pathname;
if (!/^\//.test(pathname)) {
pathname = '/' + pathname;
}
return {
href: parsed.href,
protocol: parsed.protocol, // includes :
host: parsed.host, // includes port
hostname: parsed.hostname, // does not include port
port: parsed.port,
pathname: pathname,
hash: parsed.hash, // inclues #
search: parsed.search // incudes ?
};
}
|
javascript
|
{
"resource": ""
}
|
|
q54908
|
validateConfig
|
train
|
function validateConfig() {
var metadata = config.metadata;
config.numPages = metadata.numpages;
if (!config.pageStart) {
config.pageStart = 1;
} else if (config.pageStart < 0) {
config.pageStart = metadata.numpages + config.pageStart;
}
config.pageStart = util.clamp(config.pageStart, 1, metadata.numpages);
if (!config.pageEnd) {
config.pageEnd = metadata.numpages;
} else if (config.pageEnd < 0) {
config.pageEnd = metadata.numpages + config.pageEnd;
}
config.pageEnd = util.clamp(config.pageEnd, config.pageStart, metadata.numpages);
config.numPages = config.pageEnd - config.pageStart + 1;
}
|
javascript
|
{
"resource": ""
}
|
q54909
|
prepareDOM
|
train
|
function prepareDOM() {
var i, pageNum,
zoomLevel, maxZoom,
ptWidth, ptHeight,
pxWidth, pxHeight,
pt2px = util.calculatePtSize(),
dimensions = config.metadata.dimensions,
skeleton = '';
// adjust page scale if the pages are too small/big
// it's adjusted so 100% == DOCUMENT_100_PERCENT_WIDTH px;
config.pageScale = DOCUMENT_100_PERCENT_WIDTH / (dimensions.width * pt2px);
// add zoom levels to accomodate the scale
zoomLevel = config.zoomLevels[config.zoomLevels.length - 1];
maxZoom = 3 / config.pageScale;
while (zoomLevel < maxZoom) {
zoomLevel += zoomLevel / 2;
config.zoomLevels.push(zoomLevel);
}
dimensions.exceptions = dimensions.exceptions || {};
// create skeleton
for (i = config.pageStart - 1; i < config.pageEnd; i++) {
pageNum = i + 1;
if (pageNum in dimensions.exceptions) {
ptWidth = dimensions.exceptions[pageNum].width;
ptHeight = dimensions.exceptions[pageNum].height;
} else {
ptWidth = dimensions.width;
ptHeight = dimensions.height;
}
pxWidth = ptWidth * pt2px;
pxHeight = ptHeight * pt2px;
pxWidth *= config.pageScale;
pxHeight *= config.pageScale;
skeleton += util.template(Crocodoc.pageTemplate, {
w: pxWidth,
h: pxHeight
});
}
// insert skeleton and keep a reference to the jq object
config.$pages = $(skeleton).appendTo(config.$doc);
}
|
javascript
|
{
"resource": ""
}
|
q54910
|
createPages
|
train
|
function createPages() {
var i,
pages = [],
page,
start = config.pageStart - 1,
end = config.pageEnd,
links = sortPageLinks();
//initialize pages
for (i = start; i < end; i++) {
page = scope.createComponent('page');
page.init(config.$pages.eq(i - start), {
index: i,
status: getInitialPageStatus(i),
enableLinks: config.enableLinks,
links: links[i],
pageScale: config.pageScale,
useSVG: config.useSVG
});
pages.push(page);
}
config.pages = pages;
}
|
javascript
|
{
"resource": ""
}
|
q54911
|
sortPageLinks
|
train
|
function sortPageLinks() {
var i, len, link,
destination,
// the starting and ending page *numbers* (not indexes)
start = config.pageStart,
end = config.pageEnd,
links = config.metadata.links || [],
sorted = [];
// NOTE:
// link.pagenum is the page the link resides on
// link.destination.pagenum is the page the link links to
for (i = 0, len = config.metadata.numpages; i < len; ++i) {
sorted[i] = [];
}
for (i = 0, len = links.length; i < len; ++i) {
link = links[i];
if (link.pagenum < start || link.pagenum > end) {
// link page is outside the enabled page range
continue;
}
if (link.destination) {
destination = link.destination.pagenum;
if (destination < start || destination > end) {
// destination is outside the enabled page range
continue;
} else {
// subtract the number of pages cut off from the beginning
link.destination.pagenum = destination - (start - 1);
}
}
sorted[link.pagenum - 1].push(link);
}
return sorted;
}
|
javascript
|
{
"resource": ""
}
|
q54912
|
updateSelectedPages
|
train
|
function updateSelectedPages() {
var node = util.getSelectedNode();
var $page = $(node).closest('.'+CSS_CLASS_PAGE);
$el.find('.'+CSS_CLASS_TEXT_SELECTED).removeClass(CSS_CLASS_TEXT_SELECTED);
if (node && $el.has(node)) {
$page.addClass(CSS_CLASS_TEXT_SELECTED);
}
}
|
javascript
|
{
"resource": ""
}
|
q54913
|
handleMousemove
|
train
|
function handleMousemove(event) {
$el.scrollTop(downScrollPosition.top - (event.clientY - downMousePosition.y));
$el.scrollLeft(downScrollPosition.left - (event.clientX - downMousePosition.x));
event.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
q54914
|
handleMouseup
|
train
|
function handleMouseup(event) {
scope.broadcast('dragend');
$window.off('mousemove', handleMousemove);
$window.off('mouseup', handleMouseup);
event.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
q54915
|
handleMousedown
|
train
|
function handleMousedown(event) {
scope.broadcast('dragstart');
downScrollPosition = {
top: $el.scrollTop(),
left: $el.scrollLeft()
};
downMousePosition = {
x: event.clientX,
y: event.clientY
};
$window.on('mousemove', handleMousemove);
$window.on('mouseup', handleMouseup);
event.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
q54916
|
train
|
function () {
var config = scope.getConfig();
this.config = config;
// shortcut references to jq DOM objects
this.$el = config.$el;
this.$doc = config.$doc;
this.$viewport = config.$viewport;
this.$pages = config.$pages;
this.numPages = config.numPages;
// add the layout css class
this.layoutClass = CSS_CLASS_LAYOUT_PREFIX + config.layout;
this.$el.addClass(this.layoutClass);
this.initState();
}
|
javascript
|
{
"resource": ""
}
|
|
q54917
|
train
|
function () {
var viewportEl = this.$viewport[0],
dimensionsEl = viewportEl;
// use the documentElement for viewport dimensions
// if we are using the window as the viewport
if (viewportEl === window) {
dimensionsEl = document.documentElement;
}
// setup initial state
this.state = {
scrollTop: viewportEl.scrollTop,
scrollLeft: viewportEl.scrollLeft,
viewportDimensions: {
clientWidth: dimensionsEl.clientWidth,
clientHeight: dimensionsEl.clientHeight,
offsetWidth: dimensionsEl.offsetWidth,
offsetHeight: dimensionsEl.offsetHeight
},
zoomState: {
zoom: 1,
prevZoom: 0,
zoomMode: null
},
initialWidth: 0,
initialHeight: 0,
totalWidth: 0,
totalHeight: 0
};
this.zoomLevels = [];
}
|
javascript
|
{
"resource": ""
}
|
|
q54918
|
train
|
function (direction) {
var i,
zoom = false,
currentZoom = this.state.zoomState.zoom,
zoomLevels = this.zoomLevels;
if (direction === Crocodoc.ZOOM_IN) {
for (i = 0; i < zoomLevels.length; ++i) {
if (zoomLevels[i] > currentZoom) {
zoom = zoomLevels[i];
break;
}
}
} else if (direction === Crocodoc.ZOOM_OUT) {
for (i = zoomLevels.length - 1; i >= 0; --i) {
if (zoomLevels[i] < currentZoom) {
zoom = zoomLevels[i];
break;
}
}
}
return zoom;
}
|
javascript
|
{
"resource": ""
}
|
|
q54919
|
train
|
function (left, top) {
left = parseInt(left, 10) || 0;
top = parseInt(top, 10) || 0;
this.scrollToOffset(left + this.state.scrollLeft, top + this.state.scrollTop);
}
|
javascript
|
{
"resource": ""
}
|
|
q54920
|
train
|
function () {
var prev, page,
state = this.state,
pages = state.pages;
prev = util.bisectRight(pages, state.scrollLeft, 'x0') - 1;
page = util.bisectRight(pages, state.scrollLeft + pages[prev].width / 2, 'x0') - 1;
return 1 + page;
}
|
javascript
|
{
"resource": ""
}
|
|
q54921
|
train
|
function (val) {
var state = this.state,
zoom = this.parseZoomValue(val),
zoomState = state.zoomState,
currentZoom = zoomState.zoom,
zoomMode,
shouldNotCenter;
// update the zoom mode if we landed on a named mode
zoomMode = this.calculateZoomMode(val, zoom);
//respect zoom constraints
zoom = util.clamp(zoom, state.minZoom, state.maxZoom);
scope.broadcast('beforezoom', util.extend({
page: state.currentPage,
visiblePages: util.extend([], state.visiblePages),
fullyVisiblePages: util.extend([], state.fullyVisiblePages)
}, zoomState));
// update the zoom state
zoomState.prevZoom = currentZoom;
zoomState.zoom = zoom;
zoomState.zoomMode = zoomMode;
// apply the zoom to the actual DOM element(s)
this.applyZoom(zoom);
// can the document be zoomed in/out further?
zoomState.canZoomIn = this.calculateNextZoomLevel(Crocodoc.ZOOM_IN) !== false;
zoomState.canZoomOut = this.calculateNextZoomLevel(Crocodoc.ZOOM_OUT) !== false;
// update page states, because they will have changed after zooming
this.updatePageStates();
// layout mode specific stuff
this.updateLayout();
// update scroll position for the new zoom
// @NOTE: updateScrollPosition() must be called AFTER updateLayout(),
// because the scrollable space may change in updateLayout
// @NOTE: shouldNotCenter is true when using a named zoom level
// so that resizing the browser zooms to the current page offset
// rather than to the center like when zooming in/out
shouldNotCenter = val === Crocodoc.ZOOM_AUTO ||
val === Crocodoc.ZOOM_FIT_WIDTH ||
val === Crocodoc.ZOOM_FIT_HEIGHT;
this.updateScrollPosition(shouldNotCenter);
// update again, because updateLayout could have changed page positions
this.updatePageStates();
// make sure the visible pages are accurate (also update css classes)
this.updateVisiblePages(true);
// broadcast zoom event with new zoom state
scope.broadcast('zoom', util.extend({
page: state.currentPage,
visiblePages: util.extend([], state.visiblePages),
fullyVisiblePages: util.extend([], state.fullyVisiblePages),
isDraggable: this.isDraggable()
}, zoomState));
}
|
javascript
|
{
"resource": ""
}
|
|
q54922
|
train
|
function (val) {
var zoomVal = parseFloat(val),
state = this.state,
zoomState = state.zoomState,
currentZoom = zoomState.zoom,
nextZoom = currentZoom;
// number
if (zoomVal) {
nextZoom = zoomVal;
} else {
switch (val) {
case Crocodoc.ZOOM_FIT_WIDTH:
// falls through
case Crocodoc.ZOOM_FIT_HEIGHT:
// falls through
case Crocodoc.ZOOM_AUTO:
nextZoom = this.calculateZoomValue(val);
break;
case Crocodoc.ZOOM_IN:
// falls through
case Crocodoc.ZOOM_OUT:
nextZoom = this.calculateNextZoomLevel(val) || currentZoom;
break;
// bad mode or no value
default:
// if there hasn't been a zoom set yet
if (!currentZoom) {
//use default zoom
nextZoom = this.calculateZoomValue(this.config.zoom || Crocodoc.ZOOM_AUTO);
}
else if (zoomState.zoomMode) {
//adjust zoom
nextZoom = this.calculateZoomValue(zoomState.zoomMode);
} else {
nextZoom = currentZoom;
}
break;
}
}
return nextZoom;
}
|
javascript
|
{
"resource": ""
}
|
|
q54923
|
train
|
function (val, parsedZoom) {
// check if we landed on a named mode
switch (parsedZoom) {
case this.calculateZoomValue(Crocodoc.ZOOM_AUTO):
// if the value passed is a named zoom mode, use that, because
// fitheight and fitwidth can sometimes clash with auto (else use auto)
if (typeof val === 'string' &&
(val === Crocodoc.ZOOM_FIT_WIDTH || val === Crocodoc.ZOOM_FIT_HEIGHT))
{
return val;
}
return Crocodoc.ZOOM_AUTO;
case this.calculateZoomValue(Crocodoc.ZOOM_FIT_WIDTH):
return Crocodoc.ZOOM_FIT_WIDTH;
case this.calculateZoomValue(Crocodoc.ZOOM_FIT_HEIGHT):
return Crocodoc.ZOOM_FIT_HEIGHT;
default:
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54924
|
train
|
function () {
var i, lastZoomLevel,
zoomLevels = this.config.zoomLevels.slice() || [1],
auto = this.calculateZoomValue(Crocodoc.ZOOM_AUTO),
fitWidth = this.calculateZoomValue(Crocodoc.ZOOM_FIT_WIDTH),
fitHeight = this.calculateZoomValue(Crocodoc.ZOOM_FIT_HEIGHT),
presets = [fitWidth, fitHeight];
// update min and max zoom before adding presets into the mix
// because presets should not be able to override min/max zoom
this.state.minZoom = this.config.minZoom || zoomLevels[0];
this.state.maxZoom = this.config.maxZoom || zoomLevels[zoomLevels.length - 1];
// if auto is not the same as fitWidth or fitHeight,
// add it as a possible next zoom
if (auto !== fitWidth && auto !== fitHeight) {
presets.push(auto);
}
// add auto-zoom levels and sort
zoomLevels = zoomLevels.concat(presets);
zoomLevels.sort(function sortZoomLevels(a, b){
return a - b;
});
this.zoomLevels = [];
/**
* Return true if we should use this zoom level
* @param {number} zoomLevel The zoom level to consider
* @returns {boolean} True if we should keep this level
* @private
*/
function shouldUseZoomLevel(zoomLevel) {
var similarity = lastZoomLevel / zoomLevel;
// remove duplicates
if (zoomLevel === lastZoomLevel) {
return false;
}
// keep anything that is within the similarity threshold
if (similarity < ZOOM_LEVEL_SIMILARITY_THRESHOLD) {
return true;
}
// check if it's a preset
if (util.inArray(zoomLevel, presets) > -1) {
// keep presets if they are within a higher threshold
if (similarity < ZOOM_LEVEL_PRESETS_SIMILARITY_THRESHOLD) {
return true;
}
}
return false;
}
// remove duplicates from sorted list, and remove unnecessary levels
// @NOTE: some zoom levels end up being very close to the built-in
// presets (fit-width/fit-height/auto), which makes zooming previous
// or next level kind of annoying when the zoom level barely changes.
// This fixes that by applying a threshold to the zoom levels to
// each preset, and removing the non-preset version if the
// ratio is below the threshold.
lastZoomLevel = 0;
for (i = 0; i < zoomLevels.length; ++i) {
if (shouldUseZoomLevel(zoomLevels[i])) {
lastZoomLevel = zoomLevels[i];
this.zoomLevels.push(lastZoomLevel);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54925
|
shouldUseZoomLevel
|
train
|
function shouldUseZoomLevel(zoomLevel) {
var similarity = lastZoomLevel / zoomLevel;
// remove duplicates
if (zoomLevel === lastZoomLevel) {
return false;
}
// keep anything that is within the similarity threshold
if (similarity < ZOOM_LEVEL_SIMILARITY_THRESHOLD) {
return true;
}
// check if it's a preset
if (util.inArray(zoomLevel, presets) > -1) {
// keep presets if they are within a higher threshold
if (similarity < ZOOM_LEVEL_PRESETS_SIMILARITY_THRESHOLD) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q54926
|
train
|
function (pageNum) {
var index = util.clamp(pageNum - 1, 0, this.numPages - 1),
page = this.state.pages[index];
return { top: page.y0, left: page.x0 };
}
|
javascript
|
{
"resource": ""
}
|
|
q54927
|
train
|
function (page) {
var state = this.state;
if (state.currentPage !== page) {
// page has changed
state.currentPage = page;
this.updateVisiblePages();
scope.broadcast('pagefocus', {
page: state.currentPage,
numPages: this.numPages,
visiblePages: util.extend([], state.visiblePages),
fullyVisiblePages: util.extend([], state.fullyVisiblePages)
});
} else {
// still update visible pages!
this.updateVisiblePages();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54928
|
train
|
function (updateClasses) {
var i, len, $page,
state = this.state,
visibleRange = this.calculateVisibleRange(),
fullyVisibleRange = this.calculateFullyVisibleRange();
state.visiblePages.length = 0;
state.fullyVisiblePages.length = 0;
for (i = 0, len = this.$pages.length; i < len; ++i) {
$page = this.$pages.eq(i);
if (i < visibleRange.min || i > visibleRange.max) {
if (updateClasses && $page.hasClass(CSS_CLASS_PAGE_VISIBLE)) {
$page.removeClass(CSS_CLASS_PAGE_VISIBLE);
}
} else {
if (updateClasses && !$page.hasClass(CSS_CLASS_PAGE_VISIBLE)) {
$page.addClass(CSS_CLASS_PAGE_VISIBLE);
}
state.visiblePages.push(i + 1);
}
if (i >= fullyVisibleRange.min && i <= fullyVisibleRange.max) {
state.fullyVisiblePages.push(i + 1);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54929
|
train
|
function (data) {
var zoomMode = this.state.zoomState.zoomMode;
this.state.viewportDimensions = data;
this.updateZoomLevels();
this.setZoom(zoomMode);
}
|
javascript
|
{
"resource": ""
}
|
|
q54930
|
train
|
function (shouldNotCenter) {
var state = this.state,
zoomState = state.zoomState,
ratio = zoomState.zoom / zoomState.prevZoom,
newScrollLeft, newScrollTop;
// update scroll position
newScrollLeft = state.scrollLeft * ratio;
newScrollTop = state.scrollTop * ratio;
// zoom to center
if (shouldNotCenter !== true) {
newScrollTop += state.viewportDimensions.offsetHeight * (ratio - 1) / 2;
newScrollLeft += state.viewportDimensions.offsetWidth * (ratio - 1) / 2;
}
// scroll!
this.scrollToOffset(newScrollLeft, newScrollTop);
}
|
javascript
|
{
"resource": ""
}
|
|
q54931
|
train
|
function (page) {
var index = util.clamp(page - 1, 0, this.numPages),
$precedingPage,
$currentPage;
paged.setCurrentPage.call(this, page);
// update CSS classes
this.$doc.find('.' + CSS_CLASS_PRECEDING_PAGE)
.removeClass(CSS_CLASS_PRECEDING_PAGE);
$precedingPage = this.$doc.find('.' + CSS_CLASS_CURRENT_PAGE);
$currentPage = this.$pages.eq(index);
if ($precedingPage[0] !== $currentPage[0]) {
$precedingPage
.addClass(CSS_CLASS_PRECEDING_PAGE)
.removeClass(CSS_CLASS_CURRENT_PAGE);
$currentPage.addClass(CSS_CLASS_CURRENT_PAGE);
}
this.updateVisiblePages(true);
this.updatePageClasses(index);
}
|
javascript
|
{
"resource": ""
}
|
|
q54932
|
train
|
function () {
var i, len, page, $page,
width, height, left, top, paddingH,
state = this.state,
viewportWidth = state.viewportDimensions.clientWidth,
viewportHeight = state.viewportDimensions.clientHeight;
// update pages so they are centered (preserving margins)
for (i = 0, len = this.$pages.length; i < len; ++i) {
$page = this.$pages.eq(i);
page = state.pages[i];
if (this.twoPageMode) {
paddingH = (i % 2 === 1) ? page.paddingRight : page.paddingLeft;
} else {
paddingH = page.paddingRight + page.paddingLeft;
}
width = (page.actualWidth + paddingH) * state.zoomState.zoom;
height = (page.actualHeight + page.paddingTop + page.paddingBottom) * state.zoomState.zoom;
if (this.twoPageMode) {
left = Math.max(0, (viewportWidth - width * 2) / 2);
if (i % 2 === 1) {
left += width;
}
} else {
left = (viewportWidth - width) / 2;
}
top = (viewportHeight - height) / 2;
left = Math.max(left, 0);
top = Math.max(top, 0);
$page.css({
marginLeft: left,
marginTop: top
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54933
|
train
|
function () {
var $pages = this.$pages,
index = this.state.currentPage - 1,
next = index + 1,
prev = index - 1,
buffer = 20;
// @TODO: optimize this a bit
// add/removeClass is expensive, so try using hasClass
$pages.removeClass(PRESENTATION_CSS_CLASSES);
if (this.twoPageMode) {
next = index + 2;
prev = index - 2;
$pages.slice(Math.max(prev, 0), index).addClass(CSS_CLASS_PAGE_PREV);
$pages.slice(next, next + 2).addClass(CSS_CLASS_PAGE_NEXT);
} else {
if (prev >= 0) {
$pages.eq(prev).addClass(CSS_CLASS_PAGE_PREV);
}
if (next < this.numPages) {
$pages.eq(next).addClass(CSS_CLASS_PAGE_NEXT);
}
}
$pages.slice(0, index).addClass(CSS_CLASS_PAGE_BEFORE);
$pages.slice(Math.max(0, index - buffer), index).addClass(CSS_CLASS_PAGE_BEFORE_BUFFER);
$pages.slice(next).addClass(CSS_CLASS_PAGE_AFTER);
$pages.slice(next, Math.min(this.numPages, next + buffer)).addClass(CSS_CLASS_PAGE_AFTER_BUFFER);
/*
// OPTIMIZATION CODE NOT YET WORKING PROPERLY
$pages.slice(0, index).each(function () {
var $p = $(this),
i = $p.index(),
toAdd = '',
toRm = '';
if (!$p.hasClass(beforeClass.trim())) toAdd += beforeClass;
if ($p.hasClass(nextClass.trim())) toRm += nextClass;
if ($p.hasClass(afterClass.trim())) toRm += afterClass;
if ($p.hasClass(afterBufferClass.trim())) toRm += afterBufferClass;
if (i >= index - buffer && !$p.hasClass(beforeBufferClass.trim()))
toAdd += beforeBufferClass;
else if ($p.hasClass(beforeBufferClass.trim()))
toRm += beforeBufferClass;
if (i >= prev && !$p.hasClass(prevClass.trim()))
toAdd += prevClass;
else if ($p.hasClass(prevClass.trim()))
toRm += prevClass;
$p.addClass(toAdd).removeClass(toRm);
// console.log('before', $p.index(), toRm, toAdd);
});
$pages.slice(next).each(function () {
var $p = $(this),
i = $p.index(),
toAdd = '',
toRm = '';
if (!$p.hasClass(afterClass.trim())) toAdd += afterClass;
if ($p.hasClass(prevClass.trim())) toRm += prevClass;
if ($p.hasClass(beforeClass.trim())) toRm += beforeClass;
if ($p.hasClass(beforeBufferClass.trim())) toRm += beforeBufferClass;
if (i <= index + buffer && !$p.hasClass(afterBufferClass.trim()))
toAdd += afterBufferClass;
else if ($p.hasClass(afterBufferClass.trim()))
toRm += afterBufferClass;
if (i <= next + 1 && !$p.hasClass(nextClass.trim()))
toAdd += nextClass;
else if ($p.hasClass(nextClass.trim()))
toRm += nextClass;
$p.addClass(toAdd).removeClass(toRm);
// console.log('after', $p.index(), toRm, toAdd);
});*/
}
|
javascript
|
{
"resource": ""
}
|
|
q54934
|
pageLoadLoop
|
train
|
function pageLoadLoop() {
var index;
clearTimeout(pageLoadTID);
if (pageLoadQueue.length > 0) {
// found a page to load
index = pageLoadQueue.shift();
// page exists and not reached max errors?
if (pages[index]) {
api.loadPage(index, function loadPageCallback(pageIsLoading) {
if (pageIsLoading === false) {
// don't wait if the page is not loading
pageLoadLoop();
} else {
pageLoadTID = setTimeout(pageLoadLoop, PAGE_LOAD_INTERVAL);
}
});
} else {
pageLoadLoop();
}
} else {
stopPageLoadLoop();
}
}
|
javascript
|
{
"resource": ""
}
|
q54935
|
indexInRange
|
train
|
function indexInRange(index, rangeLength) {
var range = calculateRange(rangeLength);
if (index >= range.min && index <= range.max) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q54936
|
shouldLoadPage
|
train
|
function shouldLoadPage(index) {
var page = pages[index];
// does the page exist?
if (page) {
// within page load range?
if (indexInRange(index)) {
return true;
}
// is it visible?
if (pageIsVisible(index)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q54937
|
shouldUnloadPage
|
train
|
function shouldUnloadPage(index, rangeLength) {
// within page load range?
if (indexInRange(index, rangeLength)) {
return false;
}
// is it visible?
if (pageIsVisible(index)) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54938
|
queuePagesToLoadInOrder
|
train
|
function queuePagesToLoadInOrder(start, end) {
var increment = util.sign(end - start);
while (start !== end) {
api.queuePageToLoad(start);
start += increment;
}
api.queuePageToLoad(start);
}
|
javascript
|
{
"resource": ""
}
|
q54939
|
train
|
function (pageComponents) {
pages = pageComponents;
numPages = pages.length;
pageLoadRange = (browser.mobile || browser.ielt10) ?
MAX_PAGE_LOAD_RANGE_MOBILE :
MAX_PAGE_LOAD_RANGE;
pageLoadRange = Math.min(pageLoadRange, numPages);
}
|
javascript
|
{
"resource": ""
}
|
|
q54940
|
train
|
function (state) {
scrollDirection = util.sign(state.page - layoutState.page);
layoutState = state;
}
|
javascript
|
{
"resource": ""
}
|
|
q54941
|
train
|
function (range) {
var currentIndex = layoutState.page - 1;
if (range > 0) {
range = calculateRange(range);
// load pages in the order of priority based on the direction
// the user is scrolling (load nearest page first, working in
// the scroll direction, then start on the opposite side of
// scroll direction and work outward)
// NOTE: we're assuming that a negative scroll direction means
// direction of previous pages, and positive is next pages...
if (scrollDirection >= 0) {
queuePagesToLoadInOrder(currentIndex + 1, range.max);
queuePagesToLoadInOrder(currentIndex - 1, range.min);
} else {
queuePagesToLoadInOrder(currentIndex - 1, range.min);
queuePagesToLoadInOrder(currentIndex + 1, range.max);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54942
|
train
|
function () {
var i, len;
for (i = 0, len = layoutState.visiblePages.length; i < len; ++i) {
this.queuePageToLoad(layoutState.visiblePages[i] - 1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54943
|
train
|
function (index, callback) {
$.when(pages[index] && pages[index].load())
.always(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q54944
|
train
|
function (data) {
if (!ready) {
return;
}
var i;
if (data.all === true) {
data.upto = numPages;
}
if (data.page) {
this.queuePageToLoad(data.page - 1);
} else if (data.upto) {
for (i = 0; i < data.upto; ++i) {
this.queuePageToLoad(i);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54945
|
train
|
function () {
this.preload();
$loadImgPromise.done(function loadImgSuccess(img) {
if (!imageLoaded) {
imageLoaded = true;
$img = $(img).appendTo($el);
}
});
$loadImgPromise.fail(function loadImgFail(error) {
imageLoaded = false;
if (error) {
scope.broadcast('asseterror', error);
}
});
return $loadImgPromise;
}
|
javascript
|
{
"resource": ""
}
|
|
q54946
|
createLink
|
train
|
function createLink(link) {
var $link = $('<a>').addClass(CSS_CLASS_PAGE_LINK),
left = link.bbox[0],
top = link.bbox[1],
attr = {};
if (browser.ie) {
// @NOTE: IE doesn't allow override of ctrl+click on anchor tags,
// but there is a workaround to add a child element (which triggers
// the onclick event first)
$('<span>')
.appendTo($link)
.on('click', handleClick);
}
$link.css({
left: left + 'pt',
top: top + 'pt',
width: link.bbox[2] - left + 'pt',
height: link.bbox[3] - top + 'pt'
});
if (link.uri) {
if (/^http|^mailto/.test(link.uri)) {
attr.href = encodeURI(link.uri);
attr.target = '_blank';
attr.rel = 'noreferrer'; // strip referrer for privacy
} else {
// don't embed this link... we don't trust the protocol
return;
}
} else if (link.destination) {
attr.href = '#page-' + link.destination.pagenum;
}
$link.attr(attr);
$link.data('link', link);
$link.appendTo($el);
}
|
javascript
|
{
"resource": ""
}
|
q54947
|
handleClick
|
train
|
function handleClick(event) {
var targetEl = browser.ie ? event.target.parentNode : event.target,
$link = $(targetEl),
data = $link.data('link');
if (data) {
scope.broadcast('linkclick', data);
}
event.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
q54948
|
train
|
function (el, links) {
$el = $(el);
this.createLinks(links);
if (!browser.ie) {
// @NOTE: event handlers are individually bound in IE, because
// the ctrl+click workaround fails when using event delegation
$el.on('click', '.' + CSS_CLASS_PAGE_LINK, handleClick);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54949
|
train
|
function (links) {
var i, len;
for (i = 0, len = links.length; i < len; ++i) {
createLink(links[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54950
|
createSVGEl
|
train
|
function createSVGEl() {
switch (embedStrategy) {
case EMBED_STRATEGY_IFRAME_INNERHTML:
case EMBED_STRATEGY_IFRAME_PROXY:
return $('<iframe>');
case EMBED_STRATEGY_DATA_URL_PROXY:
case EMBED_STRATEGY_DATA_URL:
return $('<object>').attr({
type: SVG_MIME_TYPE,
data: 'data:'+SVG_MIME_TYPE+';base64,' + window.btoa(SVG_CONTAINER_TEMPLATE)
});
case EMBED_STRATEGY_INLINE_SVG:
return $('<div>');
case EMBED_STRATEGY_BASIC_OBJECT:
return $('<object>');
case EMBED_STRATEGY_BASIC_IMG:
case EMBED_STRATEGY_DATA_URL_IMG:
return $('<img>');
// no default
}
}
|
javascript
|
{
"resource": ""
}
|
q54951
|
loadSVGText
|
train
|
function loadSVGText() {
if (svgLoaded ||
// @NOTE: these embed strategies don't require svg text to be loaded
embedStrategy === EMBED_STRATEGY_BASIC_OBJECT ||
embedStrategy === EMBED_STRATEGY_BASIC_IMG)
{
// don't load the SVG text, just return an empty promise
return $.Deferred().resolve().promise({
abort: function() {}
});
} else {
return scope.get('page-svg', page);
}
}
|
javascript
|
{
"resource": ""
}
|
q54952
|
loadSVGSuccess
|
train
|
function loadSVGSuccess(text) {
if (!destroyed && !unloaded) {
if (!svgLoaded && text) {
embedSVG(text);
svgLoaded = true;
if (!removeOnUnload) {
// cleanup the promise (abort will remove the svg text from
// the in-memory cache as well)
$loadSVGPromise.abort();
$loadSVGPromise = null;
}
}
// always insert the svg el when load was successful
if ($svg.parent().length === 0) {
$svg.appendTo($svgLayer);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54953
|
train
|
function () {
unloaded = true;
// stop loading the page if it hasn't finished yet
if ($loadSVGPromise && $loadSVGPromise.state() !== 'resolved') {
$loadSVGPromise.abort();
$loadSVGPromise = null;
}
// remove the svg element if necessary
if (removeOnUnload) {
if ($svg) {
$svg.remove();
$svg = null;
}
svgLoaded = false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54954
|
loadTextLayerHTMLSuccess
|
train
|
function loadTextLayerHTMLSuccess(text) {
var doc, textEl;
if (!text || loaded || destroyed) {
return;
}
loaded = true;
// create a document to parse the html text
doc = document.implementation.createHTMLDocument('');
doc.getElementsByTagName('body')[0].innerHTML = text;
text = null;
// select just the element we want (CSS_CLASS_PAGE_TEXT)
textEl = document.importNode(doc.querySelector('.' + CSS_CLASS_PAGE_TEXT), true);
$textLayer.attr('class', textEl.getAttribute('class'));
$textLayer.html(textEl.innerHTML);
subpx.fix($textLayer);
}
|
javascript
|
{
"resource": ""
}
|
q54955
|
train
|
function ($pageEl, config) {
var $text, $svg, $links;
$el = $pageEl;
$svg = $pageEl.find('.' + CSS_CLASS_PAGE_SVG);
$text = $pageEl.find('.' + CSS_CLASS_PAGE_TEXT);
$links = $pageEl.find('.' + CSS_CLASS_PAGE_LINKS);
status = config.status || PAGE_STATUS_NOT_LOADED;
index = config.index;
pageNum = index + 1;
this.config = config;
config.url = config.url || '';
pageText = scope.createComponent('page-text');
if (config.useSVG === undefined) {
config.useSVG = true;
}
pageContent = support.svg && config.useSVG ?
scope.createComponent('page-svg') :
scope.createComponent('page-img');
pageText.init($text, pageNum);
pageContent.init($svg, pageNum);
if (config.enableLinks && config.links.length) {
pageLinks = scope.createComponent('page-links');
pageLinks.init($links, config.links);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54956
|
train
|
function () {
var pageComponent = this;
loadRequested = true;
// the page has failed to load for good... don't try anymore
if (status === PAGE_STATUS_ERROR) {
return false;
}
// don't actually load if the page is converting
if (status === PAGE_STATUS_CONVERTING) {
return false;
}
// request assets to be loaded... but only ACTUALLY load if it is
// not loaded already
if (status !== PAGE_STATUS_LOADED) {
status = PAGE_STATUS_LOADING;
}
return $.when(pageContent.load(), pageText.load())
.done(function handleLoadDone() {
if (loadRequested) {
if (status !== PAGE_STATUS_LOADED) {
$el.removeClass(CSS_CLASS_PAGE_LOADING);
status = PAGE_STATUS_LOADED;
scope.broadcast('pageload', { page: pageNum });
}
} else {
pageComponent.unload();
}
})
.fail(function handleLoadFail(error) {
status = PAGE_STATUS_ERROR;
$el.addClass(CSS_CLASS_PAGE_ERROR);
scope.broadcast('pagefail', { page: index + 1, error: error });
});
}
|
javascript
|
{
"resource": ""
}
|
|
q54957
|
broadcast
|
train
|
function broadcast() {
scope.broadcast('resize', {
// shortcuts for offsetWidth/height
width: currentOffsetWidth,
height: currentOffsetHeight,
// client width is width of the inner, visible area
clientWidth: currentClientWidth,
clientHeight: currentClientHeight,
// offset width is the width of the element, including border,
// padding, and scrollbars
offsetWidth: currentOffsetWidth,
offsetHeight: currentOffsetHeight
});
}
|
javascript
|
{
"resource": ""
}
|
q54958
|
initResizer
|
train
|
function initResizer() {
var $iframe = $('<iframe frameborder="0">'),
$div = $('<div>');
$iframe.add($div).css({
opacity: 0,
visiblility: 'hidden',
position: 'absolute',
width: '100%',
height: '100%',
top: 0,
left: 0,
border: 0
});
$iframe.prependTo($div.prependTo(element));
fixElementPosition();
$window = $($iframe[0].contentWindow);
$window.on('resize', checkResize);
}
|
javascript
|
{
"resource": ""
}
|
q54959
|
checkResize
|
train
|
function checkResize() {
var newOffsetHeight = element.offsetHeight,
newOffsetWidth = element.offsetWidth;
// check if we're in a frame
if (inIframe) {
// firefox has an issue where styles aren't calculated in hidden iframes
// if the iframe was hidden and is now visible, broadcast a
// layoutchange event
if (frameWidth === 0 && window.innerWidth !== 0) {
frameWidth = window.innerWidth;
// fix the element position again if necessary
fixElementPosition();
scope.broadcast('layoutchange');
return;
}
}
//on touch devices, the offset height is sometimes zero as content is loaded
if (newOffsetHeight) {
if (newOffsetHeight !== currentOffsetHeight || newOffsetWidth !== currentOffsetWidth) {
currentOffsetHeight = newOffsetHeight;
currentOffsetWidth = newOffsetWidth;
currentClientHeight = element.clientHeight;
currentClientWidth = element.clientWidth;
broadcast();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54960
|
train
|
function (el) {
element = $(el).get(0);
// use the documentElement for viewport dimensions
// if we are using the window as the viewport
if (element === window) {
element = document.documentElement;
$window.on('resize', checkResize);
} else {
initResizer();
}
$document.on(FULLSCREENCHANGE_EVENT, checkResize);
checkResize();
}
|
javascript
|
{
"resource": ""
}
|
|
q54961
|
handleScroll
|
train
|
function handleScroll() {
// if we are just starting scrolling, fire scrollstart event
if (!scrollingStarted) {
scrollingStarted = true;
scope.broadcast('scrollstart', buildEventData());
}
clearTimeout(scrollendTID);
scrollendTID = setTimeout(handleScrollEnd, SCROLL_END_TIMEOUT);
fireScroll();
}
|
javascript
|
{
"resource": ""
}
|
q54962
|
handleTouchend
|
train
|
function handleTouchend() {
touchStarted = false;
touchEnded = true;
touchEndTime = new Date().getTime();
if (touchMoved) {
ghostScroll();
}
}
|
javascript
|
{
"resource": ""
}
|
q54963
|
ghostScroll
|
train
|
function ghostScroll() {
clearTimeout(scrollendTID);
if (ghostScrollStart === null) {
ghostScrollStart = new Date().getTime();
}
if (new Date().getTime() - ghostScrollStart > GHOST_SCROLL_TIMEOUT) {
handleScrollEnd();
return;
}
fireScroll();
scrollendTID = setTimeout(ghostScroll, GHOST_SCROLL_INTERVAL);
}
|
javascript
|
{
"resource": ""
}
|
q54964
|
train
|
function (el) {
$el = $(el);
$el.on('scroll', handleScroll);
$el.on('touchstart', handleTouchstart);
$el.on('touchmove', handleTouchmove);
$el.on('touchend', handleTouchend);
}
|
javascript
|
{
"resource": ""
}
|
|
q54965
|
train
|
function () {
clearTimeout(scrollendTID);
$el.off('scroll', handleScroll);
$el.off('touchstart', handleTouchstart);
$el.off('touchmove', handleTouchmove);
$el.off('touchend', handleTouchend);
}
|
javascript
|
{
"resource": ""
}
|
|
q54966
|
initViewerHTML
|
train
|
function initViewerHTML() {
// create viewer HTML
$el.html(Crocodoc.viewerTemplate);
if (config.useWindowAsViewport) {
config.$viewport = $(window);
$el.addClass(CSS_CLASS_WINDOW_AS_VIEWPORT);
} else {
config.$viewport = $el.find('.' + CSS_CLASS_VIEWPORT);
}
config.$doc = $el.find('.' + CSS_CLASS_DOC);
}
|
javascript
|
{
"resource": ""
}
|
q54967
|
initPlugins
|
train
|
function initPlugins() {
var name,
plugin,
plugins = config.plugins || {};
for (name in plugins) {
plugin = scope.createComponent('plugin-' + name);
if (plugin && util.isFn(plugin.init)) {
plugin.init(config.plugins[name]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54968
|
completeInit
|
train
|
function completeInit() {
setCSSFlags();
// initialize scroller and resizer components
scroller = scope.createComponent('scroller');
scroller.init(config.$viewport);
resizer = scope.createComponent('resizer');
resizer.init(config.$viewport);
var controller;
switch (config.metadata.type) {
case 'text':
// load text-based viewer
controller = scope.createComponent('controller-text');
// force the text layout only
// @TODO: allow overriding the layout eventually
config.layout = LAYOUT_TEXT;
break;
case 'paged':
/* falls through */
default:
controller = scope.createComponent('controller-paged');
break;
}
controller.init();
// disable text selection if necessary
if (config.metadata.type === 'text') {
if (!config.enableTextSelection) {
api.disableTextSelection();
}
} else if (browser.ielt9) {
api.disableTextSelection();
}
// disable links if necessary
// @NOTE: links are disabled in IE < 9
if (!config.enableLinks || browser.ielt9) {
api.disableLinks();
}
// set the initial layout
api.setLayout(config.layout);
// broadcast ready message
scope.broadcast('ready', {
page: config.page || 1,
numPages: config.numPages
});
scope.ready();
}
|
javascript
|
{
"resource": ""
}
|
q54969
|
handleLinkClick
|
train
|
function handleLinkClick(data) {
var event = api.fire('linkclick', data);
if (!event.isDefaultPrevented()) {
if (data.uri) {
window.open(data.uri);
} else if (data.destination) {
api.scrollTo(data.destination.pagenum);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54970
|
updateDragger
|
train
|
function updateDragger(isDraggable) {
if (isDraggable) {
if (!dragger) {
$el.addClass(CSS_CLASS_DRAGGABLE);
dragger = scope.createComponent('dragger');
dragger.init(config.$viewport);
}
} else {
if (dragger) {
$el.removeClass(CSS_CLASS_DRAGGABLE);
scope.destroyComponent(dragger);
dragger = null;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54971
|
validateQueryParams
|
train
|
function validateQueryParams() {
var queryString;
if (config.queryParams) {
if (typeof config.queryParams === 'string') {
// strip '?' if it's there, because we add it below
queryString = config.queryParams.replace(/^\?/, '');
} else {
queryString = util.param(config.queryParams);
}
}
config.queryString = queryString ? '?' + queryString : '';
}
|
javascript
|
{
"resource": ""
}
|
q54972
|
train
|
function () {
config = scope.getConfig();
api = config.api;
// create a unique CSS namespace for this viewer instance
config.namespace = CSS_CLASS_VIEWER + '-' + config.id;
// Setup container
$el = config.$el;
// add crocodoc viewer and namespace classes
$el.addClass(CSS_CLASS_VIEWER);
$el.addClass(config.namespace);
// add a / to the end of the base url if necessary
if (config.url) {
if (!/\/$/.test(config.url)) {
config.url += '/';
}
} else {
throw new Error('no URL given for viewer assets');
}
// make the url absolute
config.url = scope.getUtility('url').makeAbsolute(config.url);
//if useSVG hasn't been set, default to true
if (config.useSVG === undefined) {
config.useSVG = true;
}
validateQueryParams();
initViewerHTML();
initPlugins();
}
|
javascript
|
{
"resource": ""
}
|
|
q54973
|
train
|
function () {
// empty container and remove all class names that contain "crocodoc"
$el.empty().removeClass(function (i, cls) {
var match = cls.match(new RegExp('crocodoc\\S+', 'g'));
return match && match.join(' ');
});
// remove the stylesheet
$(stylesheetEl).remove();
if ($assetsPromise) {
$assetsPromise.abort();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54974
|
train
|
function (layoutMode) {
// create a layout component with the new layout config
var lastPage = config.page,
lastZoom = config.zoom || 1,
previousLayoutMode = config.layout,
newLayout;
// if there is already a layout, save some state
if (layout) {
// ignore this if we already have the specified layout
if (layoutMode === previousLayoutMode) {
return layout;
}
lastPage = layout.state.currentPage;
lastZoom = layout.state.zoomState;
}
newLayout = scope.createComponent('layout-' + layoutMode);
if (!newLayout) {
throw new Error('Invalid layout ' + layoutMode);
}
// remove and destroy the existing layout component
// @NOTE: this must be done after we decide if the
// new layout exists!
if (layout) {
scope.destroyComponent(layout);
}
config.layout = layoutMode;
layout = newLayout;
layout.init();
layout.setZoom(lastZoom.zoomMode || lastZoom.zoom || lastZoom);
if (util.isFn(layout.scrollTo)) {
layout.scrollTo(lastPage);
}
config.currentLayout = layout;
scope.broadcast('layoutchange', {
// in the context of event data, `layout` and `previousLayout`
// are actually the name of those layouts, and not the layout
// objects themselves
previousLayout: previousLayoutMode,
layout: layoutMode
});
return layout;
}
|
javascript
|
{
"resource": ""
}
|
|
q54975
|
train
|
function () {
var $loadStylesheetPromise,
$loadMetadataPromise,
$pageOneContentPromise,
$pageOneTextPromise;
if ($assetsPromise) {
return;
}
$loadMetadataPromise = scope.get('metadata');
$loadMetadataPromise.then(function handleMetadataResponse(metadata) {
config.metadata = metadata;
});
// don't load the stylesheet for IE < 9
if (browser.ielt9) {
stylesheetEl = util.insertCSS('');
config.stylesheet = stylesheetEl.styleSheet;
$loadStylesheetPromise = $.when('').promise({
abort: function () {}
});
} else {
$loadStylesheetPromise = scope.get('stylesheet');
$loadStylesheetPromise.then(function handleStylesheetResponse(cssText) {
stylesheetEl = util.insertCSS(cssText);
config.stylesheet = stylesheetEl.sheet;
});
}
// load page 1 assets immediately if necessary
if (config.autoloadFirstPage &&
(!config.pageStart || config.pageStart === 1)) {
if (support.svg && config.useSVG) {
$pageOneContentPromise = scope.get('page-svg', 1);
} else if (config.conversionIsComplete) {
// unfortunately, page-1.png is not necessarily available
// on View API's document.viewable event, so we can only
// prefetch page-1.png if conversion is complete
$pageOneContentPromise = scope.get('page-img', 1);
}
if (config.enableTextSelection) {
$pageOneTextPromise = scope.get('page-text', 1);
}
}
// when both metatadata and stylesheet are done or if either fails...
$assetsPromise = $.when($loadMetadataPromise, $loadStylesheetPromise)
.fail(function (error) {
if ($assetsPromise) {
$assetsPromise.abort();
}
scope.ready();
scope.broadcast('asseterror', error);
scope.broadcast('fail', error);
})
.then(completeInit)
.promise({
abort: function () {
$assetsPromise = null;
$loadMetadataPromise.abort();
$loadStylesheetPromise.abort();
if ($pageOneContentPromise) {
$pageOneContentPromise.abort();
}
if ($pageOneTextPromise) {
$pageOneTextPromise.abort();
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q54976
|
download
|
train
|
function download(url) {
var a = document.createElement('a');
a.href = url;
a.setAttribute('download', 'doc');
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
|
javascript
|
{
"resource": ""
}
|
q54977
|
train
|
function (config) {
var url = config.url,
viewerAPI = scope.getConfig().api;
if (url) {
viewerAPI.download = function () {
download(url);
};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54978
|
train
|
function (name, data) {
switch (name) {
case 'ready':
// $pages won't be available until the 'ready' message is broadcas
var viewerConfig = scope.getConfig();
$pages = viewerConfig.$pages;
$viewport = viewerConfig.$viewport;
$viewport.on('mousedown', handleMousedown);
break;
case 'pageload':
if ($pages.eq(data.page - 1).find('.page-content').length === 0) {
insertContent(data.page);
}
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54979
|
sendEvent
|
train
|
function sendEvent() {
var data = {},
eventName;
if (++i < c) {
if (channel.page < channel.numPages) {
data.pages = [channel.page++];
eventName = 'pageavailable.svg';
} else {
eventName = 'finished.svg';
data = '';
}
response.write('id: ' + i + '\n');
response.write('event: ' + eventName + '\n');
response.write('data: ' + (data ? JSON.stringify(data) : '') + '\n\n');
timeoutId = setTimeout(sendEvent, (Math.random() * 1000 + 50));
} else {
response.end();
}
}
|
javascript
|
{
"resource": ""
}
|
q54980
|
updateAvailablePages
|
train
|
function updateAvailablePages(pages) {
var i, page;
for (i = 0; i < pages.length; ++i) {
page = pages[i];
viewerAPI.fire('realtimeupdate', { page: page });
scope.broadcast('pageavailable', { page: page });
}
}
|
javascript
|
{
"resource": ""
}
|
q54981
|
handleFailedEvent
|
train
|
function handleFailedEvent(event) {
var data = getData(event);
viewerAPI.fire('realtimeerror', { error: data });
realtime.destroy();
}
|
javascript
|
{
"resource": ""
}
|
q54982
|
handleErrorEvent
|
train
|
function handleErrorEvent(event) {
var data = getData(event);
if (data) {
viewerAPI.fire('realtimeerror', { error: data.message });
if (data.close) {
realtime.destroy();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54983
|
registerBoxViewPageEventHandlers
|
train
|
function registerBoxViewPageEventHandlers() {
// event names depend on whether we support svg or not
if (scope.getUtility('support').svg) {
realtime.on('pageavailable.svg', handlePageAvailableEvent);
realtime.on('finished.svg', handleFinishedEvent);
realtime.on('failed.svg', handleFailedEvent);
} else {
realtime.on('pageavailable.png', handlePageAvailableEvent);
realtime.on('finished.png', handleFinishedEvent);
realtime.on('failed.png', handleFailedEvent);
}
realtime.on('error', handleErrorEvent);
}
|
javascript
|
{
"resource": ""
}
|
q54984
|
train
|
function (config, EventSource) {
var url = config.url;
if (url) {
realtime = new Crocodoc.Realtime(url, EventSource || window.EventSource);
// force the viewer to think conversion is not complete
// @TODO: ideally this wouldn't have to make an extra trip to
// the server just to find out the doc is already done
// converting, so we should have an indicator of the doc status
// in the session endpoint response
viewerConfig.conversionIsComplete = false;
registerBoxViewPageEventHandlers();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54985
|
isFullscreen
|
train
|
function isFullscreen() {
return document.fullScreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement ||
isFakeFullscreen;
}
|
javascript
|
{
"resource": ""
}
|
q54986
|
fullscreenchangeHandler
|
train
|
function fullscreenchangeHandler() {
viewerAPI.fire('fullscreenchange');
if (isFullscreen()) {
$el.addClass('crocodoc-fullscreen');
viewerAPI.fire('fullscreenenter');
} else {
$el.removeClass('crocodoc-fullscreen');
viewerAPI.fire('fullscreenexit');
}
}
|
javascript
|
{
"resource": ""
}
|
q54987
|
train
|
function (config) {
config = config || {};
if (typeof config.useFakeFullscreen !== 'undefined') {
useFakeFullscreen = config.useFakeFullscreen;
}
if (viewerConfig.useWindowAsViewport) {
// fake fullscreen mode is redundant if the window is used as
// the viewport, so turn it off
useFakeFullscreen = false;
el = document.documentElement;
$el = $(el);
} else {
if (config.element) {
$el = $(config.element);
} else {
$el = viewerConfig.$el;
}
el = $el[0];
}
// init browser-specific request/cancel fullscreen methods
requestFullscreen = el.requestFullScreen ||
el.requestFullscreen ||
el.mozRequestFullScreen ||
el.webkitRequestFullScreen ||
el.msRequestFullscreen ||
fakeRequestFullscreen;
// fullscreen APIs are completely insane
cancelFullscreen = document.cancelFullScreen ||
document.exitFullscreen ||
document.mozCancelFullScreen ||
document.webkitCancelFullScreen ||
document.msExitFullscreen ||
fakeCancelFullscreen;
// add enter/exit fullscreen methods to the viewer API
util.extend(viewerAPI, {
enterFullscreen: enterFullscreen,
exitFullscreen: exitFullscreen,
isFullscreen: isFullscreen,
isFullscreenSupported: isNativeFullscreenSupported
});
$(document).on(FULLSCREENCHANGE_EVENT, fullscreenchangeHandler);
}
|
javascript
|
{
"resource": ""
}
|
|
q54988
|
train
|
function (req, res) {
var oauthQueryStateToken = req.query.state;
var oauthCookieStateToken = req.cookies.oauthStateToken;
if (!oauthQueryStateToken || (!oauthCookieStateToken)) {
return false;
} else if (oauthQueryStateToken !== oauthCookieStateToken) {
return false;
}
res.clearCookie('oauthStateToken');
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q54989
|
train
|
function (req, res) {
var oauthStateToken = req.cookies.oauthStateToken;
if (!oauthStateToken) {
oauthStateToken = uuid.v4();
setTempCookie(res, 'oauthStateToken', oauthStateToken);
}
return oauthStateToken;
}
|
javascript
|
{
"resource": ""
}
|
|
q54990
|
train
|
function (req, res) {
var redirectTo = req.cookies.oauthRedirectUri || false;
if (redirectTo) {
res.clearCookie('oauthRedirectUri');
}
return redirectTo;
}
|
javascript
|
{
"resource": ""
}
|
|
q54991
|
train
|
function (req, provider, callback) {
var config = req.app.get('stormpathConfig');
var baseUrl = config.web.baseUrl || req.protocol + '://' + getHost(req);
var code = req.query.code;
var oauthStateToken = req.cookies.oauthStateToken;
var options = {
form: {
grant_type: 'authorization_code',
code: code,
redirect_uri: baseUrl + provider.uri,
client_id: config.authorizationServerClientId,
client_secret: config.authorizationServerClientSecret,
state: oauthStateToken
},
headers: {
Accept: 'application/json'
}
};
var authUrl = config.org + 'oauth2/' + config.authorizationServerId + '/v1/token';
request.post(authUrl, options, function (err, result, body) {
var parsedBody;
if (err) {
return callback(err);
}
var contentType = result.headers['content-type'] || '';
if (contentType.indexOf('text/plain') === 0) {
parsedBody = qs.parse(body);
} else {
try {
parsedBody = JSON.parse(body);
} catch (err) {
return callback(err);
}
if (parsedBody.error) {
return callback(new Error(parsedBody.error_description));
}
}
if (!parsedBody || typeof parsedBody !== 'object' || !parsedBody.access_token) {
return callback(new Error('Unable to parse response when exchanging an authorization code for an access token.'));
}
callback(null, parsedBody);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q54992
|
continueWithSubDomainStrategy
|
train
|
function continueWithSubDomainStrategy() {
if (web.multiTenancy.strategy === 'subdomain') {
if ((web.domainName === currentHost.domain) && currentHost.subdomain) {
return resolveOrganizationByNameKey(currentHost.subdomain, function (err, organization) {
if (err) {
return next(err);
}
if (!organization) {
return next();
}
helpers.assertOrganizationIsMappedToApplication(organization, application, function (err, isMappedToApp) {
if (err) {
return next(err);
}
if (isMappedToApp) {
return continueWithOrganization(organization);
}
logger.info('The organization "' + organization.name + '" is not mapped to this application, it will not be used.');
next();
});
});
}
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q54993
|
revokeToken
|
train
|
function revokeToken(config, token, tokenType, callback) {
callback = callback || function () {};
var req = {
url: config.org + 'oauth2/' + config.authorizationServerId + '/v1/revoke',
method: 'POST',
form: {
token: tokenType,
token_type_hint: tokenType,
client_id: config.authorizationServerClientId,
client_secret: config.authorizationServerClientSecret
}
};
requestExecutor(req, callback);
}
|
javascript
|
{
"resource": ""
}
|
q54994
|
resetPasswordWithRecoveryToken
|
train
|
function resetPasswordWithRecoveryToken(client, recoveryTokenResource, newPassword, callback) {
var userHref = '/users/' + recoveryTokenResource._embedded.user.id;
client.getAccount(userHref, function (err, account) {
if (err) {
return callback(err);
}
var href = '/authn/recovery/answer';
var body = {
stateToken: recoveryTokenResource.stateToken,
answer: account.profile.stormpathMigrationRecoveryAnswer
};
client.createResource(href, body, function (err, result) {
if (err) {
return callback(err);
}
var href = '/authn/credentials/reset_password';
var body = {
stateToken: result.stateToken,
newPassword: newPassword
};
client.createResource(href, body, callback);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q54995
|
train
|
function (form) {
var viewData = {
form: form,
organization: req.organization
};
if (form.data.password !== form.data.passwordAgain) {
viewData.error = 'Passwords do not match.';
return helpers.render(req, res, view, viewData);
}
result.password = form.data.password;
return resetPasswordWithRecoveryToken(client, result, form.data.password, function (err) {
if (err) {
logger.info('A user attempted to reset their password, but the password change itself failed.');
err = oktaErrorTransformer(err);
viewData.error = err.userMessage;
return helpers.render(req, res, view, viewData);
}
if (config.web.changePassword.autoLogin) {
var options = {
username: result.email,
password: result.password
};
if (req.organization) {
options.accountStore = req.organization.href;
}
return helpers.authenticate(options, req, res, function (err) {
if (err) {
viewData.error = err.userMessage;
return helpers.render(req, res, view, viewData);
}
res.redirect(config.web.login.nextUri);
});
}
res.redirect(config.web.changePassword.nextUri);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q54996
|
train
|
function (form) {
helpers.render(req, res, view, { form: form, organization: req.organization });
}
|
javascript
|
{
"resource": ""
}
|
|
q54997
|
initClient
|
train
|
function initClient(app, opts) {
opts.userAgent = userAgent;
var logger = opts.logger;
if (!logger) {
logger = new winston.Logger({
transports: [
new winston.transports.Console({
colorize: true,
level: opts.debug || 'error'
})
]
});
}
app.set('stormpathLogger', logger);
var client = require('./client')(opts);
client.on('error', function (err) {
logger.error(err);
app.emit('stormpath.error', err);
});
client.on('ready', function () {
app.set('stormpathClient', client);
app.set('stormpathConfig', client.config);
});
return client;
}
|
javascript
|
{
"resource": ""
}
|
q54998
|
train
|
function (form) {
render(req, res, 'organization-select', {
form: form,
formActionUri: formActionUri,
formModel: organizationSelectFormModel
});
}
|
javascript
|
{
"resource": ""
}
|
|
q54999
|
renderLoginFormWithError
|
train
|
function renderLoginFormWithError(req, res, config, err) {
var logger = req.app.get('stormpathLogger');
var view = config.web.login.view;
var nextUri = url.parse(req.query.next || '').path;
var encodedNextUri = encodeURIComponent(nextUri);
var formActionUri = config.web.login.uri + (nextUri ? ('?next=' + encodedNextUri) : '');
var oauthStateToken = common.resolveStateToken(req, res);
var providers = buildProviderModel(req, res);
var hasSocialProviders = !!Object.keys(config.web.social || {}).length;
// Stormpath is unable to create or update the account because the
// Facebook or Google response did not contain the required property.
if (err.code === 7201) {
logger.info('Provider login error: ' + err.message);
err.userMessage = 'Login failed, because we could not retrieve your email address from the provider. Please ensure that you have granted email permission to our application.';
}
getFormViewModel('login', config, function (err2, viewModel) {
err = err2 || err;
var options = {
form: forms.loginForm,
formActionUri: formActionUri,
oauthStateToken: oauthStateToken,
hasSocialProviders: hasSocialProviders,
socialProviders: providers,
error: err.userMessage || err.message,
formModel: viewModel.form
};
render(req, res, view, options);
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.