repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
box/viewer.js
dist/crocodoc.viewer.js
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
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; } }
[ "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", ";", "}", "}" ]
Append a CSS rule to the given stylesheet @param {CSSStyleSheet} sheet The stylesheet object @param {string} selector The selector @param {string} rule The rule @returns {int} The index of the new rule
[ "Append", "a", "CSS", "rule", "to", "the", "given", "stylesheet" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2096-L2107
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; }
[ "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", "{", "px", "=", "DEFAULT_PT2PX_RATIO", ";", "}", "document", ".", "body", ".", "removeChild", "(", "div", ")", ";", "return", "px", ";", "}" ]
Calculates the size of 1pt in pixels @returns {number} The pixel value
[ "Calculates", "the", "size", "of", "1pt", "in", "pixels" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2161-L2182
train
box/viewer.js
dist/crocodoc.viewer.js
function (str, token) { var total = 0, i; while ((i = str.indexOf(token, i) + 1)) { total++; } return total; }
javascript
function (str, token) { var total = 0, i; while ((i = str.indexOf(token, i) + 1)) { total++; } return total; }
[ "function", "(", "str", ",", "token", ")", "{", "var", "total", "=", "0", ",", "i", ";", "while", "(", "(", "i", "=", "str", ".", "indexOf", "(", "token", ",", "i", ")", "+", "1", ")", ")", "{", "total", "++", ";", "}", "return", "total", ";", "}" ]
Count and return the number of occurrences of token in str @param {string} str The string to search @param {string} token The string to search for @returns {int} The number of occurrences
[ "Count", "and", "return", "the", "number", "of", "occurrences", "of", "token", "in", "str" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2190-L2196
train
box/viewer.js
dist/crocodoc.viewer.js
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
function (template, data) { var p; for (p in data) { if (data.hasOwnProperty(p)) { template = template.replace(new RegExp('\\{\\{' + p + '\\}\\}', 'g'), data[p]); } } return template; }
[ "function", "(", "template", ",", "data", ")", "{", "var", "p", ";", "for", "(", "p", "in", "data", ")", "{", "if", "(", "data", ".", "hasOwnProperty", "(", "p", ")", ")", "{", "template", "=", "template", ".", "replace", "(", "new", "RegExp", "(", "'\\\\{\\\\{'", "+", "\\\\", "+", "\\\\", ",", "p", ")", ",", "'\\\\}\\\\}'", ")", ";", "}", "}", "\\\\", "}" ]
Apply the given data to a template @param {string} template The template @param {Object} data The data to apply to the template @returns {string} The filled template
[ "Apply", "the", "given", "data", "to", "a", "template" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2204-L2212
train
box/viewer.js
dist/crocodoc.viewer.js
isSubpixelRenderingSupported
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
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; }
[ "function", "isSubpixelRenderingSupported", "(", ")", "{", "if", "(", "!", "$", ".", "support", ".", "leadingWhitespace", ")", "{", "return", "false", ";", "}", "else", "{", "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", "=", "$", "(", "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", "(", ")", ";", "if", "(", "!", "(", "'ontouchstart'", "in", "window", ")", ")", "{", "if", "(", "fontsize1", "===", "fontsize2", ")", "{", "return", "false", ";", "}", "if", "(", "width1", "===", "width2", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Return true if subpixel rendering is supported @returns {Boolean} @private
[ "Return", "true", "if", "subpixel", "rendering", "is", "supported" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2236-L2275
train
box/viewer.js
dist/crocodoc.viewer.js
function (el) { if (!subpixelRenderingIsSupported) { if (document.body.style.zoom !== undefined) { var $wrap = $('<div>').addClass(CSS_CLASS_SUBPX_FIX); $(el).wrap($wrap); } } return el; }
javascript
function (el) { if (!subpixelRenderingIsSupported) { if (document.body.style.zoom !== undefined) { var $wrap = $('<div>').addClass(CSS_CLASS_SUBPX_FIX); $(el).wrap($wrap); } } return el; }
[ "function", "(", "el", ")", "{", "if", "(", "!", "subpixelRenderingIsSupported", ")", "{", "if", "(", "document", ".", "body", ".", "style", ".", "zoom", "!==", "undefined", ")", "{", "var", "$wrap", "=", "$", "(", "'<div>'", ")", ".", "addClass", "(", "CSS_CLASS_SUBPX_FIX", ")", ";", "$", "(", "el", ")", ".", "wrap", "(", "$wrap", ")", ";", "}", "}", "return", "el", ";", "}" ]
Apply the subpixel rendering fix to the given element if necessary. @NOTE: Fix is only applied if the "zoom" CSS property exists (ie., this fix is never applied in Firefox) @param {Element} el The element @returns {Element} The element
[ "Apply", "the", "subpixel", "rendering", "fix", "to", "the", "given", "element", "if", "necessary", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2291-L2299
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; }
[ "function", "(", "url", ")", "{", "var", "parsedURL", "=", "this", ".", "parse", "(", "url", ")", ";", "if", "(", "!", "parsedLocation", ")", "{", "parsedLocation", "=", "this", ".", "parse", "(", "this", ".", "getCurrentURL", "(", ")", ")", ";", "}", "if", "(", "!", "parsedURL", ".", "hostname", ")", "{", "return", "false", ";", "}", "return", "parsedURL", ".", "protocol", "!==", "parsedLocation", ".", "protocol", "||", "parsedURL", ".", "hostname", "!==", "parsedLocation", ".", "hostname", "||", "parsedURL", ".", "port", "!==", "parsedLocation", ".", "port", ";", "}" ]
Returns true if the given url is external to the current domain @param {string} url The URL @returns {Boolean} Whether or not the url is external
[ "Returns", "true", "if", "the", "given", "url", "is", "external", "to", "the", "current", "domain" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2465-L2480
train
box/viewer.js
dist/crocodoc.viewer.js
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
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 ? }; }
[ "function", "(", "url", ")", "{", "var", "parsed", "=", "document", ".", "createElement", "(", "'a'", ")", ",", "pathname", ";", "parsed", ".", "href", "=", "url", ";", "if", "(", "browser", ".", "ie", "&&", "url", "!==", "parsed", ".", "href", ")", "{", "url", "=", "parsed", ".", "href", ";", "parsed", ".", "href", "=", "url", ";", "}", "pathname", "=", "parsed", ".", "pathname", ";", "if", "(", "!", "/", "^\\/", "/", ".", "test", "(", "pathname", ")", ")", "{", "pathname", "=", "'/'", "+", "pathname", ";", "}", "return", "{", "href", ":", "parsed", ".", "href", ",", "protocol", ":", "parsed", ".", "protocol", ",", "host", ":", "parsed", ".", "host", ",", "hostname", ":", "parsed", ".", "hostname", ",", "port", ":", "parsed", ".", "port", ",", "pathname", ":", "pathname", ",", "hash", ":", "parsed", ".", "hash", ",", "search", ":", "parsed", ".", "search", "}", ";", "}" ]
Parse a URL into protocol, host, port, etc @param {string} url The URL to parse @returns {object} The parsed URL parts
[ "Parse", "a", "URL", "into", "protocol", "host", "port", "etc" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2501-L2532
train
box/viewer.js
dist/crocodoc.viewer.js
validateConfig
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
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; }
[ "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", ";", "}" ]
Validates the config options @returns {void} @private
[ "Validates", "the", "config", "options" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2555-L2571
train
box/viewer.js
dist/crocodoc.viewer.js
prepareDOM
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
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); }
[ "function", "prepareDOM", "(", ")", "{", "var", "i", ",", "pageNum", ",", "zoomLevel", ",", "maxZoom", ",", "ptWidth", ",", "ptHeight", ",", "pxWidth", ",", "pxHeight", ",", "pt2px", "=", "util", ".", "calculatePtSize", "(", ")", ",", "dimensions", "=", "config", ".", "metadata", ".", "dimensions", ",", "skeleton", "=", "''", ";", "config", ".", "pageScale", "=", "DOCUMENT_100_PERCENT_WIDTH", "/", "(", "dimensions", ".", "width", "*", "pt2px", ")", ";", "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", "||", "{", "}", ";", "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", "}", ")", ";", "}", "config", ".", "$pages", "=", "$", "(", "skeleton", ")", ".", "appendTo", "(", "config", ".", "$doc", ")", ";", "}" ]
Create the html skeleton for the viewer and pages @returns {void} @private
[ "Create", "the", "html", "skeleton", "for", "the", "viewer", "and", "pages" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2578-L2623
train
box/viewer.js
dist/crocodoc.viewer.js
createPages
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
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; }
[ "function", "createPages", "(", ")", "{", "var", "i", ",", "pages", "=", "[", "]", ",", "page", ",", "start", "=", "config", ".", "pageStart", "-", "1", ",", "end", "=", "config", ".", "pageEnd", ",", "links", "=", "sortPageLinks", "(", ")", ";", "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", ";", "}" ]
Create and init all necessary page component instances @returns {void} @private
[ "Create", "and", "init", "all", "necessary", "page", "component", "instances" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2643-L2665
train
box/viewer.js
dist/crocodoc.viewer.js
sortPageLinks
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
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; }
[ "function", "sortPageLinks", "(", ")", "{", "var", "i", ",", "len", ",", "link", ",", "destination", ",", "start", "=", "config", ".", "pageStart", ",", "end", "=", "config", ".", "pageEnd", ",", "links", "=", "config", ".", "metadata", ".", "links", "||", "[", "]", ",", "sorted", "=", "[", "]", ";", "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", ")", "{", "continue", ";", "}", "if", "(", "link", ".", "destination", ")", "{", "destination", "=", "link", ".", "destination", ".", "pagenum", ";", "if", "(", "destination", "<", "start", "||", "destination", ">", "end", ")", "{", "continue", ";", "}", "else", "{", "link", ".", "destination", ".", "pagenum", "=", "destination", "-", "(", "start", "-", "1", ")", ";", "}", "}", "sorted", "[", "link", ".", "pagenum", "-", "1", "]", ".", "push", "(", "link", ")", ";", "}", "return", "sorted", ";", "}" ]
Returns all links associated with the given page @param {int} page The page @returns {Array} Array of links @private
[ "Returns", "all", "links", "associated", "with", "the", "given", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2673-L2714
train
box/viewer.js
dist/crocodoc.viewer.js
updateSelectedPages
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
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); } }
[ "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", ")", ";", "}", "}" ]
Check if text is selected on any page, and if so, add a css class to that page @returns {void} @TODO(clakenen): this method currently only adds the selected class to one page, so we should modify it to add the class to all pages with selected text @private
[ "Check", "if", "text", "is", "selected", "on", "any", "page", "and", "if", "so", "add", "a", "css", "class", "to", "that", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2732-L2739
train
box/viewer.js
dist/crocodoc.viewer.js
handleMousemove
function handleMousemove(event) { $el.scrollTop(downScrollPosition.top - (event.clientY - downMousePosition.y)); $el.scrollLeft(downScrollPosition.left - (event.clientX - downMousePosition.x)); event.preventDefault(); }
javascript
function handleMousemove(event) { $el.scrollTop(downScrollPosition.top - (event.clientY - downMousePosition.y)); $el.scrollLeft(downScrollPosition.left - (event.clientX - downMousePosition.x)); event.preventDefault(); }
[ "function", "handleMousemove", "(", "event", ")", "{", "$el", ".", "scrollTop", "(", "downScrollPosition", ".", "top", "-", "(", "event", ".", "clientY", "-", "downMousePosition", ".", "y", ")", ")", ";", "$el", ".", "scrollLeft", "(", "downScrollPosition", ".", "left", "-", "(", "event", ".", "clientX", "-", "downMousePosition", ".", "x", ")", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}" ]
Handle mousemove events @param {Event} event The event object @returns {void}
[ "Handle", "mousemove", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2839-L2843
train
box/viewer.js
dist/crocodoc.viewer.js
handleMouseup
function handleMouseup(event) { scope.broadcast('dragend'); $window.off('mousemove', handleMousemove); $window.off('mouseup', handleMouseup); event.preventDefault(); }
javascript
function handleMouseup(event) { scope.broadcast('dragend'); $window.off('mousemove', handleMousemove); $window.off('mouseup', handleMouseup); event.preventDefault(); }
[ "function", "handleMouseup", "(", "event", ")", "{", "scope", ".", "broadcast", "(", "'dragend'", ")", ";", "$window", ".", "off", "(", "'mousemove'", ",", "handleMousemove", ")", ";", "$window", ".", "off", "(", "'mouseup'", ",", "handleMouseup", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}" ]
Handle mouseup events @param {Event} event The event object @returns {void}
[ "Handle", "mouseup", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2850-L2855
train
box/viewer.js
dist/crocodoc.viewer.js
handleMousedown
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
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(); }
[ "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", "(", ")", ";", "}" ]
Handle mousedown events @param {Event} event The event object @returns {void}
[ "Handle", "mousedown", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2862-L2875
train
box/viewer.js
dist/crocodoc.viewer.js
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
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(); }
[ "function", "(", ")", "{", "var", "config", "=", "scope", ".", "getConfig", "(", ")", ";", "this", ".", "config", "=", "config", ";", "this", ".", "$el", "=", "config", ".", "$el", ";", "this", ".", "$doc", "=", "config", ".", "$doc", ";", "this", ".", "$viewport", "=", "config", ".", "$viewport", ";", "this", ".", "$pages", "=", "config", ".", "$pages", ";", "this", ".", "numPages", "=", "config", ".", "numPages", ";", "this", ".", "layoutClass", "=", "CSS_CLASS_LAYOUT_PREFIX", "+", "config", ".", "layout", ";", "this", ".", "$el", ".", "addClass", "(", "this", ".", "layoutClass", ")", ";", "this", ".", "initState", "(", ")", ";", "}" ]
Initialize the Layout component @returns {void}
[ "Initialize", "the", "Layout", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2953-L2968
train
box/viewer.js
dist/crocodoc.viewer.js
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
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 = []; }
[ "function", "(", ")", "{", "var", "viewportEl", "=", "this", ".", "$viewport", "[", "0", "]", ",", "dimensionsEl", "=", "viewportEl", ";", "if", "(", "viewportEl", "===", "window", ")", "{", "dimensionsEl", "=", "document", ".", "documentElement", ";", "}", "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", "=", "[", "]", ";", "}" ]
Initalize the state object @returns {void}
[ "Initalize", "the", "state", "object" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2974-L3004
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; }
[ "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", ";", "}" ]
Calculate the next zoom level for zooming in or out @param {string} direction Can be either Crocodoc.ZOOM_IN or Crocodoc.ZOOM_OUT @returns {number|boolean} The next zoom level or false if the viewer cannot be zoomed in the given direction
[ "Calculate", "the", "next", "zoom", "level", "for", "zooming", "in", "or", "out" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3026-L3049
train
box/viewer.js
dist/crocodoc.viewer.js
function (left, top) { left = parseInt(left, 10) || 0; top = parseInt(top, 10) || 0; this.scrollToOffset(left + this.state.scrollLeft, top + this.state.scrollTop); }
javascript
function (left, top) { left = parseInt(left, 10) || 0; top = parseInt(top, 10) || 0; this.scrollToOffset(left + this.state.scrollLeft, top + this.state.scrollTop); }
[ "function", "(", "left", ",", "top", ")", "{", "left", "=", "parseInt", "(", "left", ",", "10", ")", "||", "0", ";", "top", "=", "parseInt", "(", "top", ",", "10", ")", "||", "0", ";", "this", ".", "scrollToOffset", "(", "left", "+", "this", ".", "state", ".", "scrollLeft", ",", "top", "+", "this", ".", "state", ".", "scrollTop", ")", ";", "}" ]
Scrolls by the given pixel amount from the current location @param {int} left Left offset to scroll to @param {int} top Top offset to scroll to @returns {void}
[ "Scrolls", "by", "the", "given", "pixel", "amount", "from", "the", "current", "location" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3068-L3072
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; }
[ "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", ";", "}" ]
Calculate which page is currently the "focused" page. In horizontal mode, this is the page farthest to the left, where at least half of the page is showing. @returns {int} The current page
[ "Calculate", "which", "page", "is", "currently", "the", "focused", "page", ".", "In", "horizontal", "mode", "this", "is", "the", "page", "farthest", "to", "the", "left", "where", "at", "least", "half", "of", "the", "page", "is", "showing", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3177-L3185
train
box/viewer.js
dist/crocodoc.viewer.js
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
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)); }
[ "function", "(", "val", ")", "{", "var", "state", "=", "this", ".", "state", ",", "zoom", "=", "this", ".", "parseZoomValue", "(", "val", ")", ",", "zoomState", "=", "state", ".", "zoomState", ",", "currentZoom", "=", "zoomState", ".", "zoom", ",", "zoomMode", ",", "shouldNotCenter", ";", "zoomMode", "=", "this", ".", "calculateZoomMode", "(", "val", ",", "zoom", ")", ";", "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", ")", ")", ";", "zoomState", ".", "prevZoom", "=", "currentZoom", ";", "zoomState", ".", "zoom", "=", "zoom", ";", "zoomState", ".", "zoomMode", "=", "zoomMode", ";", "this", ".", "applyZoom", "(", "zoom", ")", ";", "zoomState", ".", "canZoomIn", "=", "this", ".", "calculateNextZoomLevel", "(", "Crocodoc", ".", "ZOOM_IN", ")", "!==", "false", ";", "zoomState", ".", "canZoomOut", "=", "this", ".", "calculateNextZoomLevel", "(", "Crocodoc", ".", "ZOOM_OUT", ")", "!==", "false", ";", "this", ".", "updatePageStates", "(", ")", ";", "this", ".", "updateLayout", "(", ")", ";", "shouldNotCenter", "=", "val", "===", "Crocodoc", ".", "ZOOM_AUTO", "||", "val", "===", "Crocodoc", ".", "ZOOM_FIT_WIDTH", "||", "val", "===", "Crocodoc", ".", "ZOOM_FIT_HEIGHT", ";", "this", ".", "updateScrollPosition", "(", "shouldNotCenter", ")", ";", "this", ".", "updatePageStates", "(", ")", ";", "this", ".", "updateVisiblePages", "(", "true", ")", ";", "scope", ".", "broadcast", "(", "'zoom'", ",", "util", ".", "extend", "(", "{", "page", ":", "state", ".", "currentPage", ",", "visiblePages", ":", "util", ".", "extend", "(", "[", "]", ",", "state", ".", "visiblePages", ")", ",", "fullyVisiblePages", ":", "util", ".", "extend", "(", "[", "]", ",", "state", ".", "fullyVisiblePages", ")", ",", "isDraggable", ":", "this", ".", "isDraggable", "(", ")", "}", ",", "zoomState", ")", ")", ";", "}" ]
Set the zoom level for the layout @param {float|string} val The zoom level (float or one of the zoom constants)
[ "Set", "the", "zoom", "level", "for", "the", "layout" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3391-L3453
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; }
[ "function", "(", "val", ")", "{", "var", "zoomVal", "=", "parseFloat", "(", "val", ")", ",", "state", "=", "this", ".", "state", ",", "zoomState", "=", "state", ".", "zoomState", ",", "currentZoom", "=", "zoomState", ".", "zoom", ",", "nextZoom", "=", "currentZoom", ";", "if", "(", "zoomVal", ")", "{", "nextZoom", "=", "zoomVal", ";", "}", "else", "{", "switch", "(", "val", ")", "{", "case", "Crocodoc", ".", "ZOOM_FIT_WIDTH", ":", "case", "Crocodoc", ".", "ZOOM_FIT_HEIGHT", ":", "case", "Crocodoc", ".", "ZOOM_AUTO", ":", "nextZoom", "=", "this", ".", "calculateZoomValue", "(", "val", ")", ";", "break", ";", "case", "Crocodoc", ".", "ZOOM_IN", ":", "case", "Crocodoc", ".", "ZOOM_OUT", ":", "nextZoom", "=", "this", ".", "calculateNextZoomLevel", "(", "val", ")", "||", "currentZoom", ";", "break", ";", "default", ":", "if", "(", "!", "currentZoom", ")", "{", "nextZoom", "=", "this", ".", "calculateZoomValue", "(", "this", ".", "config", ".", "zoom", "||", "Crocodoc", ".", "ZOOM_AUTO", ")", ";", "}", "else", "if", "(", "zoomState", ".", "zoomMode", ")", "{", "nextZoom", "=", "this", ".", "calculateZoomValue", "(", "zoomState", ".", "zoomMode", ")", ";", "}", "else", "{", "nextZoom", "=", "currentZoom", ";", "}", "break", ";", "}", "}", "return", "nextZoom", ";", "}" ]
Parse the given zoom value into a number to zoom to. @param {float|string} val The zoom level (float or one of the zoom constants) @returns {float} The parsed zoom level
[ "Parse", "the", "given", "zoom", "value", "into", "a", "number", "to", "zoom", "to", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3460-L3504
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; } }
[ "function", "(", "val", ",", "parsedZoom", ")", "{", "switch", "(", "parsedZoom", ")", "{", "case", "this", ".", "calculateZoomValue", "(", "Crocodoc", ".", "ZOOM_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", ";", "}", "}" ]
Calculates the new zoomMode given the input val and the parsed zoom value @param {float|string} val The input zoom value @param {float} parsedZoom The parsed zoom value @returns {string|null} The new zoom move
[ "Calculates", "the", "new", "zoomMode", "given", "the", "input", "val", "and", "the", "parsed", "zoom", "value" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3512-L3531
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); } } }
[ "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", "]", ";", "this", ".", "state", ".", "minZoom", "=", "this", ".", "config", ".", "minZoom", "||", "zoomLevels", "[", "0", "]", ";", "this", ".", "state", ".", "maxZoom", "=", "this", ".", "config", ".", "maxZoom", "||", "zoomLevels", "[", "zoomLevels", ".", "length", "-", "1", "]", ";", "if", "(", "auto", "!==", "fitWidth", "&&", "auto", "!==", "fitHeight", ")", "{", "presets", ".", "push", "(", "auto", ")", ";", "}", "zoomLevels", "=", "zoomLevels", ".", "concat", "(", "presets", ")", ";", "zoomLevels", ".", "sort", "(", "function", "sortZoomLevels", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "this", ".", "zoomLevels", "=", "[", "]", ";", "function", "shouldUseZoomLevel", "(", "zoomLevel", ")", "{", "var", "similarity", "=", "lastZoomLevel", "/", "zoomLevel", ";", "if", "(", "zoomLevel", "===", "lastZoomLevel", ")", "{", "return", "false", ";", "}", "if", "(", "similarity", "<", "ZOOM_LEVEL_SIMILARITY_THRESHOLD", ")", "{", "return", "true", ";", "}", "if", "(", "util", ".", "inArray", "(", "zoomLevel", ",", "presets", ")", ">", "-", "1", ")", "{", "if", "(", "similarity", "<", "ZOOM_LEVEL_PRESETS_SIMILARITY_THRESHOLD", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "lastZoomLevel", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "zoomLevels", ".", "length", ";", "++", "i", ")", "{", "if", "(", "shouldUseZoomLevel", "(", "zoomLevels", "[", "i", "]", ")", ")", "{", "lastZoomLevel", "=", "zoomLevels", "[", "i", "]", ";", "this", ".", "zoomLevels", ".", "push", "(", "lastZoomLevel", ")", ";", "}", "}", "}" ]
Update zoom levels and the min and max zoom @returns {void}
[ "Update", "zoom", "levels", "and", "the", "min", "and", "max", "zoom" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3537-L3604
train
box/viewer.js
dist/crocodoc.viewer.js
shouldUseZoomLevel
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
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; }
[ "function", "shouldUseZoomLevel", "(", "zoomLevel", ")", "{", "var", "similarity", "=", "lastZoomLevel", "/", "zoomLevel", ";", "if", "(", "zoomLevel", "===", "lastZoomLevel", ")", "{", "return", "false", ";", "}", "if", "(", "similarity", "<", "ZOOM_LEVEL_SIMILARITY_THRESHOLD", ")", "{", "return", "true", ";", "}", "if", "(", "util", ".", "inArray", "(", "zoomLevel", ",", "presets", ")", ">", "-", "1", ")", "{", "if", "(", "similarity", "<", "ZOOM_LEVEL_PRESETS_SIMILARITY_THRESHOLD", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
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
[ "Return", "true", "if", "we", "should", "use", "this", "zoom", "level" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3570-L3588
train
box/viewer.js
dist/crocodoc.viewer.js
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
function (pageNum) { var index = util.clamp(pageNum - 1, 0, this.numPages - 1), page = this.state.pages[index]; return { top: page.y0, left: page.x0 }; }
[ "function", "(", "pageNum", ")", "{", "var", "index", "=", "util", ".", "clamp", "(", "pageNum", "-", "1", ",", "0", ",", "this", ".", "numPages", "-", "1", ")", ",", "page", "=", "this", ".", "state", ".", "pages", "[", "index", "]", ";", "return", "{", "top", ":", "page", ".", "y0", ",", "left", ":", "page", ".", "x0", "}", ";", "}" ]
Given a page number, return an object with top and left properties of the scroll position for that page @param {int} pageNum The page number @returns {Object} The scroll position object
[ "Given", "a", "page", "number", "return", "an", "object", "with", "top", "and", "left", "properties", "of", "the", "scroll", "position", "for", "that", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3692-L3696
train
box/viewer.js
dist/crocodoc.viewer.js
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
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(); } }
[ "function", "(", "page", ")", "{", "var", "state", "=", "this", ".", "state", ";", "if", "(", "state", ".", "currentPage", "!==", "page", ")", "{", "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", "{", "this", ".", "updateVisiblePages", "(", ")", ";", "}", "}" ]
Set the current page, update the visible pages, and broadcast a pagefocus message if the given page is not already the current page @param {int} page The page number
[ "Set", "the", "current", "page", "update", "the", "visible", "pages", "and", "broadcast", "a", "pagefocus", "message", "if", "the", "given", "page", "is", "not", "already", "the", "current", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3773-L3789
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); } } }
[ "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", ")", ";", "}", "}", "}" ]
Calculate and update which pages are visible, possibly updating CSS classes on the pages @param {boolean} updateClasses Wheter to update page CSS classes as well @returns {void}
[ "Calculate", "and", "update", "which", "pages", "are", "visible", "possibly", "updating", "CSS", "classes", "on", "the", "pages" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3797-L3820
train
box/viewer.js
dist/crocodoc.viewer.js
function (data) { var zoomMode = this.state.zoomState.zoomMode; this.state.viewportDimensions = data; this.updateZoomLevels(); this.setZoom(zoomMode); }
javascript
function (data) { var zoomMode = this.state.zoomState.zoomMode; this.state.viewportDimensions = data; this.updateZoomLevels(); this.setZoom(zoomMode); }
[ "function", "(", "data", ")", "{", "var", "zoomMode", "=", "this", ".", "state", ".", "zoomState", ".", "zoomMode", ";", "this", ".", "state", ".", "viewportDimensions", "=", "data", ";", "this", ".", "updateZoomLevels", "(", ")", ";", "this", ".", "setZoom", "(", "zoomMode", ")", ";", "}" ]
Handle resize messages @param {Object} data Object containing width and height of the viewport @returns {void}
[ "Handle", "resize", "messages" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3936-L3941
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); }
[ "function", "(", "shouldNotCenter", ")", "{", "var", "state", "=", "this", ".", "state", ",", "zoomState", "=", "state", ".", "zoomState", ",", "ratio", "=", "zoomState", ".", "zoom", "/", "zoomState", ".", "prevZoom", ",", "newScrollLeft", ",", "newScrollTop", ";", "newScrollLeft", "=", "state", ".", "scrollLeft", "*", "ratio", ";", "newScrollTop", "=", "state", ".", "scrollTop", "*", "ratio", ";", "if", "(", "shouldNotCenter", "!==", "true", ")", "{", "newScrollTop", "+=", "state", ".", "viewportDimensions", ".", "offsetHeight", "*", "(", "ratio", "-", "1", ")", "/", "2", ";", "newScrollLeft", "+=", "state", ".", "viewportDimensions", ".", "offsetWidth", "*", "(", "ratio", "-", "1", ")", "/", "2", ";", "}", "this", ".", "scrollToOffset", "(", "newScrollLeft", ",", "newScrollTop", ")", ";", "}" ]
Update the scroll position after a zoom @param {bool} shouldNotCenter Whether or not the scroll position should be updated to center the new zoom level @returns {void}
[ "Update", "the", "scroll", "position", "after", "a", "zoom" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L3963-L3981
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); }
[ "function", "(", "page", ")", "{", "var", "index", "=", "util", ".", "clamp", "(", "page", "-", "1", ",", "0", ",", "this", ".", "numPages", ")", ",", "$precedingPage", ",", "$currentPage", ";", "paged", ".", "setCurrentPage", ".", "call", "(", "this", ",", "page", ")", ";", "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", ")", ";", "}" ]
Set the current page and updatePageClasses @param {int} page The page number
[ "Set", "the", "current", "page", "and", "updatePageClasses" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4174-L4197
train
box/viewer.js
dist/crocodoc.viewer.js
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
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 }); } }
[ "function", "(", ")", "{", "var", "i", ",", "len", ",", "page", ",", "$page", ",", "width", ",", "height", ",", "left", ",", "top", ",", "paddingH", ",", "state", "=", "this", ".", "state", ",", "viewportWidth", "=", "state", ".", "viewportDimensions", ".", "clientWidth", ",", "viewportHeight", "=", "state", ".", "viewportDimensions", ".", "clientHeight", ";", "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", "}", ")", ";", "}", "}" ]
Update page margins for the viewport size and zoom level @returns {void}
[ "Update", "page", "margins", "for", "the", "viewport", "size", "and", "zoom", "level" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4256-L4291
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); });*/ }
[ "function", "(", ")", "{", "var", "$pages", "=", "this", ".", "$pages", ",", "index", "=", "this", ".", "state", ".", "currentPage", "-", "1", ",", "next", "=", "index", "+", "1", ",", "prev", "=", "index", "-", "1", ",", "buffer", "=", "20", ";", "$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", ")", ";", "}" ]
Update page classes for presentation mode transitions @returns {void}
[ "Update", "page", "classes", "for", "presentation", "mode", "transitions" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4297-L4367
train
box/viewer.js
dist/crocodoc.viewer.js
pageLoadLoop
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
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(); } }
[ "function", "pageLoadLoop", "(", ")", "{", "var", "index", ";", "clearTimeout", "(", "pageLoadTID", ")", ";", "if", "(", "pageLoadQueue", ".", "length", ">", "0", ")", "{", "index", "=", "pageLoadQueue", ".", "shift", "(", ")", ";", "if", "(", "pages", "[", "index", "]", ")", "{", "api", ".", "loadPage", "(", "index", ",", "function", "loadPageCallback", "(", "pageIsLoading", ")", "{", "if", "(", "pageIsLoading", "===", "false", ")", "{", "pageLoadLoop", "(", ")", ";", "}", "else", "{", "pageLoadTID", "=", "setTimeout", "(", "pageLoadLoop", ",", "PAGE_LOAD_INTERVAL", ")", ";", "}", "}", ")", ";", "}", "else", "{", "pageLoadLoop", "(", ")", ";", "}", "}", "else", "{", "stopPageLoadLoop", "(", ")", ";", "}", "}" ]
Loop through the pageLoadQueue and load pages sequentially, setting a timeout to run again after PAGE_LOAD_INTERVAL ms until the queue is empty @returns {void} @private
[ "Loop", "through", "the", "pageLoadQueue", "and", "load", "pages", "sequentially", "setting", "a", "timeout", "to", "run", "again", "after", "PAGE_LOAD_INTERVAL", "ms", "until", "the", "queue", "is", "empty" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4633-L4655
train
box/viewer.js
dist/crocodoc.viewer.js
indexInRange
function indexInRange(index, rangeLength) { var range = calculateRange(rangeLength); if (index >= range.min && index <= range.max) { return true; } return false; }
javascript
function indexInRange(index, rangeLength) { var range = calculateRange(rangeLength); if (index >= range.min && index <= range.max) { return true; } return false; }
[ "function", "indexInRange", "(", "index", ",", "rangeLength", ")", "{", "var", "range", "=", "calculateRange", "(", "rangeLength", ")", ";", "if", "(", "index", ">=", "range", ".", "min", "&&", "index", "<=", "range", ".", "max", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Returns true if the given index is in the page load range, and false otherwise @param {int} index The page index @param {int} rangeLength The page range length @returns {bool} Whether the page index is in the page load range @private
[ "Returns", "true", "if", "the", "given", "index", "is", "in", "the", "page", "load", "range", "and", "false", "otherwise" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4709-L4715
train
box/viewer.js
dist/crocodoc.viewer.js
shouldLoadPage
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
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; }
[ "function", "shouldLoadPage", "(", "index", ")", "{", "var", "page", "=", "pages", "[", "index", "]", ";", "if", "(", "page", ")", "{", "if", "(", "indexInRange", "(", "index", ")", ")", "{", "return", "true", ";", "}", "if", "(", "pageIsVisible", "(", "index", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if the given page index should be loaded, and false otherwise @param {int} index The page index @returns {bool} Whether the page should be loaded @private
[ "Returns", "true", "if", "the", "given", "page", "index", "should", "be", "loaded", "and", "false", "otherwise" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4723-L4741
train
box/viewer.js
dist/crocodoc.viewer.js
shouldUnloadPage
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
function shouldUnloadPage(index, rangeLength) { // within page load range? if (indexInRange(index, rangeLength)) { return false; } // is it visible? if (pageIsVisible(index)) { return false; } return true; }
[ "function", "shouldUnloadPage", "(", "index", ",", "rangeLength", ")", "{", "if", "(", "indexInRange", "(", "index", ",", "rangeLength", ")", ")", "{", "return", "false", ";", "}", "if", "(", "pageIsVisible", "(", "index", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns true if the given page index should be unloaded, and false otherwise @param {int} index The page index @param {int} rangeLength The range length @returns {bool} Whether the page should be unloaded @private
[ "Returns", "true", "if", "the", "given", "page", "index", "should", "be", "unloaded", "and", "false", "otherwise" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4750-L4763
train
box/viewer.js
dist/crocodoc.viewer.js
queuePagesToLoadInOrder
function queuePagesToLoadInOrder(start, end) { var increment = util.sign(end - start); while (start !== end) { api.queuePageToLoad(start); start += increment; } api.queuePageToLoad(start); }
javascript
function queuePagesToLoadInOrder(start, end) { var increment = util.sign(end - start); while (start !== end) { api.queuePageToLoad(start); start += increment; } api.queuePageToLoad(start); }
[ "function", "queuePagesToLoadInOrder", "(", "start", ",", "end", ")", "{", "var", "increment", "=", "util", ".", "sign", "(", "end", "-", "start", ")", ";", "while", "(", "start", "!==", "end", ")", "{", "api", ".", "queuePageToLoad", "(", "start", ")", ";", "start", "+=", "increment", ";", "}", "api", ".", "queuePageToLoad", "(", "start", ")", ";", "}" ]
Queues pages to load in order from indexFrom to indexTo @param {number} start The page index to start at @param {number} end The page index to end at @returns {void}
[ "Queues", "pages", "to", "load", "in", "order", "from", "indexFrom", "to", "indexTo" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4782-L4790
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); }
[ "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", ")", ";", "}" ]
Initialize the LazyLoader component @param {Array} pageComponents The array of page components to lazily load @returns {void}
[ "Initialize", "the", "LazyLoader", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4845-L4852
train
box/viewer.js
dist/crocodoc.viewer.js
function (state) { scrollDirection = util.sign(state.page - layoutState.page); layoutState = state; }
javascript
function (state) { scrollDirection = util.sign(state.page - layoutState.page); layoutState = state; }
[ "function", "(", "state", ")", "{", "scrollDirection", "=", "util", ".", "sign", "(", "state", ".", "page", "-", "layoutState", ".", "page", ")", ";", "layoutState", "=", "state", ";", "}" ]
Updates the current layout state and scroll direction @param {Object} state The layout state @returns {void}
[ "Updates", "the", "current", "layout", "state", "and", "scroll", "direction" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4867-L4870
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); } } }
[ "function", "(", "range", ")", "{", "var", "currentIndex", "=", "layoutState", ".", "page", "-", "1", ";", "if", "(", "range", ">", "0", ")", "{", "range", "=", "calculateRange", "(", "range", ")", ";", "if", "(", "scrollDirection", ">=", "0", ")", "{", "queuePagesToLoadInOrder", "(", "currentIndex", "+", "1", ",", "range", ".", "max", ")", ";", "queuePagesToLoadInOrder", "(", "currentIndex", "-", "1", ",", "range", ".", "min", ")", ";", "}", "else", "{", "queuePagesToLoadInOrder", "(", "currentIndex", "-", "1", ",", "range", ".", "min", ")", ";", "queuePagesToLoadInOrder", "(", "currentIndex", "+", "1", ",", "range", ".", "max", ")", ";", "}", "}", "}" ]
Queue pages to load within the given range such that proceeding pages are added before preceding pages @param {int} range The range to load beyond the current page @returns {void}
[ "Queue", "pages", "to", "load", "within", "the", "given", "range", "such", "that", "proceeding", "pages", "are", "added", "before", "preceding", "pages" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4901-L4919
train
box/viewer.js
dist/crocodoc.viewer.js
function () { var i, len; for (i = 0, len = layoutState.visiblePages.length; i < len; ++i) { this.queuePageToLoad(layoutState.visiblePages[i] - 1); } }
javascript
function () { var i, len; for (i = 0, len = layoutState.visiblePages.length; i < len; ++i) { this.queuePageToLoad(layoutState.visiblePages[i] - 1); } }
[ "function", "(", ")", "{", "var", "i", ",", "len", ";", "for", "(", "i", "=", "0", ",", "len", "=", "layoutState", ".", "visiblePages", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "this", ".", "queuePageToLoad", "(", "layoutState", ".", "visiblePages", "[", "i", "]", "-", "1", ")", ";", "}", "}" ]
Queue to load all pages that are visible according to the current layoutState @returns {void}
[ "Queue", "to", "load", "all", "pages", "that", "are", "visible", "according", "to", "the", "current", "layoutState" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4926-L4931
train
box/viewer.js
dist/crocodoc.viewer.js
function (index, callback) { $.when(pages[index] && pages[index].load()) .always(callback); }
javascript
function (index, callback) { $.when(pages[index] && pages[index].load()) .always(callback); }
[ "function", "(", "index", ",", "callback", ")", "{", "$", ".", "when", "(", "pages", "[", "index", "]", "&&", "pages", "[", "index", "]", ".", "load", "(", ")", ")", ".", "always", "(", "callback", ")", ";", "}" ]
Call the load method on the page object at the specified index @param {int} index The index of the page to load @param {Function} callback Callback function to call always (regardless of page load success/fail) @returns {void}
[ "Call", "the", "load", "method", "on", "the", "page", "object", "at", "the", "specified", "index" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L4962-L4965
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); } } }
[ "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", ")", ";", "}", "}", "}" ]
Handle pageavailable messages @param {Object} data The message data @returns {void}
[ "Handle", "pageavailable", "messages" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5011-L5026
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; }
[ "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", ";", "}" ]
Load the image @returns {$.Promise} A jQuery Promise object
[ "Load", "the", "image" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5167-L5185
train
box/viewer.js
dist/crocodoc.viewer.js
createLink
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
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); }
[ "function", "createLink", "(", "link", ")", "{", "var", "$link", "=", "$", "(", "'<a>'", ")", ".", "addClass", "(", "CSS_CLASS_PAGE_LINK", ")", ",", "left", "=", "link", ".", "bbox", "[", "0", "]", ",", "top", "=", "link", ".", "bbox", "[", "1", "]", ",", "attr", "=", "{", "}", ";", "if", "(", "browser", ".", "ie", ")", "{", "$", "(", "'<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'", ";", "}", "else", "{", "return", ";", "}", "}", "else", "if", "(", "link", ".", "destination", ")", "{", "attr", ".", "href", "=", "'#page-'", "+", "link", ".", "destination", ".", "pagenum", ";", "}", "$link", ".", "attr", "(", "attr", ")", ";", "$link", ".", "data", "(", "'link'", ",", "link", ")", ";", "$link", ".", "appendTo", "(", "$el", ")", ";", "}" ]
Create a link element given link data @param {Object} link The link data @returns {void} @private
[ "Create", "a", "link", "element", "given", "link", "data" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5227-L5265
train
box/viewer.js
dist/crocodoc.viewer.js
handleClick
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
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(); }
[ "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", "(", ")", ";", "}" ]
Handle link clicks @param {Event} event The event object @returns {void} @private
[ "Handle", "link", "clicks" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5273-L5282
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); } }
[ "function", "(", "el", ",", "links", ")", "{", "$el", "=", "$", "(", "el", ")", ";", "this", ".", "createLinks", "(", "links", ")", ";", "if", "(", "!", "browser", ".", "ie", ")", "{", "$el", ".", "on", "(", "'click'", ",", "'.'", "+", "CSS_CLASS_PAGE_LINK", ",", "handleClick", ")", ";", "}", "}" ]
Initialize the page-links component @param {Array} links Links configuration array @returns {void} @TODO (possible): make a links data-provider instead of passing them in as an argument?
[ "Initialize", "the", "page", "-", "links", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5296-L5304
train
box/viewer.js
dist/crocodoc.viewer.js
function (links) { var i, len; for (i = 0, len = links.length; i < len; ++i) { createLink(links[i]); } }
javascript
function (links) { var i, len; for (i = 0, len = links.length; i < len; ++i) { createLink(links[i]); } }
[ "function", "(", "links", ")", "{", "var", "i", ",", "len", ";", "for", "(", "i", "=", "0", ",", "len", "=", "links", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "createLink", "(", "links", "[", "i", "]", ")", ";", "}", "}" ]
Create and insert link elements into the element @param {Array} links Array of link data @returns {void}
[ "Create", "and", "insert", "link", "elements", "into", "the", "element" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5322-L5327
train
box/viewer.js
dist/crocodoc.viewer.js
createSVGEl
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
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 } }
[ "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>'", ")", ";", "}", "}" ]
Create and return a jQuery object for the SVG element @returns {Object} The SVG $element @private
[ "Create", "and", "return", "a", "jQuery", "object", "for", "the", "SVG", "element" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5365-L5390
train
box/viewer.js
dist/crocodoc.viewer.js
loadSVGText
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
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); } }
[ "function", "loadSVGText", "(", ")", "{", "if", "(", "svgLoaded", "||", "embedStrategy", "===", "EMBED_STRATEGY_BASIC_OBJECT", "||", "embedStrategy", "===", "EMBED_STRATEGY_BASIC_IMG", ")", "{", "return", "$", ".", "Deferred", "(", ")", ".", "resolve", "(", ")", ".", "promise", "(", "{", "abort", ":", "function", "(", ")", "{", "}", "}", ")", ";", "}", "else", "{", "return", "scope", ".", "get", "(", "'page-svg'", ",", "page", ")", ";", "}", "}" ]
Load svg text if necessary @returns {$.Promise} @private
[ "Load", "svg", "text", "if", "necessary" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5413-L5426
train
box/viewer.js
dist/crocodoc.viewer.js
loadSVGSuccess
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
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); } } }
[ "function", "loadSVGSuccess", "(", "text", ")", "{", "if", "(", "!", "destroyed", "&&", "!", "unloaded", ")", "{", "if", "(", "!", "svgLoaded", "&&", "text", ")", "{", "embedSVG", "(", "text", ")", ";", "svgLoaded", "=", "true", ";", "if", "(", "!", "removeOnUnload", ")", "{", "$loadSVGPromise", ".", "abort", "(", ")", ";", "$loadSVGPromise", "=", "null", ";", "}", "}", "if", "(", "$svg", ".", "parent", "(", ")", ".", "length", "===", "0", ")", "{", "$svg", ".", "appendTo", "(", "$svgLayer", ")", ";", "}", "}", "}" ]
handle SVG load success @param {string} text The SVG text @returns {void}
[ "handle", "SVG", "load", "success" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5569-L5586
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; } }
[ "function", "(", ")", "{", "unloaded", "=", "true", ";", "if", "(", "$loadSVGPromise", "&&", "$loadSVGPromise", ".", "state", "(", ")", "!==", "'resolved'", ")", "{", "$loadSVGPromise", ".", "abort", "(", ")", ";", "$loadSVGPromise", "=", "null", ";", "}", "if", "(", "removeOnUnload", ")", "{", "if", "(", "$svg", ")", "{", "$svg", ".", "remove", "(", ")", ";", "$svg", "=", "null", ";", "}", "svgLoaded", "=", "false", ";", "}", "}" ]
Unload the SVG object if necessary @returns {void}
[ "Unload", "the", "SVG", "object", "if", "necessary" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5671-L5687
train
box/viewer.js
dist/crocodoc.viewer.js
loadTextLayerHTMLSuccess
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
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); }
[ "function", "loadTextLayerHTMLSuccess", "(", "text", ")", "{", "var", "doc", ",", "textEl", ";", "if", "(", "!", "text", "||", "loaded", "||", "destroyed", ")", "{", "return", ";", "}", "loaded", "=", "true", ";", "doc", "=", "document", ".", "implementation", ".", "createHTMLDocument", "(", "''", ")", ";", "doc", ".", "getElementsByTagName", "(", "'body'", ")", "[", "0", "]", ".", "innerHTML", "=", "text", ";", "text", "=", "null", ";", "textEl", "=", "document", ".", "importNode", "(", "doc", ".", "querySelector", "(", "'.'", "+", "CSS_CLASS_PAGE_TEXT", ")", ",", "true", ")", ";", "$textLayer", ".", "attr", "(", "'class'", ",", "textEl", ".", "getAttribute", "(", "'class'", ")", ")", ";", "$textLayer", ".", "html", "(", "textEl", ".", "innerHTML", ")", ";", "subpx", ".", "fix", "(", "$textLayer", ")", ";", "}" ]
Handle success loading HTML text @param {string} text The HTML text @returns {void} @private
[ "Handle", "success", "loading", "HTML", "text" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5727-L5746
train
box/viewer.js
dist/crocodoc.viewer.js
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
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); } }
[ "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", ")", ";", "}", "}" ]
Initialize the Page component @returns {void}
[ "Initialize", "the", "Page", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5917-L5945
train
box/viewer.js
dist/crocodoc.viewer.js
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
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 }); }); }
[ "function", "(", ")", "{", "var", "pageComponent", "=", "this", ";", "loadRequested", "=", "true", ";", "if", "(", "status", "===", "PAGE_STATUS_ERROR", ")", "{", "return", "false", ";", "}", "if", "(", "status", "===", "PAGE_STATUS_CONVERTING", ")", "{", "return", "false", ";", "}", "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", "}", ")", ";", "}", ")", ";", "}" ]
Load and show SVG and text assets for this page @returns {$.Promise} jQuery Promise object or false if the page is not loading
[ "Load", "and", "show", "SVG", "and", "text", "assets", "for", "this", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L5971-L6008
train
box/viewer.js
dist/crocodoc.viewer.js
broadcast
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
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 }); }
[ "function", "broadcast", "(", ")", "{", "scope", ".", "broadcast", "(", "'resize'", ",", "{", "width", ":", "currentOffsetWidth", ",", "height", ":", "currentOffsetHeight", ",", "clientWidth", ":", "currentClientWidth", ",", "clientHeight", ":", "currentClientHeight", ",", "offsetWidth", ":", "currentOffsetWidth", ",", "offsetHeight", ":", "currentOffsetHeight", "}", ")", ";", "}" ]
Fire the resize event with the proper data @returns {void} @private
[ "Fire", "the", "resize", "event", "with", "the", "proper", "data" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6086-L6099
train
box/viewer.js
dist/crocodoc.viewer.js
initResizer
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
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); }
[ "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", ")", ";", "}" ]
Initialize an iframe to fire events on resize @returns {void} @private
[ "Initialize", "an", "iframe", "to", "fire", "events", "on", "resize" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6121-L6138
train
box/viewer.js
dist/crocodoc.viewer.js
checkResize
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
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(); } } }
[ "function", "checkResize", "(", ")", "{", "var", "newOffsetHeight", "=", "element", ".", "offsetHeight", ",", "newOffsetWidth", "=", "element", ".", "offsetWidth", ";", "if", "(", "inIframe", ")", "{", "if", "(", "frameWidth", "===", "0", "&&", "window", ".", "innerWidth", "!==", "0", ")", "{", "frameWidth", "=", "window", ".", "innerWidth", ";", "fixElementPosition", "(", ")", ";", "scope", ".", "broadcast", "(", "'layoutchange'", ")", ";", "return", ";", "}", "}", "if", "(", "newOffsetHeight", ")", "{", "if", "(", "newOffsetHeight", "!==", "currentOffsetHeight", "||", "newOffsetWidth", "!==", "currentOffsetWidth", ")", "{", "currentOffsetHeight", "=", "newOffsetHeight", ";", "currentOffsetWidth", "=", "newOffsetWidth", ";", "currentClientHeight", "=", "element", ".", "clientHeight", ";", "currentClientWidth", "=", "element", ".", "clientWidth", ";", "broadcast", "(", ")", ";", "}", "}", "}" ]
Check if the element has resized, and broadcast the resize event if so @returns {void} @private
[ "Check", "if", "the", "element", "has", "resized", "and", "broadcast", "the", "resize", "event", "if", "so" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6145-L6173
train
box/viewer.js
dist/crocodoc.viewer.js
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
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(); }
[ "function", "(", "el", ")", "{", "element", "=", "$", "(", "el", ")", ".", "get", "(", "0", ")", ";", "if", "(", "element", "===", "window", ")", "{", "element", "=", "document", ".", "documentElement", ";", "$window", ".", "on", "(", "'resize'", ",", "checkResize", ")", ";", "}", "else", "{", "initResizer", "(", ")", ";", "}", "$document", ".", "on", "(", "FULLSCREENCHANGE_EVENT", ",", "checkResize", ")", ";", "checkResize", "(", ")", ";", "}" ]
Initialize the Resizer component with an element to watch @param {HTMLElement} el The element to watch @returns {void}
[ "Initialize", "the", "Resizer", "component", "with", "an", "element", "to", "watch" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6199-L6214
train
box/viewer.js
dist/crocodoc.viewer.js
handleScroll
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
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(); }
[ "function", "handleScroll", "(", ")", "{", "if", "(", "!", "scrollingStarted", ")", "{", "scrollingStarted", "=", "true", ";", "scope", ".", "broadcast", "(", "'scrollstart'", ",", "buildEventData", "(", ")", ")", ";", "}", "clearTimeout", "(", "scrollendTID", ")", ";", "scrollendTID", "=", "setTimeout", "(", "handleScrollEnd", ",", "SCROLL_END_TIMEOUT", ")", ";", "fireScroll", "(", ")", ";", "}" ]
Handle scroll events @returns {void} @private
[ "Handle", "scroll", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6288-L6297
train
box/viewer.js
dist/crocodoc.viewer.js
handleTouchend
function handleTouchend() { touchStarted = false; touchEnded = true; touchEndTime = new Date().getTime(); if (touchMoved) { ghostScroll(); } }
javascript
function handleTouchend() { touchStarted = false; touchEnded = true; touchEndTime = new Date().getTime(); if (touchMoved) { ghostScroll(); } }
[ "function", "handleTouchend", "(", ")", "{", "touchStarted", "=", "false", ";", "touchEnded", "=", "true", ";", "touchEndTime", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "if", "(", "touchMoved", ")", "{", "ghostScroll", "(", ")", ";", "}", "}" ]
Handle touchend events @returns {void} @private
[ "Handle", "touchend", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6326-L6333
train
box/viewer.js
dist/crocodoc.viewer.js
ghostScroll
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
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); }
[ "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", ")", ";", "}" ]
Fire fake scroll events. iOS doesn't fire events during the 'momentum' part of scrolling so this is used to fake these events until the page stops moving. @returns {void} @private
[ "Fire", "fake", "scroll", "events", ".", "iOS", "doesn", "t", "fire", "events", "during", "the", "momentum", "part", "of", "scrolling", "so", "this", "is", "used", "to", "fake", "these", "events", "until", "the", "page", "stops", "moving", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6342-L6353
train
box/viewer.js
dist/crocodoc.viewer.js
function (el) { $el = $(el); $el.on('scroll', handleScroll); $el.on('touchstart', handleTouchstart); $el.on('touchmove', handleTouchmove); $el.on('touchend', handleTouchend); }
javascript
function (el) { $el = $(el); $el.on('scroll', handleScroll); $el.on('touchstart', handleTouchstart); $el.on('touchmove', handleTouchmove); $el.on('touchend', handleTouchend); }
[ "function", "(", "el", ")", "{", "$el", "=", "$", "(", "el", ")", ";", "$el", ".", "on", "(", "'scroll'", ",", "handleScroll", ")", ";", "$el", ".", "on", "(", "'touchstart'", ",", "handleTouchstart", ")", ";", "$el", ".", "on", "(", "'touchmove'", ",", "handleTouchmove", ")", ";", "$el", ".", "on", "(", "'touchend'", ",", "handleTouchend", ")", ";", "}" ]
Initialize the scroller component @param {Element} el The Element @returns {void}
[ "Initialize", "the", "scroller", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6361-L6367
train
box/viewer.js
dist/crocodoc.viewer.js
function () { clearTimeout(scrollendTID); $el.off('scroll', handleScroll); $el.off('touchstart', handleTouchstart); $el.off('touchmove', handleTouchmove); $el.off('touchend', handleTouchend); }
javascript
function () { clearTimeout(scrollendTID); $el.off('scroll', handleScroll); $el.off('touchstart', handleTouchstart); $el.off('touchmove', handleTouchmove); $el.off('touchend', handleTouchend); }
[ "function", "(", ")", "{", "clearTimeout", "(", "scrollendTID", ")", ";", "$el", ".", "off", "(", "'scroll'", ",", "handleScroll", ")", ";", "$el", ".", "off", "(", "'touchstart'", ",", "handleTouchstart", ")", ";", "$el", ".", "off", "(", "'touchmove'", ",", "handleTouchmove", ")", ";", "$el", ".", "off", "(", "'touchend'", ",", "handleTouchend", ")", ";", "}" ]
Destroy the scroller component @returns {void}
[ "Destroy", "the", "scroller", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6373-L6379
train
box/viewer.js
dist/crocodoc.viewer.js
initViewerHTML
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
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); }
[ "function", "initViewerHTML", "(", ")", "{", "$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", ")", ";", "}" ]
Create and insert basic viewer DOM structure @returns {void} @private
[ "Create", "and", "insert", "basic", "viewer", "DOM", "structure" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6431-L6441
train
box/viewer.js
dist/crocodoc.viewer.js
initPlugins
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
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]); } } }
[ "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", "]", ")", ";", "}", "}", "}" ]
Initialize all plugins specified for this viewer instance @returns {void} @private
[ "Initialize", "all", "plugins", "specified", "for", "this", "viewer", "instance" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6448-L6458
train
box/viewer.js
dist/crocodoc.viewer.js
completeInit
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
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(); }
[ "function", "completeInit", "(", ")", "{", "setCSSFlags", "(", ")", ";", "scroller", "=", "scope", ".", "createComponent", "(", "'scroller'", ")", ";", "scroller", ".", "init", "(", "config", ".", "$viewport", ")", ";", "resizer", "=", "scope", ".", "createComponent", "(", "'resizer'", ")", ";", "resizer", ".", "init", "(", "config", ".", "$viewport", ")", ";", "var", "controller", ";", "switch", "(", "config", ".", "metadata", ".", "type", ")", "{", "case", "'text'", ":", "controller", "=", "scope", ".", "createComponent", "(", "'controller-text'", ")", ";", "config", ".", "layout", "=", "LAYOUT_TEXT", ";", "break", ";", "case", "'paged'", ":", "default", ":", "controller", "=", "scope", ".", "createComponent", "(", "'controller-paged'", ")", ";", "break", ";", "}", "controller", ".", "init", "(", ")", ";", "if", "(", "config", ".", "metadata", ".", "type", "===", "'text'", ")", "{", "if", "(", "!", "config", ".", "enableTextSelection", ")", "{", "api", ".", "disableTextSelection", "(", ")", ";", "}", "}", "else", "if", "(", "browser", ".", "ielt9", ")", "{", "api", ".", "disableTextSelection", "(", ")", ";", "}", "if", "(", "!", "config", ".", "enableLinks", "||", "browser", ".", "ielt9", ")", "{", "api", ".", "disableLinks", "(", ")", ";", "}", "api", ".", "setLayout", "(", "config", ".", "layout", ")", ";", "scope", ".", "broadcast", "(", "'ready'", ",", "{", "page", ":", "config", ".", "page", "||", "1", ",", "numPages", ":", "config", ".", "numPages", "}", ")", ";", "scope", ".", "ready", "(", ")", ";", "}" ]
Complete intialization after document metadata has been loaded; ie., bind events, init lazyloader and layout, broadcast ready message @returns {void} @private
[ "Complete", "intialization", "after", "document", "metadata", "has", "been", "loaded", ";", "ie", ".", "bind", "events", "init", "lazyloader", "and", "layout", "broadcast", "ready", "message" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6466-L6518
train
box/viewer.js
dist/crocodoc.viewer.js
handleLinkClick
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
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); } } }
[ "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", ")", ";", "}", "}", "}" ]
Handler for linkclick messages @returns {void} @private
[ "Handler", "for", "linkclick", "messages" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6525-L6534
train
box/viewer.js
dist/crocodoc.viewer.js
updateDragger
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
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; } } }
[ "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", ";", "}", "}", "}" ]
Enable or disable the dragger given the `isDraggable` flag @param {Boolean} isDraggable Whether or not the layout is draggable @returns {void} @private
[ "Enable", "or", "disable", "the", "dragger", "given", "the", "isDraggable", "flag" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6542-L6556
train
box/viewer.js
dist/crocodoc.viewer.js
validateQueryParams
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
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 : ''; }
[ "function", "validateQueryParams", "(", ")", "{", "var", "queryString", ";", "if", "(", "config", ".", "queryParams", ")", "{", "if", "(", "typeof", "config", ".", "queryParams", "===", "'string'", ")", "{", "queryString", "=", "config", ".", "queryParams", ".", "replace", "(", "/", "^\\?", "/", ",", "''", ")", ";", "}", "else", "{", "queryString", "=", "util", ".", "param", "(", "config", ".", "queryParams", ")", ";", "}", "}", "config", ".", "queryString", "=", "queryString", "?", "'?'", "+", "queryString", ":", "''", ";", "}" ]
Validates and normalizes queryParams config option @returns {void}
[ "Validates", "and", "normalizes", "queryParams", "config", "option" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6562-L6573
train
box/viewer.js
dist/crocodoc.viewer.js
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
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(); }
[ "function", "(", ")", "{", "config", "=", "scope", ".", "getConfig", "(", ")", ";", "api", "=", "config", ".", "api", ";", "config", ".", "namespace", "=", "CSS_CLASS_VIEWER", "+", "'-'", "+", "config", ".", "id", ";", "$el", "=", "config", ".", "$el", ";", "$el", ".", "addClass", "(", "CSS_CLASS_VIEWER", ")", ";", "$el", ".", "addClass", "(", "config", ".", "namespace", ")", ";", "if", "(", "config", ".", "url", ")", "{", "if", "(", "!", "/", "\\/$", "/", ".", "test", "(", "config", ".", "url", ")", ")", "{", "config", ".", "url", "+=", "'/'", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'no URL given for viewer assets'", ")", ";", "}", "config", ".", "url", "=", "scope", ".", "getUtility", "(", "'url'", ")", ".", "makeAbsolute", "(", "config", ".", "url", ")", ";", "if", "(", "config", ".", "useSVG", "===", "undefined", ")", "{", "config", ".", "useSVG", "=", "true", ";", "}", "validateQueryParams", "(", ")", ";", "initViewerHTML", "(", ")", ";", "initPlugins", "(", ")", ";", "}" ]
Initialize the viewer api @returns {void}
[ "Initialize", "the", "viewer", "api" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6655-L6689
train
box/viewer.js
dist/crocodoc.viewer.js
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
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(); } }
[ "function", "(", ")", "{", "$el", ".", "empty", "(", ")", ".", "removeClass", "(", "function", "(", "i", ",", "cls", ")", "{", "var", "match", "=", "cls", ".", "match", "(", "new", "RegExp", "(", "'crocodoc\\\\S+'", ",", "\\\\", ")", ")", ";", "'g'", "}", ")", ";", "return", "match", "&&", "match", ".", "join", "(", "' '", ")", ";", "$", "(", "stylesheetEl", ")", ".", "remove", "(", ")", ";", "}" ]
Destroy the viewer-base component @returns {void}
[ "Destroy", "the", "viewer", "-", "base", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6695-L6708
train
box/viewer.js
dist/crocodoc.viewer.js
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
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; }
[ "function", "(", "layoutMode", ")", "{", "var", "lastPage", "=", "config", ".", "page", ",", "lastZoom", "=", "config", ".", "zoom", "||", "1", ",", "previousLayoutMode", "=", "config", ".", "layout", ",", "newLayout", ";", "if", "(", "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", ")", ";", "}", "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'", ",", "{", "previousLayout", ":", "previousLayoutMode", ",", "layout", ":", "layoutMode", "}", ")", ";", "return", "layout", ";", "}" ]
Set the layout to the given mode, destroying and cleaning up the current layout if there is one @param {string} layoutMode The layout mode @returns {Layout} The layout object
[ "Set", "the", "layout", "to", "the", "given", "mode", "destroying", "and", "cleaning", "up", "the", "current", "layout", "if", "there", "is", "one" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6716-L6764
train
box/viewer.js
dist/crocodoc.viewer.js
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
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(); } } }); }
[ "function", "(", ")", "{", "var", "$loadStylesheetPromise", ",", "$loadMetadataPromise", ",", "$pageOneContentPromise", ",", "$pageOneTextPromise", ";", "if", "(", "$assetsPromise", ")", "{", "return", ";", "}", "$loadMetadataPromise", "=", "scope", ".", "get", "(", "'metadata'", ")", ";", "$loadMetadataPromise", ".", "then", "(", "function", "handleMetadataResponse", "(", "metadata", ")", "{", "config", ".", "metadata", "=", "metadata", ";", "}", ")", ";", "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", ";", "}", ")", ";", "}", "if", "(", "config", ".", "autoloadFirstPage", "&&", "(", "!", "config", ".", "pageStart", "||", "config", ".", "pageStart", "===", "1", ")", ")", "{", "if", "(", "support", ".", "svg", "&&", "config", ".", "useSVG", ")", "{", "$pageOneContentPromise", "=", "scope", ".", "get", "(", "'page-svg'", ",", "1", ")", ";", "}", "else", "if", "(", "config", ".", "conversionIsComplete", ")", "{", "$pageOneContentPromise", "=", "scope", ".", "get", "(", "'page-img'", ",", "1", ")", ";", "}", "if", "(", "config", ".", "enableTextSelection", ")", "{", "$pageOneTextPromise", "=", "scope", ".", "get", "(", "'page-text'", ",", "1", ")", ";", "}", "}", "$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", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Load the metadata and css for this document @returns {void}
[ "Load", "the", "metadata", "and", "css", "for", "this", "document" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L6770-L6841
train
box/viewer.js
plugins/download/download.js
download
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
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); }
[ "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", ")", ";", "}" ]
Initiate a download for the given URL @param {string} url The download URL @returns {void} @private
[ "Initiate", "a", "download", "for", "the", "given", "URL" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/download/download.js#L15-L22
train
box/viewer.js
plugins/download/download.js
function (config) { var url = config.url, viewerAPI = scope.getConfig().api; if (url) { viewerAPI.download = function () { download(url); }; } }
javascript
function (config) { var url = config.url, viewerAPI = scope.getConfig().api; if (url) { viewerAPI.download = function () { download(url); }; } }
[ "function", "(", "config", ")", "{", "var", "url", "=", "config", ".", "url", ",", "viewerAPI", "=", "scope", ".", "getConfig", "(", ")", ".", "api", ";", "if", "(", "url", ")", "{", "viewerAPI", ".", "download", "=", "function", "(", ")", "{", "download", "(", "url", ")", ";", "}", ";", "}", "}" ]
Initialize the download plugin @param {Object} config The config object @param {string} config.url The download URL @returns {void}
[ "Initialize", "the", "download", "plugin" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/download/download.js#L31-L40
train
box/viewer.js
examples/page-content-flip/page-content.js
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
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; } }
[ "function", "(", "name", ",", "data", ")", "{", "switch", "(", "name", ")", "{", "case", "'ready'", ":", "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", ";", "}", "}" ]
insert content into each page as it loads
[ "insert", "content", "into", "each", "page", "as", "it", "loads" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/examples/page-content-flip/page-content.js#L65-L80
train
box/viewer.js
examples/realtime/server.js
sendEvent
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
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(); } }
[ "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'", ")", ";", "\\n", "response", ".", "write", "(", "'event: '", "+", "eventName", "+", "'\\n'", ")", ";", "\\n", "}", "else", "response", ".", "write", "(", "'data: '", "+", "(", "data", "?", "JSON", ".", "stringify", "(", "data", ")", ":", "''", ")", "+", "'\\n\\n'", ")", ";", "}" ]
send 100 events before forcing a reconnect
[ "send", "100", "events", "before", "forcing", "a", "reconnect" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/examples/realtime/server.js#L88-L106
train
box/viewer.js
plugins/realtime/realtime.js
updateAvailablePages
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
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 }); } }
[ "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", "}", ")", ";", "}", "}" ]
Notify the viewer that new pages are available for loading @param {Array} pages Array of integer page numbers that are available @returns {void} @private
[ "Notify", "the", "viewer", "that", "new", "pages", "are", "available", "for", "loading" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/realtime/realtime.js#L87-L94
train
box/viewer.js
plugins/realtime/realtime.js
handleFailedEvent
function handleFailedEvent(event) { var data = getData(event); viewerAPI.fire('realtimeerror', { error: data }); realtime.destroy(); }
javascript
function handleFailedEvent(event) { var data = getData(event); viewerAPI.fire('realtimeerror', { error: data }); realtime.destroy(); }
[ "function", "handleFailedEvent", "(", "event", ")", "{", "var", "data", "=", "getData", "(", "event", ")", ";", "viewerAPI", ".", "fire", "(", "'realtimeerror'", ",", "{", "error", ":", "data", "}", ")", ";", "realtime", ".", "destroy", "(", ")", ";", "}" ]
Handle error and failed eventSource events @param {Event} event The event object @returns {void} @private
[ "Handle", "error", "and", "failed", "eventSource", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/realtime/realtime.js#L113-L117
train
box/viewer.js
plugins/realtime/realtime.js
handleErrorEvent
function handleErrorEvent(event) { var data = getData(event); if (data) { viewerAPI.fire('realtimeerror', { error: data.message }); if (data.close) { realtime.destroy(); } } }
javascript
function handleErrorEvent(event) { var data = getData(event); if (data) { viewerAPI.fire('realtimeerror', { error: data.message }); if (data.close) { realtime.destroy(); } } }
[ "function", "handleErrorEvent", "(", "event", ")", "{", "var", "data", "=", "getData", "(", "event", ")", ";", "if", "(", "data", ")", "{", "viewerAPI", ".", "fire", "(", "'realtimeerror'", ",", "{", "error", ":", "data", ".", "message", "}", ")", ";", "if", "(", "data", ".", "close", ")", "{", "realtime", ".", "destroy", "(", ")", ";", "}", "}", "}" ]
Handle eventSource errors @param {Event} event The event object @returns {void} @private
[ "Handle", "eventSource", "errors" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/realtime/realtime.js#L139-L147
train
box/viewer.js
plugins/realtime/realtime.js
registerBoxViewPageEventHandlers
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
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); }
[ "function", "registerBoxViewPageEventHandlers", "(", ")", "{", "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", ")", ";", "}" ]
Registers event handlers for page streaming specific realtime events @returns {void} @private
[ "Registers", "event", "handlers", "for", "page", "streaming", "specific", "realtime", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/realtime/realtime.js#L154-L167
train
box/viewer.js
plugins/realtime/realtime.js
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
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(); } }
[ "function", "(", "config", ",", "EventSource", ")", "{", "var", "url", "=", "config", ".", "url", ";", "if", "(", "url", ")", "{", "realtime", "=", "new", "Crocodoc", ".", "Realtime", "(", "url", ",", "EventSource", "||", "window", ".", "EventSource", ")", ";", "viewerConfig", ".", "conversionIsComplete", "=", "false", ";", "registerBoxViewPageEventHandlers", "(", ")", ";", "}", "}" ]
Initialize the realtime plugin @param {Object} config The config object @param {string} config.url The URL to connect to for realtime events @param {Function} [EventSource] EventSource constructor to use (for testing purposes) @returns {void}
[ "Initialize", "the", "realtime", "plugin" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/realtime/realtime.js#L177-L190
train
box/viewer.js
plugins/fullscreen/fullscreen.js
isFullscreen
function isFullscreen() { return document.fullScreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || isFakeFullscreen; }
javascript
function isFullscreen() { return document.fullScreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || isFakeFullscreen; }
[ "function", "isFullscreen", "(", ")", "{", "return", "document", ".", "fullScreenElement", "||", "document", ".", "webkitFullscreenElement", "||", "document", ".", "mozFullScreenElement", "||", "document", ".", "msFullscreenElement", "||", "isFakeFullscreen", ";", "}" ]
Return true if full screen is active @returns {boolean} @private
[ "Return", "true", "if", "full", "screen", "is", "active" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/fullscreen/fullscreen.js#L30-L36
train
box/viewer.js
plugins/fullscreen/fullscreen.js
fullscreenchangeHandler
function fullscreenchangeHandler() { viewerAPI.fire('fullscreenchange'); if (isFullscreen()) { $el.addClass('crocodoc-fullscreen'); viewerAPI.fire('fullscreenenter'); } else { $el.removeClass('crocodoc-fullscreen'); viewerAPI.fire('fullscreenexit'); } }
javascript
function fullscreenchangeHandler() { viewerAPI.fire('fullscreenchange'); if (isFullscreen()) { $el.addClass('crocodoc-fullscreen'); viewerAPI.fire('fullscreenenter'); } else { $el.removeClass('crocodoc-fullscreen'); viewerAPI.fire('fullscreenexit'); } }
[ "function", "fullscreenchangeHandler", "(", ")", "{", "viewerAPI", ".", "fire", "(", "'fullscreenchange'", ")", ";", "if", "(", "isFullscreen", "(", ")", ")", "{", "$el", ".", "addClass", "(", "'crocodoc-fullscreen'", ")", ";", "viewerAPI", ".", "fire", "(", "'fullscreenenter'", ")", ";", "}", "else", "{", "$el", ".", "removeClass", "(", "'crocodoc-fullscreen'", ")", ";", "viewerAPI", ".", "fire", "(", "'fullscreenexit'", ")", ";", "}", "}" ]
Handle fullscreenchange events @returns {void} @private
[ "Handle", "fullscreenchange", "events" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/fullscreen/fullscreen.js#L43-L52
train
box/viewer.js
plugins/fullscreen/fullscreen.js
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
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); }
[ "function", "(", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "if", "(", "typeof", "config", ".", "useFakeFullscreen", "!==", "'undefined'", ")", "{", "useFakeFullscreen", "=", "config", ".", "useFakeFullscreen", ";", "}", "if", "(", "viewerConfig", ".", "useWindowAsViewport", ")", "{", "useFakeFullscreen", "=", "false", ";", "el", "=", "document", ".", "documentElement", ";", "$el", "=", "$", "(", "el", ")", ";", "}", "else", "{", "if", "(", "config", ".", "element", ")", "{", "$el", "=", "$", "(", "config", ".", "element", ")", ";", "}", "else", "{", "$el", "=", "viewerConfig", ".", "$el", ";", "}", "el", "=", "$el", "[", "0", "]", ";", "}", "requestFullscreen", "=", "el", ".", "requestFullScreen", "||", "el", ".", "requestFullscreen", "||", "el", ".", "mozRequestFullScreen", "||", "el", ".", "webkitRequestFullScreen", "||", "el", ".", "msRequestFullscreen", "||", "fakeRequestFullscreen", ";", "cancelFullscreen", "=", "document", ".", "cancelFullScreen", "||", "document", ".", "exitFullscreen", "||", "document", ".", "mozCancelFullScreen", "||", "document", ".", "webkitCancelFullScreen", "||", "document", ".", "msExitFullscreen", "||", "fakeCancelFullscreen", ";", "util", ".", "extend", "(", "viewerAPI", ",", "{", "enterFullscreen", ":", "enterFullscreen", ",", "exitFullscreen", ":", "exitFullscreen", ",", "isFullscreen", ":", "isFullscreen", ",", "isFullscreenSupported", ":", "isNativeFullscreenSupported", "}", ")", ";", "$", "(", "document", ")", ".", "on", "(", "FULLSCREENCHANGE_EVENT", ",", "fullscreenchangeHandler", ")", ";", "}" ]
Initialize the fullscreen plugin @param {Object} config Config options for the fullscreen plugin @param {Element} config.element The element to use for fullscreen @param {boolen} config.useFakeFullscreen Whether to use fake fullscreen mode @returns {void}
[ "Initialize", "the", "fullscreen", "plugin" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/plugins/fullscreen/fullscreen.js#L132-L178
train
stormpath/express-stormpath
lib/oauth/common.js
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
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; }
[ "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", ";", "}" ]
Consume a state token cookie. @method @private @param {Object} req - The http request. @param {Object} res - The http response. @return {bool} Whether or not the token was successfully verified and consumed.
[ "Consume", "a", "state", "token", "cookie", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/oauth/common.js#L21-L34
train
stormpath/express-stormpath
lib/oauth/common.js
function (req, res) { var oauthStateToken = req.cookies.oauthStateToken; if (!oauthStateToken) { oauthStateToken = uuid.v4(); setTempCookie(res, 'oauthStateToken', oauthStateToken); } return oauthStateToken; }
javascript
function (req, res) { var oauthStateToken = req.cookies.oauthStateToken; if (!oauthStateToken) { oauthStateToken = uuid.v4(); setTempCookie(res, 'oauthStateToken', oauthStateToken); } return oauthStateToken; }
[ "function", "(", "req", ",", "res", ")", "{", "var", "oauthStateToken", "=", "req", ".", "cookies", ".", "oauthStateToken", ";", "if", "(", "!", "oauthStateToken", ")", "{", "oauthStateToken", "=", "uuid", ".", "v4", "(", ")", ";", "setTempCookie", "(", "res", ",", "'oauthStateToken'", ",", "oauthStateToken", ")", ";", "}", "return", "oauthStateToken", ";", "}" ]
Resolve a state token from a request. If then token doesn't exist then a new token is created and appended onto the response. @method @private @param {Object} req - The http request. @param {Object} res - The http response. @return {string} A state token (UUID).
[ "Resolve", "a", "state", "token", "from", "a", "request", ".", "If", "then", "token", "doesn", "t", "exist", "then", "a", "new", "token", "is", "created", "and", "appended", "onto", "the", "response", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/oauth/common.js#L47-L56
train
stormpath/express-stormpath
lib/oauth/common.js
function (req, res) { var redirectTo = req.cookies.oauthRedirectUri || false; if (redirectTo) { res.clearCookie('oauthRedirectUri'); } return redirectTo; }
javascript
function (req, res) { var redirectTo = req.cookies.oauthRedirectUri || false; if (redirectTo) { res.clearCookie('oauthRedirectUri'); } return redirectTo; }
[ "function", "(", "req", ",", "res", ")", "{", "var", "redirectTo", "=", "req", ".", "cookies", ".", "oauthRedirectUri", "||", "false", ";", "if", "(", "redirectTo", ")", "{", "res", ".", "clearCookie", "(", "'oauthRedirectUri'", ")", ";", "}", "return", "redirectTo", ";", "}" ]
Consume a redirect uri cookie. @method @private @param {Object} req - The http request. @param {Object} res - The http response. @return {mixed} The redirect uri (string) or false if didn't exist.
[ "Consume", "a", "redirect", "uri", "cookie", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/oauth/common.js#L68-L76
train
stormpath/express-stormpath
lib/oauth/common.js
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Exchange an authentication code for an OAuth access token. @method @private @param {string} config - stormpathConfig object @param {string} code - The authentication code. @param {string} baseUrl - The base url to prepend to the callback uri. @param {Object} provider - The provider object that contains the client id, secret, and uri. @param {Function} callback - The callback to call once a response has been resolved.
[ "Exchange", "an", "authentication", "code", "for", "an", "OAuth", "access", "token", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/oauth/common.js#L90-L140
train
stormpath/express-stormpath
lib/middleware/default-organization-resolver.js
continueWithSubDomainStrategy
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
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(); }
[ "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", "(", ")", ";", "}" ]
Strategy which tries to resolve an organization from a sub domain. If this step fails then it falls back to resolving an organization from an access token cookie.
[ "Strategy", "which", "tries", "to", "resolve", "an", "organization", "from", "a", "sub", "domain", ".", "If", "this", "step", "fails", "then", "it", "falls", "back", "to", "resolving", "an", "organization", "from", "an", "access", "token", "cookie", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/middleware/default-organization-resolver.js#L55-L89
train
stormpath/express-stormpath
lib/helpers/revoke-token.js
revokeToken
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
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); }
[ "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", ")", ";", "}" ]
Revoke a token. @method @private @param {tokenResolverFn} tokenResolver - Function that resolves a token of some kind. @param {string} jwt - Raw JWT. @param {string} jwtSigningKey - Secret used to sign the JWT. @param {callbackFn} callback - Optional callback.
[ "Revoke", "a", "token", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/revoke-token.js#L16-L31
train
stormpath/express-stormpath
lib/controllers/change-password.js
resetPasswordWithRecoveryToken
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
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); }); }); }
[ "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", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Uses the AuthN API to complete a password reset workflow. Use application.sendPasswordResetEmail() to get recoveryTokenResponse @param {*} client stormpath client instance @param {*} recoveryTokenResource the response from /authn/recovery/password @param {*} newPassword new password that the end-user has provided @param {*} callback
[ "Uses", "the", "AuthN", "API", "to", "complete", "a", "password", "reset", "workflow", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/change-password.js#L17-L49
train
stormpath/express-stormpath
lib/controllers/change-password.js
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
If we get here, it means the user is submitting a password change request, so we should attempt to change the user's password.
[ "If", "we", "get", "here", "it", "means", "the", "user", "is", "submitting", "a", "password", "change", "request", "so", "we", "should", "attempt", "to", "change", "the", "user", "s", "password", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/change-password.js#L126-L169
train
stormpath/express-stormpath
lib/controllers/change-password.js
function (form) { helpers.render(req, res, view, { form: form, organization: req.organization }); }
javascript
function (form) { helpers.render(req, res, view, { form: form, organization: req.organization }); }
[ "function", "(", "form", ")", "{", "helpers", ".", "render", "(", "req", ",", "res", ",", "view", ",", "{", "form", ":", "form", ",", "organization", ":", "req", ".", "organization", "}", ")", ";", "}" ]
If we get here, it means the user is doing a simple GET request, so we should just render the forgot password template.
[ "If", "we", "get", "here", "it", "means", "the", "user", "is", "doing", "a", "simple", "GET", "request", "so", "we", "should", "just", "render", "the", "forgot", "password", "template", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/change-password.js#L183-L185
train
stormpath/express-stormpath
lib/stormpath.js
initClient
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
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; }
[ "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", ";", "}" ]
Initialize the Stormpath client. @method @private @param {Object} app - The express application. @param {object} opts - A JSON hash of user supplied options. @return {Function} A function which accepts a callback.
[ "Initialize", "the", "Stormpath", "client", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/stormpath.js#L28-L59
train
stormpath/express-stormpath
lib/helpers/organization-resolution-guard.js
function (form) { render(req, res, 'organization-select', { form: form, formActionUri: formActionUri, formModel: organizationSelectFormModel }); }
javascript
function (form) { render(req, res, 'organization-select', { form: form, formActionUri: formActionUri, formModel: organizationSelectFormModel }); }
[ "function", "(", "form", ")", "{", "render", "(", "req", ",", "res", ",", "'organization-select'", ",", "{", "form", ":", "form", ",", "formActionUri", ":", "formActionUri", ",", "formModel", ":", "organizationSelectFormModel", "}", ")", ";", "}" ]
If we get here, it means the user is doing a simple GET request, so we should just render the original template.
[ "If", "we", "get", "here", "it", "means", "the", "user", "is", "doing", "a", "simple", "GET", "request", "so", "we", "should", "just", "render", "the", "original", "template", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/organization-resolution-guard.js#L121-L127
train
stormpath/express-stormpath
lib/oauth/error-responder.js
renderLoginFormWithError
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
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); }); }
[ "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", ";", "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", ")", ";", "}", ")", ";", "}" ]
Takes an error object and renders the login form with that error. @method @param {Object} req - The http request. @param {Object} res - The http response. @param {Object} config - Stormpath config. @param {Object} err - The error to display.
[ "Takes", "an", "error", "object", "and", "renders", "the", "login", "form", "with", "that", "error", "." ]
aed8d26ba51272755ea4eab706b4417e4bbeed99
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/oauth/error-responder.js#L23-L58
train