id
int32
0
58k
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
11,300
emmetio/emmet
lib/action/updateTag.js
function(editor, abbr) { abbr = abbr || editor.prompt("Enter abbreviation"); if (!abbr) { return false; } var content = editor.getContent(); var ctx = actionUtils.captureContext(editor); var tag = this.getUpdatedTag(abbr, ctx, content); if (!tag) { // nothing to update return false; } // check if tag name was updated if (tag.name() != ctx.name && ctx.match.close) { editor.replaceContent('</' + tag.name() + '>', ctx.match.close.range.start, ctx.match.close.range.end, true); } editor.replaceContent(tag.source, ctx.match.open.range.start, ctx.match.open.range.end, true); return true; }
javascript
function(editor, abbr) { abbr = abbr || editor.prompt("Enter abbreviation"); if (!abbr) { return false; } var content = editor.getContent(); var ctx = actionUtils.captureContext(editor); var tag = this.getUpdatedTag(abbr, ctx, content); if (!tag) { // nothing to update return false; } // check if tag name was updated if (tag.name() != ctx.name && ctx.match.close) { editor.replaceContent('</' + tag.name() + '>', ctx.match.close.range.start, ctx.match.close.range.end, true); } editor.replaceContent(tag.source, ctx.match.open.range.start, ctx.match.open.range.end, true); return true; }
[ "function", "(", "editor", ",", "abbr", ")", "{", "abbr", "=", "abbr", "||", "editor", ".", "prompt", "(", "\"Enter abbreviation\"", ")", ";", "if", "(", "!", "abbr", ")", "{", "return", "false", ";", "}", "var", "content", "=", "editor", ".", "getContent", "(", ")", ";", "var", "ctx", "=", "actionUtils", ".", "captureContext", "(", "editor", ")", ";", "var", "tag", "=", "this", ".", "getUpdatedTag", "(", "abbr", ",", "ctx", ",", "content", ")", ";", "if", "(", "!", "tag", ")", "{", "// nothing to update", "return", "false", ";", "}", "// check if tag name was updated", "if", "(", "tag", ".", "name", "(", ")", "!=", "ctx", ".", "name", "&&", "ctx", ".", "match", ".", "close", ")", "{", "editor", ".", "replaceContent", "(", "'</'", "+", "tag", ".", "name", "(", ")", "+", "'>'", ",", "ctx", ".", "match", ".", "close", ".", "range", ".", "start", ",", "ctx", ".", "match", ".", "close", ".", "range", ".", "end", ",", "true", ")", ";", "}", "editor", ".", "replaceContent", "(", "tag", ".", "source", ",", "ctx", ".", "match", ".", "open", ".", "range", ".", "start", ",", "ctx", ".", "match", ".", "open", ".", "range", ".", "end", ",", "true", ")", ";", "return", "true", ";", "}" ]
Matches HTML tag under caret and updates its definition according to given abbreviation @param {IEmmetEditor} Editor instance @param {String} abbr Abbreviation to update with
[ "Matches", "HTML", "tag", "under", "caret", "and", "updates", "its", "definition", "according", "to", "given", "abbreviation" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/action/updateTag.js#L75-L98
11,301
emmetio/emmet
lib/action/updateTag.js
function(abbr, ctx, content, options) { if (!ctx) { // nothing to update return null; } var tree = parser.parse(abbr, options || {}); // for this action some characters in abbreviation has special // meaning. For example, `.-c2` means “remove `c2` class from // element” and `.+c3` means “append class `c3` to exising one. // // But `.+c3` abbreviation will actually produce two elements: // <div class=""> and <c3>. Thus, we have to walk on each element // of parsed tree and use their definitions to update current element var tag = xmlEditTree.parse(ctx.match.open.range.substring(content), { offset: ctx.match.outerRange.start }); tree.children.forEach(function(node, i) { updateAttributes(tag, node, i); }); // if tag name was resolved by implicit tag name resolver, // then user omitted it in abbreviation and wants to keep // original tag name var el = tree.children[0]; if (!el.data('nameResolved')) { tag.name(el.name()); } return tag; }
javascript
function(abbr, ctx, content, options) { if (!ctx) { // nothing to update return null; } var tree = parser.parse(abbr, options || {}); // for this action some characters in abbreviation has special // meaning. For example, `.-c2` means “remove `c2` class from // element” and `.+c3` means “append class `c3` to exising one. // // But `.+c3` abbreviation will actually produce two elements: // <div class=""> and <c3>. Thus, we have to walk on each element // of parsed tree and use their definitions to update current element var tag = xmlEditTree.parse(ctx.match.open.range.substring(content), { offset: ctx.match.outerRange.start }); tree.children.forEach(function(node, i) { updateAttributes(tag, node, i); }); // if tag name was resolved by implicit tag name resolver, // then user omitted it in abbreviation and wants to keep // original tag name var el = tree.children[0]; if (!el.data('nameResolved')) { tag.name(el.name()); } return tag; }
[ "function", "(", "abbr", ",", "ctx", ",", "content", ",", "options", ")", "{", "if", "(", "!", "ctx", ")", "{", "// nothing to update", "return", "null", ";", "}", "var", "tree", "=", "parser", ".", "parse", "(", "abbr", ",", "options", "||", "{", "}", ")", ";", "// for this action some characters in abbreviation has special", "// meaning. For example, `.-c2` means “remove `c2` class from", "// element” and `.+c3` means “append class `c3` to exising one.", "// ", "// But `.+c3` abbreviation will actually produce two elements:", "// <div class=\"\"> and <c3>. Thus, we have to walk on each element", "// of parsed tree and use their definitions to update current element", "var", "tag", "=", "xmlEditTree", ".", "parse", "(", "ctx", ".", "match", ".", "open", ".", "range", ".", "substring", "(", "content", ")", ",", "{", "offset", ":", "ctx", ".", "match", ".", "outerRange", ".", "start", "}", ")", ";", "tree", ".", "children", ".", "forEach", "(", "function", "(", "node", ",", "i", ")", "{", "updateAttributes", "(", "tag", ",", "node", ",", "i", ")", ";", "}", ")", ";", "// if tag name was resolved by implicit tag name resolver,", "// then user omitted it in abbreviation and wants to keep", "// original tag name", "var", "el", "=", "tree", ".", "children", "[", "0", "]", ";", "if", "(", "!", "el", ".", "data", "(", "'nameResolved'", ")", ")", "{", "tag", ".", "name", "(", "el", ".", "name", "(", ")", ")", ";", "}", "return", "tag", ";", "}" ]
Returns XMLEditContainer node with updated tag structure of existing tag context. This data can be used to modify existing tag @param {String} abbr Abbreviation @param {Object} ctx Tag to be updated (captured with `htmlMatcher`) @param {String} content Original editor content @return {XMLEditContainer}
[ "Returns", "XMLEditContainer", "node", "with", "updated", "tag", "structure", "of", "existing", "tag", "context", ".", "This", "data", "can", "be", "used", "to", "modify", "existing", "tag" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/action/updateTag.js#L109-L141
11,302
emmetio/emmet
lib/action/base64.js
encodeToBase64
function encodeToBase64(editor, imgPath, pos) { var editorFile = editor.getFilePath(); var defaultMimeType = 'application/octet-stream'; if (editorFile === null) { throw "You should save your file before using this action"; } // locate real image path file.locateFile(editorFile, imgPath, function(realImgPath) { if (realImgPath === null) { throw "Can't find " + imgPath + ' file'; } file.read(realImgPath, function(err, content) { if (err) { throw 'Unable to read ' + realImgPath + ': ' + err; } var b64 = base64.encode(String(content)); if (!b64) { throw "Can't encode file content to base64"; } b64 = 'data:' + (actionUtils.mimeTypes[String(file.getExt(realImgPath))] || defaultMimeType) + ';base64,' + b64; editor.replaceContent('$0' + b64, pos, pos + imgPath.length); }); }); return true; }
javascript
function encodeToBase64(editor, imgPath, pos) { var editorFile = editor.getFilePath(); var defaultMimeType = 'application/octet-stream'; if (editorFile === null) { throw "You should save your file before using this action"; } // locate real image path file.locateFile(editorFile, imgPath, function(realImgPath) { if (realImgPath === null) { throw "Can't find " + imgPath + ' file'; } file.read(realImgPath, function(err, content) { if (err) { throw 'Unable to read ' + realImgPath + ': ' + err; } var b64 = base64.encode(String(content)); if (!b64) { throw "Can't encode file content to base64"; } b64 = 'data:' + (actionUtils.mimeTypes[String(file.getExt(realImgPath))] || defaultMimeType) + ';base64,' + b64; editor.replaceContent('$0' + b64, pos, pos + imgPath.length); }); }); return true; }
[ "function", "encodeToBase64", "(", "editor", ",", "imgPath", ",", "pos", ")", "{", "var", "editorFile", "=", "editor", ".", "getFilePath", "(", ")", ";", "var", "defaultMimeType", "=", "'application/octet-stream'", ";", "if", "(", "editorFile", "===", "null", ")", "{", "throw", "\"You should save your file before using this action\"", ";", "}", "// locate real image path", "file", ".", "locateFile", "(", "editorFile", ",", "imgPath", ",", "function", "(", "realImgPath", ")", "{", "if", "(", "realImgPath", "===", "null", ")", "{", "throw", "\"Can't find \"", "+", "imgPath", "+", "' file'", ";", "}", "file", ".", "read", "(", "realImgPath", ",", "function", "(", "err", ",", "content", ")", "{", "if", "(", "err", ")", "{", "throw", "'Unable to read '", "+", "realImgPath", "+", "': '", "+", "err", ";", "}", "var", "b64", "=", "base64", ".", "encode", "(", "String", "(", "content", ")", ")", ";", "if", "(", "!", "b64", ")", "{", "throw", "\"Can't encode file content to base64\"", ";", "}", "b64", "=", "'data:'", "+", "(", "actionUtils", ".", "mimeTypes", "[", "String", "(", "file", ".", "getExt", "(", "realImgPath", ")", ")", "]", "||", "defaultMimeType", ")", "+", "';base64,'", "+", "b64", ";", "editor", ".", "replaceContent", "(", "'$0'", "+", "b64", ",", "pos", ",", "pos", "+", "imgPath", ".", "length", ")", ";", "}", ")", ";", "}", ")", ";", "return", "true", ";", "}" ]
Encodes image to base64 @param {IEmmetEditor} editor @param {String} imgPath Path to image @param {Number} pos Caret position where image is located in the editor @return {Boolean}
[ "Encodes", "image", "to", "base64" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/action/base64.js#L39-L71
11,303
emmetio/emmet
lib/action/base64.js
decodeFromBase64
function decodeFromBase64(editor, filePath, data, pos) { // ask user to enter path to file filePath = filePath || String(editor.prompt('Enter path to file (absolute or relative)')); if (!filePath) { return false; } var editorFile = editor.getFilePath(); file.createPath(editorFile, filePath, function(err, absPath) { if (err || !absPath) { throw "Can't save file"; } var content = data.replace(/^data\:.+?;.+?,/, ''); file.save(absPath, base64.decode(content), function(err) { if (err) { throw 'Unable to save ' + absPath + ': ' + err; } editor.replaceContent('$0' + filePath, pos, pos + data.length); }); }); return true; }
javascript
function decodeFromBase64(editor, filePath, data, pos) { // ask user to enter path to file filePath = filePath || String(editor.prompt('Enter path to file (absolute or relative)')); if (!filePath) { return false; } var editorFile = editor.getFilePath(); file.createPath(editorFile, filePath, function(err, absPath) { if (err || !absPath) { throw "Can't save file"; } var content = data.replace(/^data\:.+?;.+?,/, ''); file.save(absPath, base64.decode(content), function(err) { if (err) { throw 'Unable to save ' + absPath + ': ' + err; } editor.replaceContent('$0' + filePath, pos, pos + data.length); }); }); return true; }
[ "function", "decodeFromBase64", "(", "editor", ",", "filePath", ",", "data", ",", "pos", ")", "{", "// ask user to enter path to file", "filePath", "=", "filePath", "||", "String", "(", "editor", ".", "prompt", "(", "'Enter path to file (absolute or relative)'", ")", ")", ";", "if", "(", "!", "filePath", ")", "{", "return", "false", ";", "}", "var", "editorFile", "=", "editor", ".", "getFilePath", "(", ")", ";", "file", ".", "createPath", "(", "editorFile", ",", "filePath", ",", "function", "(", "err", ",", "absPath", ")", "{", "if", "(", "err", "||", "!", "absPath", ")", "{", "throw", "\"Can't save file\"", ";", "}", "var", "content", "=", "data", ".", "replace", "(", "/", "^data\\:.+?;.+?,", "/", ",", "''", ")", ";", "file", ".", "save", "(", "absPath", ",", "base64", ".", "decode", "(", "content", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "'Unable to save '", "+", "absPath", "+", "': '", "+", "err", ";", "}", "editor", ".", "replaceContent", "(", "'$0'", "+", "filePath", ",", "pos", ",", "pos", "+", "data", ".", "length", ")", ";", "}", ")", ";", "}", ")", ";", "return", "true", ";", "}" ]
Decodes base64 string back to file. @param {IEmmetEditor} editor @param {String} filePath to new image @param {String} data Base64-encoded file content @param {Number} pos Caret position where image is located in the editor
[ "Decodes", "base64", "string", "back", "to", "file", "." ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/action/base64.js#L80-L104
11,304
emmetio/emmet
lib/action/balance.js
getCSSRanges
function getCSSRanges(content, pos) { var rule; if (typeof content === 'string') { var ruleRange = cssSections.matchEnclosingRule(content, pos); if (ruleRange) { rule = cssEditTree.parse(ruleRange.substring(content), { offset: ruleRange.start }); } } else { // passed parsed CSS rule rule = content; } if (!rule) { return null; } // find all possible ranges var ranges = rangesForCSSRule(rule, pos); // remove empty ranges ranges = ranges.filter(function(item) { return !!item.length; }); return utils.unique(ranges, function(item) { return item.valueOf(); }); }
javascript
function getCSSRanges(content, pos) { var rule; if (typeof content === 'string') { var ruleRange = cssSections.matchEnclosingRule(content, pos); if (ruleRange) { rule = cssEditTree.parse(ruleRange.substring(content), { offset: ruleRange.start }); } } else { // passed parsed CSS rule rule = content; } if (!rule) { return null; } // find all possible ranges var ranges = rangesForCSSRule(rule, pos); // remove empty ranges ranges = ranges.filter(function(item) { return !!item.length; }); return utils.unique(ranges, function(item) { return item.valueOf(); }); }
[ "function", "getCSSRanges", "(", "content", ",", "pos", ")", "{", "var", "rule", ";", "if", "(", "typeof", "content", "===", "'string'", ")", "{", "var", "ruleRange", "=", "cssSections", ".", "matchEnclosingRule", "(", "content", ",", "pos", ")", ";", "if", "(", "ruleRange", ")", "{", "rule", "=", "cssEditTree", ".", "parse", "(", "ruleRange", ".", "substring", "(", "content", ")", ",", "{", "offset", ":", "ruleRange", ".", "start", "}", ")", ";", "}", "}", "else", "{", "// passed parsed CSS rule", "rule", "=", "content", ";", "}", "if", "(", "!", "rule", ")", "{", "return", "null", ";", "}", "// find all possible ranges", "var", "ranges", "=", "rangesForCSSRule", "(", "rule", ",", "pos", ")", ";", "// remove empty ranges", "ranges", "=", "ranges", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "!", "!", "item", ".", "length", ";", "}", ")", ";", "return", "utils", ".", "unique", "(", "ranges", ",", "function", "(", "item", ")", "{", "return", "item", ".", "valueOf", "(", ")", ";", "}", ")", ";", "}" ]
Returns all possible selection ranges for given caret position @param {String} content CSS content @param {Number} pos Caret position(where to start searching) @return {Array}
[ "Returns", "all", "possible", "selection", "ranges", "for", "given", "caret", "position" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/action/balance.js#L138-L167
11,305
emmetio/emmet
lib/action/balance.js
function(editor, direction) { direction = String((direction || 'out').toLowerCase()); var info = editorUtils.outputInfo(editor); if (actionUtils.isSupportedCSS(info.syntax)) { return balanceCSS(editor, direction); } return balanceHTML(editor, direction); }
javascript
function(editor, direction) { direction = String((direction || 'out').toLowerCase()); var info = editorUtils.outputInfo(editor); if (actionUtils.isSupportedCSS(info.syntax)) { return balanceCSS(editor, direction); } return balanceHTML(editor, direction); }
[ "function", "(", "editor", ",", "direction", ")", "{", "direction", "=", "String", "(", "(", "direction", "||", "'out'", ")", ".", "toLowerCase", "(", ")", ")", ";", "var", "info", "=", "editorUtils", ".", "outputInfo", "(", "editor", ")", ";", "if", "(", "actionUtils", ".", "isSupportedCSS", "(", "info", ".", "syntax", ")", ")", "{", "return", "balanceCSS", "(", "editor", ",", "direction", ")", ";", "}", "return", "balanceHTML", "(", "editor", ",", "direction", ")", ";", "}" ]
Find and select HTML tag pair @param {IEmmetEditor} editor Editor instance @param {String} direction Direction of pair matching: 'in' or 'out'. Default is 'out'
[ "Find", "and", "select", "HTML", "tag", "pair" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/action/balance.js#L252-L260
11,306
emmetio/emmet
lib/resolver/cssGradient.js
getGradientPrefixes
function getGradientPrefixes(type) { var prefixes = cssResolver.vendorPrefixes(type); if (!prefixes) { // disabled Can I Use, fallback to property list prefixes = prefs.getArray('css.gradient.prefixes'); } return prefixes || []; }
javascript
function getGradientPrefixes(type) { var prefixes = cssResolver.vendorPrefixes(type); if (!prefixes) { // disabled Can I Use, fallback to property list prefixes = prefs.getArray('css.gradient.prefixes'); } return prefixes || []; }
[ "function", "getGradientPrefixes", "(", "type", ")", "{", "var", "prefixes", "=", "cssResolver", ".", "vendorPrefixes", "(", "type", ")", ";", "if", "(", "!", "prefixes", ")", "{", "// disabled Can I Use, fallback to property list", "prefixes", "=", "prefs", ".", "getArray", "(", "'css.gradient.prefixes'", ")", ";", "}", "return", "prefixes", "||", "[", "]", ";", "}" ]
Returns vendor prefixes for given gradient type @param {String} type Gradient type (currently, 'linear-gradient' is the only supported value) @return {Array}
[ "Returns", "vendor", "prefixes", "for", "given", "gradient", "type" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/cssGradient.js#L71-L79
11,307
emmetio/emmet
lib/resolver/cssGradient.js
getPropertiesForGradient
function getPropertiesForGradient(gradients, property) { var props = []; var propertyName = property.name(); var omitDir = prefs.get('css.gradient.omitDefaultDirection'); if (prefs.get('css.gradient.fallback') && ~propertyName.toLowerCase().indexOf('background')) { props.push({ name: 'background-color', value: '${1:' + gradients[0].gradient.colorStops[0].color + '}' }); } var value = property.value(); getGradientPrefixes('linear-gradient').forEach(function(prefix) { var name = cssResolver.prefixed(propertyName, prefix); if (prefix == 'webkit' && prefs.get('css.gradient.oldWebkit')) { try { props.push({ name: name, value: insertGradientsIntoCSSValue(gradients, value, { prefix: prefix, oldWebkit: true, omitDefaultDirection: omitDir }) }); } catch(e) {} } props.push({ name: name, value: insertGradientsIntoCSSValue(gradients, value, { prefix: prefix, omitDefaultDirection: omitDir }) }); }); return props.sort(function(a, b) { return b.name.length - a.name.length; }); }
javascript
function getPropertiesForGradient(gradients, property) { var props = []; var propertyName = property.name(); var omitDir = prefs.get('css.gradient.omitDefaultDirection'); if (prefs.get('css.gradient.fallback') && ~propertyName.toLowerCase().indexOf('background')) { props.push({ name: 'background-color', value: '${1:' + gradients[0].gradient.colorStops[0].color + '}' }); } var value = property.value(); getGradientPrefixes('linear-gradient').forEach(function(prefix) { var name = cssResolver.prefixed(propertyName, prefix); if (prefix == 'webkit' && prefs.get('css.gradient.oldWebkit')) { try { props.push({ name: name, value: insertGradientsIntoCSSValue(gradients, value, { prefix: prefix, oldWebkit: true, omitDefaultDirection: omitDir }) }); } catch(e) {} } props.push({ name: name, value: insertGradientsIntoCSSValue(gradients, value, { prefix: prefix, omitDefaultDirection: omitDir }) }); }); return props.sort(function(a, b) { return b.name.length - a.name.length; }); }
[ "function", "getPropertiesForGradient", "(", "gradients", ",", "property", ")", "{", "var", "props", "=", "[", "]", ";", "var", "propertyName", "=", "property", ".", "name", "(", ")", ";", "var", "omitDir", "=", "prefs", ".", "get", "(", "'css.gradient.omitDefaultDirection'", ")", ";", "if", "(", "prefs", ".", "get", "(", "'css.gradient.fallback'", ")", "&&", "~", "propertyName", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "'background'", ")", ")", "{", "props", ".", "push", "(", "{", "name", ":", "'background-color'", ",", "value", ":", "'${1:'", "+", "gradients", "[", "0", "]", ".", "gradient", ".", "colorStops", "[", "0", "]", ".", "color", "+", "'}'", "}", ")", ";", "}", "var", "value", "=", "property", ".", "value", "(", ")", ";", "getGradientPrefixes", "(", "'linear-gradient'", ")", ".", "forEach", "(", "function", "(", "prefix", ")", "{", "var", "name", "=", "cssResolver", ".", "prefixed", "(", "propertyName", ",", "prefix", ")", ";", "if", "(", "prefix", "==", "'webkit'", "&&", "prefs", ".", "get", "(", "'css.gradient.oldWebkit'", ")", ")", "{", "try", "{", "props", ".", "push", "(", "{", "name", ":", "name", ",", "value", ":", "insertGradientsIntoCSSValue", "(", "gradients", ",", "value", ",", "{", "prefix", ":", "prefix", ",", "oldWebkit", ":", "true", ",", "omitDefaultDirection", ":", "omitDir", "}", ")", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "props", ".", "push", "(", "{", "name", ":", "name", ",", "value", ":", "insertGradientsIntoCSSValue", "(", "gradients", ",", "value", ",", "{", "prefix", ":", "prefix", ",", "omitDefaultDirection", ":", "omitDir", "}", ")", "}", ")", ";", "}", ")", ";", "return", "props", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", ".", "name", ".", "length", "-", "a", ".", "name", ".", "length", ";", "}", ")", ";", "}" ]
Returns list of CSS properties with gradient @param {Array} gradient List of gradient objects @param {CSSEditElement} property Original CSS property @returns {Array}
[ "Returns", "list", "of", "CSS", "properties", "with", "gradient" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/cssGradient.js#L100-L140
11,308
emmetio/emmet
lib/resolver/cssGradient.js
insertGradientsIntoCSSValue
function insertGradientsIntoCSSValue(gradients, value, options) { // gradients *should* passed in order they actually appear in CSS property // iterate over it in backward direction to preserve gradient locations options = options || {}; gradients = utils.clone(gradients); gradients.reverse().forEach(function(item, i) { var suffix = !i && options.placeholder ? options.placeholder : ''; var str = options.oldWebkit ? item.gradient.stringifyOldWebkit(options) : item.gradient.stringify(options); value = utils.replaceSubstring(value, str + suffix, item.matchedPart); }); return value; }
javascript
function insertGradientsIntoCSSValue(gradients, value, options) { // gradients *should* passed in order they actually appear in CSS property // iterate over it in backward direction to preserve gradient locations options = options || {}; gradients = utils.clone(gradients); gradients.reverse().forEach(function(item, i) { var suffix = !i && options.placeholder ? options.placeholder : ''; var str = options.oldWebkit ? item.gradient.stringifyOldWebkit(options) : item.gradient.stringify(options); value = utils.replaceSubstring(value, str + suffix, item.matchedPart); }); return value; }
[ "function", "insertGradientsIntoCSSValue", "(", "gradients", ",", "value", ",", "options", ")", "{", "// gradients *should* passed in order they actually appear in CSS property", "// iterate over it in backward direction to preserve gradient locations", "options", "=", "options", "||", "{", "}", ";", "gradients", "=", "utils", ".", "clone", "(", "gradients", ")", ";", "gradients", ".", "reverse", "(", ")", ".", "forEach", "(", "function", "(", "item", ",", "i", ")", "{", "var", "suffix", "=", "!", "i", "&&", "options", ".", "placeholder", "?", "options", ".", "placeholder", ":", "''", ";", "var", "str", "=", "options", ".", "oldWebkit", "?", "item", ".", "gradient", ".", "stringifyOldWebkit", "(", "options", ")", ":", "item", ".", "gradient", ".", "stringify", "(", "options", ")", ";", "value", "=", "utils", ".", "replaceSubstring", "(", "value", ",", "str", "+", "suffix", ",", "item", ".", "matchedPart", ")", ";", "}", ")", ";", "return", "value", ";", "}" ]
Replaces old gradient definitions in given CSS property value with new ones, preserving original formatting @param {Array} gradients List of CSS gradients @param {String} value Original CSS value @param {Object} options Options for gradient’s stringify() method @return {String}
[ "Replaces", "old", "gradient", "definitions", "in", "given", "CSS", "property", "value", "with", "new", "ones", "preserving", "original", "formatting" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/cssGradient.js#L150-L162
11,309
emmetio/emmet
lib/resolver/cssGradient.js
pasteGradient
function pasteGradient(property, gradients) { var rule = property.parent; var alignVendor = prefs.get('css.alignVendor'); var omitDir = prefs.get('css.gradient.omitDefaultDirection'); // we may have aligned gradient definitions: find the smallest value // separator var sep = property.styleSeparator; var before = property.styleBefore; // first, remove all properties within CSS rule with the same name and // gradient definition rule.getAll(similarPropertyNames(property)).forEach(function(item) { if (item != property && /gradient/i.test(item.value())) { if (item.styleSeparator.length < sep.length) { sep = item.styleSeparator; } if (item.styleBefore.length < before.length) { before = item.styleBefore; } rule.remove(item); } }); if (alignVendor) { // update prefix if (before != property.styleBefore) { var fullRange = property.fullRange(); rule._updateSource(before, fullRange.start, fullRange.start + property.styleBefore.length); property.styleBefore = before; } // update separator value if (sep != property.styleSeparator) { rule._updateSource(sep, property.nameRange().end, property.valueRange().start); property.styleSeparator = sep; } } var value = property.value(); // create list of properties to insert var propsToInsert = getPropertiesForGradient(gradients, property); // align prefixed values if (alignVendor) { var names = [], values = []; propsToInsert.forEach(function(item) { names.push(item.name); values.push(item.value); }); values.push(property.value()); names.push(property.name()); var valuePads = utils.getStringsPads(values.map(function(v) { return v.substring(0, v.indexOf('(')); })); var namePads = utils.getStringsPads(names); property.name(namePads[namePads.length - 1] + property.name()); propsToInsert.forEach(function(prop, i) { prop.name = namePads[i] + prop.name; prop.value = valuePads[i] + prop.value; }); property.value(valuePads[valuePads.length - 1] + property.value()); } // put vendor-prefixed definitions before current rule propsToInsert.forEach(function(prop) { rule.add(prop.name, prop.value, rule.indexOf(property)); }); // put vanilla-clean gradient definition into current rule property.value(insertGradientsIntoCSSValue(gradients, value, { placeholder: '${2}', omitDefaultDirection: omitDir })); }
javascript
function pasteGradient(property, gradients) { var rule = property.parent; var alignVendor = prefs.get('css.alignVendor'); var omitDir = prefs.get('css.gradient.omitDefaultDirection'); // we may have aligned gradient definitions: find the smallest value // separator var sep = property.styleSeparator; var before = property.styleBefore; // first, remove all properties within CSS rule with the same name and // gradient definition rule.getAll(similarPropertyNames(property)).forEach(function(item) { if (item != property && /gradient/i.test(item.value())) { if (item.styleSeparator.length < sep.length) { sep = item.styleSeparator; } if (item.styleBefore.length < before.length) { before = item.styleBefore; } rule.remove(item); } }); if (alignVendor) { // update prefix if (before != property.styleBefore) { var fullRange = property.fullRange(); rule._updateSource(before, fullRange.start, fullRange.start + property.styleBefore.length); property.styleBefore = before; } // update separator value if (sep != property.styleSeparator) { rule._updateSource(sep, property.nameRange().end, property.valueRange().start); property.styleSeparator = sep; } } var value = property.value(); // create list of properties to insert var propsToInsert = getPropertiesForGradient(gradients, property); // align prefixed values if (alignVendor) { var names = [], values = []; propsToInsert.forEach(function(item) { names.push(item.name); values.push(item.value); }); values.push(property.value()); names.push(property.name()); var valuePads = utils.getStringsPads(values.map(function(v) { return v.substring(0, v.indexOf('(')); })); var namePads = utils.getStringsPads(names); property.name(namePads[namePads.length - 1] + property.name()); propsToInsert.forEach(function(prop, i) { prop.name = namePads[i] + prop.name; prop.value = valuePads[i] + prop.value; }); property.value(valuePads[valuePads.length - 1] + property.value()); } // put vendor-prefixed definitions before current rule propsToInsert.forEach(function(prop) { rule.add(prop.name, prop.value, rule.indexOf(property)); }); // put vanilla-clean gradient definition into current rule property.value(insertGradientsIntoCSSValue(gradients, value, { placeholder: '${2}', omitDefaultDirection: omitDir })); }
[ "function", "pasteGradient", "(", "property", ",", "gradients", ")", "{", "var", "rule", "=", "property", ".", "parent", ";", "var", "alignVendor", "=", "prefs", ".", "get", "(", "'css.alignVendor'", ")", ";", "var", "omitDir", "=", "prefs", ".", "get", "(", "'css.gradient.omitDefaultDirection'", ")", ";", "// we may have aligned gradient definitions: find the smallest value", "// separator", "var", "sep", "=", "property", ".", "styleSeparator", ";", "var", "before", "=", "property", ".", "styleBefore", ";", "// first, remove all properties within CSS rule with the same name and", "// gradient definition", "rule", ".", "getAll", "(", "similarPropertyNames", "(", "property", ")", ")", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "item", "!=", "property", "&&", "/", "gradient", "/", "i", ".", "test", "(", "item", ".", "value", "(", ")", ")", ")", "{", "if", "(", "item", ".", "styleSeparator", ".", "length", "<", "sep", ".", "length", ")", "{", "sep", "=", "item", ".", "styleSeparator", ";", "}", "if", "(", "item", ".", "styleBefore", ".", "length", "<", "before", ".", "length", ")", "{", "before", "=", "item", ".", "styleBefore", ";", "}", "rule", ".", "remove", "(", "item", ")", ";", "}", "}", ")", ";", "if", "(", "alignVendor", ")", "{", "// update prefix", "if", "(", "before", "!=", "property", ".", "styleBefore", ")", "{", "var", "fullRange", "=", "property", ".", "fullRange", "(", ")", ";", "rule", ".", "_updateSource", "(", "before", ",", "fullRange", ".", "start", ",", "fullRange", ".", "start", "+", "property", ".", "styleBefore", ".", "length", ")", ";", "property", ".", "styleBefore", "=", "before", ";", "}", "// update separator value", "if", "(", "sep", "!=", "property", ".", "styleSeparator", ")", "{", "rule", ".", "_updateSource", "(", "sep", ",", "property", ".", "nameRange", "(", ")", ".", "end", ",", "property", ".", "valueRange", "(", ")", ".", "start", ")", ";", "property", ".", "styleSeparator", "=", "sep", ";", "}", "}", "var", "value", "=", "property", ".", "value", "(", ")", ";", "// create list of properties to insert", "var", "propsToInsert", "=", "getPropertiesForGradient", "(", "gradients", ",", "property", ")", ";", "// align prefixed values", "if", "(", "alignVendor", ")", "{", "var", "names", "=", "[", "]", ",", "values", "=", "[", "]", ";", "propsToInsert", ".", "forEach", "(", "function", "(", "item", ")", "{", "names", ".", "push", "(", "item", ".", "name", ")", ";", "values", ".", "push", "(", "item", ".", "value", ")", ";", "}", ")", ";", "values", ".", "push", "(", "property", ".", "value", "(", ")", ")", ";", "names", ".", "push", "(", "property", ".", "name", "(", ")", ")", ";", "var", "valuePads", "=", "utils", ".", "getStringsPads", "(", "values", ".", "map", "(", "function", "(", "v", ")", "{", "return", "v", ".", "substring", "(", "0", ",", "v", ".", "indexOf", "(", "'('", ")", ")", ";", "}", ")", ")", ";", "var", "namePads", "=", "utils", ".", "getStringsPads", "(", "names", ")", ";", "property", ".", "name", "(", "namePads", "[", "namePads", ".", "length", "-", "1", "]", "+", "property", ".", "name", "(", ")", ")", ";", "propsToInsert", ".", "forEach", "(", "function", "(", "prop", ",", "i", ")", "{", "prop", ".", "name", "=", "namePads", "[", "i", "]", "+", "prop", ".", "name", ";", "prop", ".", "value", "=", "valuePads", "[", "i", "]", "+", "prop", ".", "value", ";", "}", ")", ";", "property", ".", "value", "(", "valuePads", "[", "valuePads", ".", "length", "-", "1", "]", "+", "property", ".", "value", "(", ")", ")", ";", "}", "// put vendor-prefixed definitions before current rule", "propsToInsert", ".", "forEach", "(", "function", "(", "prop", ")", "{", "rule", ".", "add", "(", "prop", ".", "name", ",", "prop", ".", "value", ",", "rule", ".", "indexOf", "(", "property", ")", ")", ";", "}", ")", ";", "// put vanilla-clean gradient definition into current rule", "property", ".", "value", "(", "insertGradientsIntoCSSValue", "(", "gradients", ",", "value", ",", "{", "placeholder", ":", "'${2}'", ",", "omitDefaultDirection", ":", "omitDir", "}", ")", ")", ";", "}" ]
Pastes gradient definition into CSS rule with correct vendor-prefixes @param {EditElement} property Matched CSS property @param {Array} gradients List of gradients to insert
[ "Pastes", "gradient", "definition", "into", "CSS", "rule", "with", "correct", "vendor", "-", "prefixes" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/cssGradient.js#L187-L266
11,310
emmetio/emmet
lib/resolver/cssGradient.js
function(cssProp) { var value = cssProp.value(); var gradients = []; var that = this; cssProp.valueParts().forEach(function(part) { var partValue = part.substring(value); if (linearGradient.isLinearGradient(partValue)) { var gradient = linearGradient.parse(partValue); if (gradient) { gradients.push({ gradient: gradient, matchedPart: part }); } } }); return gradients.length ? gradients : null; }
javascript
function(cssProp) { var value = cssProp.value(); var gradients = []; var that = this; cssProp.valueParts().forEach(function(part) { var partValue = part.substring(value); if (linearGradient.isLinearGradient(partValue)) { var gradient = linearGradient.parse(partValue); if (gradient) { gradients.push({ gradient: gradient, matchedPart: part }); } } }); return gradients.length ? gradients : null; }
[ "function", "(", "cssProp", ")", "{", "var", "value", "=", "cssProp", ".", "value", "(", ")", ";", "var", "gradients", "=", "[", "]", ";", "var", "that", "=", "this", ";", "cssProp", ".", "valueParts", "(", ")", ".", "forEach", "(", "function", "(", "part", ")", "{", "var", "partValue", "=", "part", ".", "substring", "(", "value", ")", ";", "if", "(", "linearGradient", ".", "isLinearGradient", "(", "partValue", ")", ")", "{", "var", "gradient", "=", "linearGradient", ".", "parse", "(", "partValue", ")", ";", "if", "(", "gradient", ")", "{", "gradients", ".", "push", "(", "{", "gradient", ":", "gradient", ",", "matchedPart", ":", "part", "}", ")", ";", "}", "}", "}", ")", ";", "return", "gradients", ".", "length", "?", "gradients", ":", "null", ";", "}" ]
Search for gradient definitions inside CSS property value @returns {Array} Array of matched gradients
[ "Search", "for", "gradient", "definitions", "inside", "CSS", "property", "value" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/cssGradient.js#L307-L325
11,311
emmetio/emmet
lib/resolver/cssGradient.js
function(editor, syntax) { var propertyName = prefs.get('css.gradient.defaultProperty'); var omitDir = prefs.get('css.gradient.omitDefaultDirection'); if (!propertyName) { return false; } // assuming that gradient definition is written on new line, // do a simplified parsing var content = String(editor.getContent()); /** @type Range */ var lineRange = range.create(editor.getCurrentLineRange()); // get line content and adjust range with padding var line = lineRange.substring(content) .replace(/^\s+/, function(pad) { lineRange.start += pad.length; return ''; }) .replace(/\s+$/, function(pad) { lineRange.end -= pad.length; return ''; }); // trick parser: make it think that we’re parsing actual CSS property var fakeCSS = 'a{' + propertyName + ': ' + line + ';}'; var gradients = this.gradientsFromCSSProperty(fakeCSS, fakeCSS.length - 2); if (gradients) { var props = getPropertiesForGradient(gradients.gradients, gradients.property); props.push({ name: gradients.property.name(), value: insertGradientsIntoCSSValue(gradients.gradients, gradients.property.value(), { placeholder: '${2}', omitDefaultDirection: omitDir }) }); var sep = cssResolver.getSyntaxPreference('valueSeparator', syntax); var end = cssResolver.getSyntaxPreference('propertyEnd', syntax); if (prefs.get('css.alignVendor')) { var pads = utils.getStringsPads(props.map(function(prop) { return prop.value.substring(0, prop.value.indexOf('(')); })); props.forEach(function(prop, i) { prop.value = pads[i] + prop.value; }); } props = props.map(function(item) { return item.name + sep + item.value + end; }); editor.replaceContent(props.join('\n'), lineRange.start, lineRange.end); return true; } return false; }
javascript
function(editor, syntax) { var propertyName = prefs.get('css.gradient.defaultProperty'); var omitDir = prefs.get('css.gradient.omitDefaultDirection'); if (!propertyName) { return false; } // assuming that gradient definition is written on new line, // do a simplified parsing var content = String(editor.getContent()); /** @type Range */ var lineRange = range.create(editor.getCurrentLineRange()); // get line content and adjust range with padding var line = lineRange.substring(content) .replace(/^\s+/, function(pad) { lineRange.start += pad.length; return ''; }) .replace(/\s+$/, function(pad) { lineRange.end -= pad.length; return ''; }); // trick parser: make it think that we’re parsing actual CSS property var fakeCSS = 'a{' + propertyName + ': ' + line + ';}'; var gradients = this.gradientsFromCSSProperty(fakeCSS, fakeCSS.length - 2); if (gradients) { var props = getPropertiesForGradient(gradients.gradients, gradients.property); props.push({ name: gradients.property.name(), value: insertGradientsIntoCSSValue(gradients.gradients, gradients.property.value(), { placeholder: '${2}', omitDefaultDirection: omitDir }) }); var sep = cssResolver.getSyntaxPreference('valueSeparator', syntax); var end = cssResolver.getSyntaxPreference('propertyEnd', syntax); if (prefs.get('css.alignVendor')) { var pads = utils.getStringsPads(props.map(function(prop) { return prop.value.substring(0, prop.value.indexOf('(')); })); props.forEach(function(prop, i) { prop.value = pads[i] + prop.value; }); } props = props.map(function(item) { return item.name + sep + item.value + end; }); editor.replaceContent(props.join('\n'), lineRange.start, lineRange.end); return true; } return false; }
[ "function", "(", "editor", ",", "syntax", ")", "{", "var", "propertyName", "=", "prefs", ".", "get", "(", "'css.gradient.defaultProperty'", ")", ";", "var", "omitDir", "=", "prefs", ".", "get", "(", "'css.gradient.omitDefaultDirection'", ")", ";", "if", "(", "!", "propertyName", ")", "{", "return", "false", ";", "}", "// assuming that gradient definition is written on new line,", "// do a simplified parsing", "var", "content", "=", "String", "(", "editor", ".", "getContent", "(", ")", ")", ";", "/** @type Range */", "var", "lineRange", "=", "range", ".", "create", "(", "editor", ".", "getCurrentLineRange", "(", ")", ")", ";", "// get line content and adjust range with padding", "var", "line", "=", "lineRange", ".", "substring", "(", "content", ")", ".", "replace", "(", "/", "^\\s+", "/", ",", "function", "(", "pad", ")", "{", "lineRange", ".", "start", "+=", "pad", ".", "length", ";", "return", "''", ";", "}", ")", ".", "replace", "(", "/", "\\s+$", "/", ",", "function", "(", "pad", ")", "{", "lineRange", ".", "end", "-=", "pad", ".", "length", ";", "return", "''", ";", "}", ")", ";", "// trick parser: make it think that we’re parsing actual CSS property", "var", "fakeCSS", "=", "'a{'", "+", "propertyName", "+", "': '", "+", "line", "+", "';}'", ";", "var", "gradients", "=", "this", ".", "gradientsFromCSSProperty", "(", "fakeCSS", ",", "fakeCSS", ".", "length", "-", "2", ")", ";", "if", "(", "gradients", ")", "{", "var", "props", "=", "getPropertiesForGradient", "(", "gradients", ".", "gradients", ",", "gradients", ".", "property", ")", ";", "props", ".", "push", "(", "{", "name", ":", "gradients", ".", "property", ".", "name", "(", ")", ",", "value", ":", "insertGradientsIntoCSSValue", "(", "gradients", ".", "gradients", ",", "gradients", ".", "property", ".", "value", "(", ")", ",", "{", "placeholder", ":", "'${2}'", ",", "omitDefaultDirection", ":", "omitDir", "}", ")", "}", ")", ";", "var", "sep", "=", "cssResolver", ".", "getSyntaxPreference", "(", "'valueSeparator'", ",", "syntax", ")", ";", "var", "end", "=", "cssResolver", ".", "getSyntaxPreference", "(", "'propertyEnd'", ",", "syntax", ")", ";", "if", "(", "prefs", ".", "get", "(", "'css.alignVendor'", ")", ")", "{", "var", "pads", "=", "utils", ".", "getStringsPads", "(", "props", ".", "map", "(", "function", "(", "prop", ")", "{", "return", "prop", ".", "value", ".", "substring", "(", "0", ",", "prop", ".", "value", ".", "indexOf", "(", "'('", ")", ")", ";", "}", ")", ")", ";", "props", ".", "forEach", "(", "function", "(", "prop", ",", "i", ")", "{", "prop", ".", "value", "=", "pads", "[", "i", "]", "+", "prop", ".", "value", ";", "}", ")", ";", "}", "props", "=", "props", ".", "map", "(", "function", "(", "item", ")", "{", "return", "item", ".", "name", "+", "sep", "+", "item", ".", "value", "+", "end", ";", "}", ")", ";", "editor", ".", "replaceContent", "(", "props", ".", "join", "(", "'\\n'", ")", ",", "lineRange", ".", "start", ",", "lineRange", ".", "end", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Tries to expand gradient outside CSS value @param {IEmmetEditor} editor @param {String} syntax
[ "Tries", "to", "expand", "gradient", "outside", "CSS", "value" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/cssGradient.js#L416-L475
11,312
emmetio/emmet
lib/assets/handlerList.js
function(fn, options) { // TODO hack for stable sort, remove after fixing `list()` var order = this._list.length; if (options && 'order' in options) { order = options.order * 10000; } this._list.push(utils.extend({}, options, {order: order, fn: fn})); }
javascript
function(fn, options) { // TODO hack for stable sort, remove after fixing `list()` var order = this._list.length; if (options && 'order' in options) { order = options.order * 10000; } this._list.push(utils.extend({}, options, {order: order, fn: fn})); }
[ "function", "(", "fn", ",", "options", ")", "{", "// TODO hack for stable sort, remove after fixing `list()`", "var", "order", "=", "this", ".", "_list", ".", "length", ";", "if", "(", "options", "&&", "'order'", "in", "options", ")", "{", "order", "=", "options", ".", "order", "*", "10000", ";", "}", "this", ".", "_list", ".", "push", "(", "utils", ".", "extend", "(", "{", "}", ",", "options", ",", "{", "order", ":", "order", ",", "fn", ":", "fn", "}", ")", ")", ";", "}" ]
Adds function handler @param {Function} fn Handler @param {Object} options Handler options. Possible values are:<br><br> <b>order</b> : (<code>Number</code>) – order in handler list. Handlers with higher order value will be executed earlier.
[ "Adds", "function", "handler" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/handlerList.js#L32-L39
11,313
emmetio/emmet
lib/assets/handlerList.js
function(fn) { var item = utils.find(this._list, function(item) { return item.fn === fn; }); if (item) { this._list.splice(this._list.indexOf(item), 1); } }
javascript
function(fn) { var item = utils.find(this._list, function(item) { return item.fn === fn; }); if (item) { this._list.splice(this._list.indexOf(item), 1); } }
[ "function", "(", "fn", ")", "{", "var", "item", "=", "utils", ".", "find", "(", "this", ".", "_list", ",", "function", "(", "item", ")", "{", "return", "item", ".", "fn", "===", "fn", ";", "}", ")", ";", "if", "(", "item", ")", "{", "this", ".", "_list", ".", "splice", "(", "this", ".", "_list", ".", "indexOf", "(", "item", ")", ",", "1", ")", ";", "}", "}" ]
Removes handler from list @param {Function} fn
[ "Removes", "handler", "from", "list" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/handlerList.js#L45-L52
11,314
emmetio/emmet
lib/emmet.js
getFileName
function getFileName(path) { var re = /([\w\.\-]+)$/i; var m = re.exec(path); return m ? m[1] : ''; }
javascript
function getFileName(path) { var re = /([\w\.\-]+)$/i; var m = re.exec(path); return m ? m[1] : ''; }
[ "function", "getFileName", "(", "path", ")", "{", "var", "re", "=", "/", "([\\w\\.\\-]+)$", "/", "i", ";", "var", "m", "=", "re", ".", "exec", "(", "path", ")", ";", "return", "m", "?", "m", "[", "1", "]", ":", "''", ";", "}" ]
Returns file name part from path @param {String} path Path to file @return {String}
[ "Returns", "file", "name", "part", "from", "path" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/emmet.js#L28-L32
11,315
emmetio/emmet
lib/emmet.js
function(abbr, syntax, profile, contextNode) { return parser.expand(abbr, { syntax: syntax, profile: profile, contextNode: contextNode }); }
javascript
function(abbr, syntax, profile, contextNode) { return parser.expand(abbr, { syntax: syntax, profile: profile, contextNode: contextNode }); }
[ "function", "(", "abbr", ",", "syntax", ",", "profile", ",", "contextNode", ")", "{", "return", "parser", ".", "expand", "(", "abbr", ",", "{", "syntax", ":", "syntax", ",", "profile", ":", "profile", ",", "contextNode", ":", "contextNode", "}", ")", ";", "}" ]
The essential function that expands Emmet abbreviation @param {String} abbr Abbreviation to parse @param {String} syntax Abbreviation's context syntax @param {String} profile Output profile (or its name) @param {Object} contextNode Contextual node where abbreviation is written @return {String}
[ "The", "essential", "function", "that", "expands", "Emmet", "abbreviation" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/emmet.js#L66-L72
11,316
emmetio/emmet
lib/emmet.js
function(profiles) { profiles = utils.parseJSON(profiles); var snippets = {}; Object.keys(profiles).forEach(function(syntax) { var options = profiles[syntax]; if (!(syntax in snippets)) { snippets[syntax] = {}; } snippets[syntax].profile = normalizeProfile(options); }); this.loadSnippets(snippets); }
javascript
function(profiles) { profiles = utils.parseJSON(profiles); var snippets = {}; Object.keys(profiles).forEach(function(syntax) { var options = profiles[syntax]; if (!(syntax in snippets)) { snippets[syntax] = {}; } snippets[syntax].profile = normalizeProfile(options); }); this.loadSnippets(snippets); }
[ "function", "(", "profiles", ")", "{", "profiles", "=", "utils", ".", "parseJSON", "(", "profiles", ")", ";", "var", "snippets", "=", "{", "}", ";", "Object", ".", "keys", "(", "profiles", ")", ".", "forEach", "(", "function", "(", "syntax", ")", "{", "var", "options", "=", "profiles", "[", "syntax", "]", ";", "if", "(", "!", "(", "syntax", "in", "snippets", ")", ")", "{", "snippets", "[", "syntax", "]", "=", "{", "}", ";", "}", "snippets", "[", "syntax", "]", ".", "profile", "=", "normalizeProfile", "(", "options", ")", ";", "}", ")", ";", "this", ".", "loadSnippets", "(", "snippets", ")", ";", "}" ]
Load syntax-specific output profiles. These are essentially an extension to syntax snippets @param {Object} profiles Dictionary of profiles
[ "Load", "syntax", "-", "specific", "output", "profiles", ".", "These", "are", "essentially", "an", "extension", "to", "syntax", "snippets" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/emmet.js#L248-L260
11,317
emmetio/emmet
lib/emmet.js
function(profiles) { profiles = utils.parseJSON(profiles); Object.keys(profiles).forEach(function(name) { profile.create(name, normalizeProfile(profiles[name])); }); }
javascript
function(profiles) { profiles = utils.parseJSON(profiles); Object.keys(profiles).forEach(function(name) { profile.create(name, normalizeProfile(profiles[name])); }); }
[ "function", "(", "profiles", ")", "{", "profiles", "=", "utils", ".", "parseJSON", "(", "profiles", ")", ";", "Object", ".", "keys", "(", "profiles", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "profile", ".", "create", "(", "name", ",", "normalizeProfile", "(", "profiles", "[", "name", "]", ")", ")", ";", "}", ")", ";", "}" ]
Load named profiles @param {Object} profiles
[ "Load", "named", "profiles" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/emmet.js#L266-L271
11,318
emmetio/emmet
lib/utils/abbreviation.js
function(node) { return (this.hasTagsInContent(node) && this.isBlock(node)) || node.children.some(function(child) { return this.isBlock(child); }, this); }
javascript
function(node) { return (this.hasTagsInContent(node) && this.isBlock(node)) || node.children.some(function(child) { return this.isBlock(child); }, this); }
[ "function", "(", "node", ")", "{", "return", "(", "this", ".", "hasTagsInContent", "(", "node", ")", "&&", "this", ".", "isBlock", "(", "node", ")", ")", "||", "node", ".", "children", ".", "some", "(", "function", "(", "child", ")", "{", "return", "this", ".", "isBlock", "(", "child", ")", ";", "}", ",", "this", ")", ";", "}" ]
Test if current element contains block-level children @param {AbbreviationNode} node @return {Boolean}
[ "Test", "if", "current", "element", "contains", "block", "-", "level", "children" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/utils/abbreviation.js#L77-L82
11,319
emmetio/emmet
lib/vendor/klass.js
function(protoProps, classProps) { var child = inherits(this, protoProps, classProps); child.extend = this.extend; // a hack required to WSH inherit `toString` method if (protoProps.hasOwnProperty('toString')) child.prototype.toString = protoProps.toString; return child; }
javascript
function(protoProps, classProps) { var child = inherits(this, protoProps, classProps); child.extend = this.extend; // a hack required to WSH inherit `toString` method if (protoProps.hasOwnProperty('toString')) child.prototype.toString = protoProps.toString; return child; }
[ "function", "(", "protoProps", ",", "classProps", ")", "{", "var", "child", "=", "inherits", "(", "this", ",", "protoProps", ",", "classProps", ")", ";", "child", ".", "extend", "=", "this", ".", "extend", ";", "// a hack required to WSH inherit `toString` method", "if", "(", "protoProps", ".", "hasOwnProperty", "(", "'toString'", ")", ")", "child", ".", "prototype", ".", "toString", "=", "protoProps", ".", "toString", ";", "return", "child", ";", "}" ]
The self-propagating extend function for classes. Took it from Backbone @param {Object} protoProps @param {Object} classProps @returns {Object}
[ "The", "self", "-", "propagating", "extend", "function", "for", "classes", ".", "Took", "it", "from", "Backbone" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/vendor/klass.js#L74-L81
11,320
emmetio/emmet
lib/filter/bem.js
processClassName
function processClassName(name, item) { name = transformClassName(name, item, 'element'); name = transformClassName(name, item, 'modifier'); // expand class name // possible values: // * block__element // * block__element_modifier // * block__element_modifier1_modifier2 // * block_modifier var block = '', element = '', modifier = ''; var separators = getSeparators(); if (~name.indexOf(separators.element)) { var elements = name.split(separators.element); block = elements.shift(); var modifiers = elements.pop().split(separators.modifier); elements.push(modifiers.shift()); element = elements.join(separators.element); modifier = modifiers.join(separators.modifier); } else if (~name.indexOf(separators.modifier)) { var blockModifiers = name.split(separators.modifier); block = blockModifiers.shift(); modifier = blockModifiers.join(separators.modifier); } if (block || element || modifier) { if (!block) { block = item.__bem.block; } // inherit parent bem element, if exists // if (item.parent && item.parent.__bem && item.parent.__bem.element) // element = item.parent.__bem.element + separators.element + element; // produce multiple classes var prefix = block; var result = []; if (element) { prefix += separators.element + element; result.push(prefix); } else { result.push(prefix); } if (modifier) { result.push(prefix + separators.modifier + modifier); } if (!item.__bem.block || modifier) { item.__bem.block = block; } item.__bem.element = element; item.__bem.modifier = modifier; return result; } // ...otherwise, return processed or original class name return name; }
javascript
function processClassName(name, item) { name = transformClassName(name, item, 'element'); name = transformClassName(name, item, 'modifier'); // expand class name // possible values: // * block__element // * block__element_modifier // * block__element_modifier1_modifier2 // * block_modifier var block = '', element = '', modifier = ''; var separators = getSeparators(); if (~name.indexOf(separators.element)) { var elements = name.split(separators.element); block = elements.shift(); var modifiers = elements.pop().split(separators.modifier); elements.push(modifiers.shift()); element = elements.join(separators.element); modifier = modifiers.join(separators.modifier); } else if (~name.indexOf(separators.modifier)) { var blockModifiers = name.split(separators.modifier); block = blockModifiers.shift(); modifier = blockModifiers.join(separators.modifier); } if (block || element || modifier) { if (!block) { block = item.__bem.block; } // inherit parent bem element, if exists // if (item.parent && item.parent.__bem && item.parent.__bem.element) // element = item.parent.__bem.element + separators.element + element; // produce multiple classes var prefix = block; var result = []; if (element) { prefix += separators.element + element; result.push(prefix); } else { result.push(prefix); } if (modifier) { result.push(prefix + separators.modifier + modifier); } if (!item.__bem.block || modifier) { item.__bem.block = block; } item.__bem.element = element; item.__bem.modifier = modifier; return result; } // ...otherwise, return processed or original class name return name; }
[ "function", "processClassName", "(", "name", ",", "item", ")", "{", "name", "=", "transformClassName", "(", "name", ",", "item", ",", "'element'", ")", ";", "name", "=", "transformClassName", "(", "name", ",", "item", ",", "'modifier'", ")", ";", "// expand class name", "// possible values:", "// * block__element", "// * block__element_modifier", "// * block__element_modifier1_modifier2", "// * block_modifier", "var", "block", "=", "''", ",", "element", "=", "''", ",", "modifier", "=", "''", ";", "var", "separators", "=", "getSeparators", "(", ")", ";", "if", "(", "~", "name", ".", "indexOf", "(", "separators", ".", "element", ")", ")", "{", "var", "elements", "=", "name", ".", "split", "(", "separators", ".", "element", ")", ";", "block", "=", "elements", ".", "shift", "(", ")", ";", "var", "modifiers", "=", "elements", ".", "pop", "(", ")", ".", "split", "(", "separators", ".", "modifier", ")", ";", "elements", ".", "push", "(", "modifiers", ".", "shift", "(", ")", ")", ";", "element", "=", "elements", ".", "join", "(", "separators", ".", "element", ")", ";", "modifier", "=", "modifiers", ".", "join", "(", "separators", ".", "modifier", ")", ";", "}", "else", "if", "(", "~", "name", ".", "indexOf", "(", "separators", ".", "modifier", ")", ")", "{", "var", "blockModifiers", "=", "name", ".", "split", "(", "separators", ".", "modifier", ")", ";", "block", "=", "blockModifiers", ".", "shift", "(", ")", ";", "modifier", "=", "blockModifiers", ".", "join", "(", "separators", ".", "modifier", ")", ";", "}", "if", "(", "block", "||", "element", "||", "modifier", ")", "{", "if", "(", "!", "block", ")", "{", "block", "=", "item", ".", "__bem", ".", "block", ";", "}", "// inherit parent bem element, if exists", "//\t\t\tif (item.parent && item.parent.__bem && item.parent.__bem.element)", "//\t\t\t\telement = item.parent.__bem.element + separators.element + element;", "// produce multiple classes", "var", "prefix", "=", "block", ";", "var", "result", "=", "[", "]", ";", "if", "(", "element", ")", "{", "prefix", "+=", "separators", ".", "element", "+", "element", ";", "result", ".", "push", "(", "prefix", ")", ";", "}", "else", "{", "result", ".", "push", "(", "prefix", ")", ";", "}", "if", "(", "modifier", ")", "{", "result", ".", "push", "(", "prefix", "+", "separators", ".", "modifier", "+", "modifier", ")", ";", "}", "if", "(", "!", "item", ".", "__bem", ".", "block", "||", "modifier", ")", "{", "item", ".", "__bem", ".", "block", "=", "block", ";", "}", "item", ".", "__bem", ".", "element", "=", "element", ";", "item", ".", "__bem", ".", "modifier", "=", "modifier", ";", "return", "result", ";", "}", "// ...otherwise, return processed or original class name", "return", "name", ";", "}" ]
Processes class name @param {String} name Class name item to process @param {AbbreviationNode} item Host node for provided class name @returns Processed class name. May return <code>Array</code> of class names
[ "Processes", "class", "name" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/filter/bem.js#L103-L166
11,321
emmetio/emmet
lib/filter/bem.js
transformClassName
function transformClassName(name, item, entityType) { var separators = getSeparators(); var reSep = new RegExp('^(' + separators[entityType] + ')+', 'g'); if (reSep.test(name)) { var depth = 0; // parent lookup depth var cleanName = name.replace(reSep, function(str) { depth = str.length / separators[entityType].length; return ''; }); // find donor element var donor = item; while (donor.parent && depth--) { donor = donor.parent; } if (!donor || !donor.__bem) donor = item; if (donor && donor.__bem) { var prefix = donor.__bem.block; // decide if we should inherit element name // if (entityType == 'element') { // var curElem = cleanName.split(separators.modifier, 1)[0]; // if (donor.__bem.element && donor.__bem.element != curElem) // prefix += separators.element + donor.__bem.element; // } if (entityType == 'modifier' && donor.__bem.element) prefix += separators.element + donor.__bem.element; return prefix + separators[entityType] + cleanName; } } return name; }
javascript
function transformClassName(name, item, entityType) { var separators = getSeparators(); var reSep = new RegExp('^(' + separators[entityType] + ')+', 'g'); if (reSep.test(name)) { var depth = 0; // parent lookup depth var cleanName = name.replace(reSep, function(str) { depth = str.length / separators[entityType].length; return ''; }); // find donor element var donor = item; while (donor.parent && depth--) { donor = donor.parent; } if (!donor || !donor.__bem) donor = item; if (donor && donor.__bem) { var prefix = donor.__bem.block; // decide if we should inherit element name // if (entityType == 'element') { // var curElem = cleanName.split(separators.modifier, 1)[0]; // if (donor.__bem.element && donor.__bem.element != curElem) // prefix += separators.element + donor.__bem.element; // } if (entityType == 'modifier' && donor.__bem.element) prefix += separators.element + donor.__bem.element; return prefix + separators[entityType] + cleanName; } } return name; }
[ "function", "transformClassName", "(", "name", ",", "item", ",", "entityType", ")", "{", "var", "separators", "=", "getSeparators", "(", ")", ";", "var", "reSep", "=", "new", "RegExp", "(", "'^('", "+", "separators", "[", "entityType", "]", "+", "')+'", ",", "'g'", ")", ";", "if", "(", "reSep", ".", "test", "(", "name", ")", ")", "{", "var", "depth", "=", "0", ";", "// parent lookup depth", "var", "cleanName", "=", "name", ".", "replace", "(", "reSep", ",", "function", "(", "str", ")", "{", "depth", "=", "str", ".", "length", "/", "separators", "[", "entityType", "]", ".", "length", ";", "return", "''", ";", "}", ")", ";", "// find donor element", "var", "donor", "=", "item", ";", "while", "(", "donor", ".", "parent", "&&", "depth", "--", ")", "{", "donor", "=", "donor", ".", "parent", ";", "}", "if", "(", "!", "donor", "||", "!", "donor", ".", "__bem", ")", "donor", "=", "item", ";", "if", "(", "donor", "&&", "donor", ".", "__bem", ")", "{", "var", "prefix", "=", "donor", ".", "__bem", ".", "block", ";", "// decide if we should inherit element name", "//\t\t\t\tif (entityType == 'element') {", "//\t\t\t\t\tvar curElem = cleanName.split(separators.modifier, 1)[0];", "//\t\t\t\t\tif (donor.__bem.element && donor.__bem.element != curElem)", "//\t\t\t\t\t\tprefix += separators.element + donor.__bem.element;", "//\t\t\t\t}", "if", "(", "entityType", "==", "'modifier'", "&&", "donor", ".", "__bem", ".", "element", ")", "prefix", "+=", "separators", ".", "element", "+", "donor", ".", "__bem", ".", "element", ";", "return", "prefix", "+", "separators", "[", "entityType", "]", "+", "cleanName", ";", "}", "}", "return", "name", ";", "}" ]
Low-level function to transform user-typed class name into full BEM class @param {String} name Class name item to process @param {AbbreviationNode} item Host node for provided class name @param {String} entityType Type of entity to be tried to transform ('element' or 'modifier') @returns {String} Processed class name or original one if it can't be transformed
[ "Low", "-", "level", "function", "to", "transform", "user", "-", "typed", "class", "name", "into", "full", "BEM", "class" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/filter/bem.js#L177-L214
11,322
emmetio/emmet
lib/action/main.js
function(title, menu) { return utils.find(menu || this.getMenu(), function(val) { if (val.type == 'action') { if (val.label == title || val.name == title) { return val.name; } } else { return this.getActionNameForMenuTitle(title, val.items); } }, this); }
javascript
function(title, menu) { return utils.find(menu || this.getMenu(), function(val) { if (val.type == 'action') { if (val.label == title || val.name == title) { return val.name; } } else { return this.getActionNameForMenuTitle(title, val.items); } }, this); }
[ "function", "(", "title", ",", "menu", ")", "{", "return", "utils", ".", "find", "(", "menu", "||", "this", ".", "getMenu", "(", ")", ",", "function", "(", "val", ")", "{", "if", "(", "val", ".", "type", "==", "'action'", ")", "{", "if", "(", "val", ".", "label", "==", "title", "||", "val", ".", "name", "==", "title", ")", "{", "return", "val", ".", "name", ";", "}", "}", "else", "{", "return", "this", ".", "getActionNameForMenuTitle", "(", "title", ",", "val", ".", "items", ")", ";", "}", "}", ",", "this", ")", ";", "}" ]
Returns action name associated with menu item title @param {String} title @returns {String}
[ "Returns", "action", "name", "associated", "with", "menu", "item", "title" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/action/main.js#L228-L238
11,323
emmetio/emmet
lib/assets/caniuse.js
parseDB
function parseDB(data, optimized) { if (typeof data == 'string') { data = JSON.parse(data); } if (!optimized) { data = optimize(data); } vendorsDB = data.vendors; cssDB = data.css; erasDB = data.era; }
javascript
function parseDB(data, optimized) { if (typeof data == 'string') { data = JSON.parse(data); } if (!optimized) { data = optimize(data); } vendorsDB = data.vendors; cssDB = data.css; erasDB = data.era; }
[ "function", "parseDB", "(", "data", ",", "optimized", ")", "{", "if", "(", "typeof", "data", "==", "'string'", ")", "{", "data", "=", "JSON", ".", "parse", "(", "data", ")", ";", "}", "if", "(", "!", "optimized", ")", "{", "data", "=", "optimize", "(", "data", ")", ";", "}", "vendorsDB", "=", "data", ".", "vendors", ";", "cssDB", "=", "data", ".", "css", ";", "erasDB", "=", "data", ".", "era", ";", "}" ]
Parses raw Can I Use database for better lookups @param {String} data Raw database @param {Boolean} optimized Pass `true` if given `data` is already optimized @return {Object}
[ "Parses", "raw", "Can", "I", "Use", "database", "for", "better", "lookups" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L84-L96
11,324
emmetio/emmet
lib/assets/caniuse.js
optimize
function optimize(data) { if (typeof data == 'string') { data = JSON.parse(data); } return { vendors: parseVendors(data), css: parseCSS(data), era: parseEra(data) }; }
javascript
function optimize(data) { if (typeof data == 'string') { data = JSON.parse(data); } return { vendors: parseVendors(data), css: parseCSS(data), era: parseEra(data) }; }
[ "function", "optimize", "(", "data", ")", "{", "if", "(", "typeof", "data", "==", "'string'", ")", "{", "data", "=", "JSON", ".", "parse", "(", "data", ")", ";", "}", "return", "{", "vendors", ":", "parseVendors", "(", "data", ")", ",", "css", ":", "parseCSS", "(", "data", ")", ",", "era", ":", "parseEra", "(", "data", ")", "}", ";", "}" ]
Extract required data only from CIU database @param {Object} data Raw Can I Use database @return {Object} Optimized database
[ "Extract", "required", "data", "only", "from", "CIU", "database" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L103-L113
11,325
emmetio/emmet
lib/assets/caniuse.js
parseVendors
function parseVendors(data) { var out = {}; Object.keys(data.agents).forEach(function(name) { var agent = data.agents[name]; out[name] = { prefix: agent.prefix, versions: agent.versions }; }); return out; }
javascript
function parseVendors(data) { var out = {}; Object.keys(data.agents).forEach(function(name) { var agent = data.agents[name]; out[name] = { prefix: agent.prefix, versions: agent.versions }; }); return out; }
[ "function", "parseVendors", "(", "data", ")", "{", "var", "out", "=", "{", "}", ";", "Object", ".", "keys", "(", "data", ".", "agents", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "agent", "=", "data", ".", "agents", "[", "name", "]", ";", "out", "[", "name", "]", "=", "{", "prefix", ":", "agent", ".", "prefix", ",", "versions", ":", "agent", ".", "versions", "}", ";", "}", ")", ";", "return", "out", ";", "}" ]
Parses vendor data @param {Object} data @return {Object}
[ "Parses", "vendor", "data" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L120-L130
11,326
emmetio/emmet
lib/assets/caniuse.js
parseCSS
function parseCSS(data) { var out = {}; var cssCategories = data.cats.CSS; Object.keys(data.data).forEach(function(name) { var section = data.data[name]; if (name in cssSections) { cssSections[name].forEach(function(kw) { out[kw] = section.stats; }); } }); return out; }
javascript
function parseCSS(data) { var out = {}; var cssCategories = data.cats.CSS; Object.keys(data.data).forEach(function(name) { var section = data.data[name]; if (name in cssSections) { cssSections[name].forEach(function(kw) { out[kw] = section.stats; }); } }); return out; }
[ "function", "parseCSS", "(", "data", ")", "{", "var", "out", "=", "{", "}", ";", "var", "cssCategories", "=", "data", ".", "cats", ".", "CSS", ";", "Object", ".", "keys", "(", "data", ".", "data", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "section", "=", "data", ".", "data", "[", "name", "]", ";", "if", "(", "name", "in", "cssSections", ")", "{", "cssSections", "[", "name", "]", ".", "forEach", "(", "function", "(", "kw", ")", "{", "out", "[", "kw", "]", "=", "section", ".", "stats", ";", "}", ")", ";", "}", "}", ")", ";", "return", "out", ";", "}" ]
Parses CSS data from Can I Use raw database @param {Object} data @return {Object}
[ "Parses", "CSS", "data", "from", "Can", "I", "Use", "raw", "database" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L137-L150
11,327
emmetio/emmet
lib/assets/caniuse.js
parseEra
function parseEra(data) { // some runtimes (like Mozilla Rhino) does not preserves // key order so we have to sort values manually return Object.keys(data.eras).sort(function(a, b) { return parseInt(a.substr(1)) - parseInt(b.substr(1)); }); }
javascript
function parseEra(data) { // some runtimes (like Mozilla Rhino) does not preserves // key order so we have to sort values manually return Object.keys(data.eras).sort(function(a, b) { return parseInt(a.substr(1)) - parseInt(b.substr(1)); }); }
[ "function", "parseEra", "(", "data", ")", "{", "// some runtimes (like Mozilla Rhino) does not preserves", "// key order so we have to sort values manually", "return", "Object", ".", "keys", "(", "data", ".", "eras", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "parseInt", "(", "a", ".", "substr", "(", "1", ")", ")", "-", "parseInt", "(", "b", ".", "substr", "(", "1", ")", ")", ";", "}", ")", ";", "}" ]
Parses era data from Can I Use raw database @param {Object} data @return {Array}
[ "Parses", "era", "data", "from", "Can", "I", "Use", "raw", "database" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L157-L163
11,328
emmetio/emmet
lib/assets/caniuse.js
getVendorsList
function getVendorsList() { var allVendors = Object.keys(vendorsDB); var vendors = prefs.getArray('caniuse.vendors'); if (!vendors || vendors[0] == 'all') { return allVendors; } return intersection(allVendors, vendors); }
javascript
function getVendorsList() { var allVendors = Object.keys(vendorsDB); var vendors = prefs.getArray('caniuse.vendors'); if (!vendors || vendors[0] == 'all') { return allVendors; } return intersection(allVendors, vendors); }
[ "function", "getVendorsList", "(", ")", "{", "var", "allVendors", "=", "Object", ".", "keys", "(", "vendorsDB", ")", ";", "var", "vendors", "=", "prefs", ".", "getArray", "(", "'caniuse.vendors'", ")", ";", "if", "(", "!", "vendors", "||", "vendors", "[", "0", "]", "==", "'all'", ")", "{", "return", "allVendors", ";", "}", "return", "intersection", "(", "allVendors", ",", "vendors", ")", ";", "}" ]
Returs list of supported vendors, depending on user preferences @return {Array}
[ "Returs", "list", "of", "supported", "vendors", "depending", "on", "user", "preferences" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L169-L177
11,329
emmetio/emmet
lib/assets/caniuse.js
getVersionSlice
function getVersionSlice() { var era = prefs.get('caniuse.era'); var ix = erasDB.indexOf(era); if (!~ix) { ix = erasDB.indexOf('e-2'); } return ix; }
javascript
function getVersionSlice() { var era = prefs.get('caniuse.era'); var ix = erasDB.indexOf(era); if (!~ix) { ix = erasDB.indexOf('e-2'); } return ix; }
[ "function", "getVersionSlice", "(", ")", "{", "var", "era", "=", "prefs", ".", "get", "(", "'caniuse.era'", ")", ";", "var", "ix", "=", "erasDB", ".", "indexOf", "(", "era", ")", ";", "if", "(", "!", "~", "ix", ")", "{", "ix", "=", "erasDB", ".", "indexOf", "(", "'e-2'", ")", ";", "}", "return", "ix", ";", "}" ]
Returns size of version slice as defined by era identifier @return {Number}
[ "Returns", "size", "of", "version", "slice", "as", "defined", "by", "era", "identifier" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L183-L191
11,330
emmetio/emmet
lib/assets/caniuse.js
function(property) { if (!prefs.get('caniuse.enabled') || !cssDB || !(property in cssDB)) { return null; } var prefixes = []; var propStats = cssDB[property]; var versions = getVersionSlice(); getVendorsList().forEach(function(vendor) { var vendorVesions = vendorsDB[vendor].versions.slice(versions); for (var i = 0, v; i < vendorVesions.length; i++) { v = vendorVesions[i]; if (!v) { continue; } if (~propStats[vendor][v].indexOf('x')) { prefixes.push(vendorsDB[vendor].prefix); break; } } }); return utils.unique(prefixes).sort(function(a, b) { return b.length - a.length; }); }
javascript
function(property) { if (!prefs.get('caniuse.enabled') || !cssDB || !(property in cssDB)) { return null; } var prefixes = []; var propStats = cssDB[property]; var versions = getVersionSlice(); getVendorsList().forEach(function(vendor) { var vendorVesions = vendorsDB[vendor].versions.slice(versions); for (var i = 0, v; i < vendorVesions.length; i++) { v = vendorVesions[i]; if (!v) { continue; } if (~propStats[vendor][v].indexOf('x')) { prefixes.push(vendorsDB[vendor].prefix); break; } } }); return utils.unique(prefixes).sort(function(a, b) { return b.length - a.length; }); }
[ "function", "(", "property", ")", "{", "if", "(", "!", "prefs", ".", "get", "(", "'caniuse.enabled'", ")", "||", "!", "cssDB", "||", "!", "(", "property", "in", "cssDB", ")", ")", "{", "return", "null", ";", "}", "var", "prefixes", "=", "[", "]", ";", "var", "propStats", "=", "cssDB", "[", "property", "]", ";", "var", "versions", "=", "getVersionSlice", "(", ")", ";", "getVendorsList", "(", ")", ".", "forEach", "(", "function", "(", "vendor", ")", "{", "var", "vendorVesions", "=", "vendorsDB", "[", "vendor", "]", ".", "versions", ".", "slice", "(", "versions", ")", ";", "for", "(", "var", "i", "=", "0", ",", "v", ";", "i", "<", "vendorVesions", ".", "length", ";", "i", "++", ")", "{", "v", "=", "vendorVesions", "[", "i", "]", ";", "if", "(", "!", "v", ")", "{", "continue", ";", "}", "if", "(", "~", "propStats", "[", "vendor", "]", "[", "v", "]", ".", "indexOf", "(", "'x'", ")", ")", "{", "prefixes", ".", "push", "(", "vendorsDB", "[", "vendor", "]", ".", "prefix", ")", ";", "break", ";", "}", "}", "}", ")", ";", "return", "utils", ".", "unique", "(", "prefixes", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", ".", "length", "-", "a", ".", "length", ";", "}", ")", ";", "}" ]
Resolves prefixes for given property @param {String} property A property to resolve. It can start with `@` symbol (CSS section, like `@keyframes`) or `:` (CSS value, like `flex`) @return {Array} Array of resolved prefixes or <code>null</code> if prefixes can't be resolved. Empty array means property has no vendor prefixes
[ "Resolves", "prefixes", "for", "given", "property" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/caniuse.js#L220-L247
11,331
emmetio/emmet
lib/assets/profile.js
function(name, options) { if (arguments.length == 2) return createProfile(name, options); else // create profile object only return new OutputProfile(utils.defaults(name || {}, defaultProfile)); }
javascript
function(name, options) { if (arguments.length == 2) return createProfile(name, options); else // create profile object only return new OutputProfile(utils.defaults(name || {}, defaultProfile)); }
[ "function", "(", "name", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "==", "2", ")", "return", "createProfile", "(", "name", ",", "options", ")", ";", "else", "// create profile object only", "return", "new", "OutputProfile", "(", "utils", ".", "defaults", "(", "name", "||", "{", "}", ",", "defaultProfile", ")", ")", ";", "}" ]
Creates new output profile and adds it into internal dictionary @param {String} name Profile name @param {Object} options Profile options @memberOf emmet.profile @returns {Object} New profile
[ "Creates", "new", "output", "profile", "and", "adds", "it", "into", "internal", "dictionary" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/profile.js#L205-L211
11,332
emmetio/emmet
lib/assets/profile.js
function(name, syntax) { if (!name && syntax) { // search in user resources first var profile = resources.findItem(syntax, 'profile'); if (profile) { name = profile; } } if (!name) { return profiles.plain; } if (name instanceof OutputProfile) { return name; } if (typeof name === 'string' && name.toLowerCase() in profiles) { return profiles[name.toLowerCase()]; } return this.create(name); }
javascript
function(name, syntax) { if (!name && syntax) { // search in user resources first var profile = resources.findItem(syntax, 'profile'); if (profile) { name = profile; } } if (!name) { return profiles.plain; } if (name instanceof OutputProfile) { return name; } if (typeof name === 'string' && name.toLowerCase() in profiles) { return profiles[name.toLowerCase()]; } return this.create(name); }
[ "function", "(", "name", ",", "syntax", ")", "{", "if", "(", "!", "name", "&&", "syntax", ")", "{", "// search in user resources first", "var", "profile", "=", "resources", ".", "findItem", "(", "syntax", ",", "'profile'", ")", ";", "if", "(", "profile", ")", "{", "name", "=", "profile", ";", "}", "}", "if", "(", "!", "name", ")", "{", "return", "profiles", ".", "plain", ";", "}", "if", "(", "name", "instanceof", "OutputProfile", ")", "{", "return", "name", ";", "}", "if", "(", "typeof", "name", "===", "'string'", "&&", "name", ".", "toLowerCase", "(", ")", "in", "profiles", ")", "{", "return", "profiles", "[", "name", ".", "toLowerCase", "(", ")", "]", ";", "}", "return", "this", ".", "create", "(", "name", ")", ";", "}" ]
Returns profile by its name. If profile wasn't found, returns 'plain' profile @param {String} name Profile name. Might be profile itself @param {String} syntax. Optional. Current editor syntax. If defined, profile is searched in resources first, then in predefined profiles @returns {Object}
[ "Returns", "profile", "by", "its", "name", ".", "If", "profile", "wasn", "t", "found", "returns", "plain", "profile" ]
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/assets/profile.js#L221-L243
11,333
testing-library/jest-dom
src/to-have-style.js
expectedDiff
function expectedDiff(expected, computedStyles) { const received = Array.from(computedStyles) .filter(prop => expected[prop]) .reduce( (obj, prop) => Object.assign(obj, {[prop]: computedStyles.getPropertyValue(prop)}), {}, ) const diffOutput = jestDiff( printoutStyles(expected), printoutStyles(received), ) // Remove the "+ Received" annotation because this is a one-way diff return diffOutput.replace(`${chalk.red('+ Received')}\n`, '') }
javascript
function expectedDiff(expected, computedStyles) { const received = Array.from(computedStyles) .filter(prop => expected[prop]) .reduce( (obj, prop) => Object.assign(obj, {[prop]: computedStyles.getPropertyValue(prop)}), {}, ) const diffOutput = jestDiff( printoutStyles(expected), printoutStyles(received), ) // Remove the "+ Received" annotation because this is a one-way diff return diffOutput.replace(`${chalk.red('+ Received')}\n`, '') }
[ "function", "expectedDiff", "(", "expected", ",", "computedStyles", ")", "{", "const", "received", "=", "Array", ".", "from", "(", "computedStyles", ")", ".", "filter", "(", "prop", "=>", "expected", "[", "prop", "]", ")", ".", "reduce", "(", "(", "obj", ",", "prop", ")", "=>", "Object", ".", "assign", "(", "obj", ",", "{", "[", "prop", "]", ":", "computedStyles", ".", "getPropertyValue", "(", "prop", ")", "}", ")", ",", "{", "}", ",", ")", "const", "diffOutput", "=", "jestDiff", "(", "printoutStyles", "(", "expected", ")", ",", "printoutStyles", "(", "received", ")", ",", ")", "// Remove the \"+ Received\" annotation because this is a one-way diff", "return", "diffOutput", ".", "replace", "(", "`", "${", "chalk", ".", "red", "(", "'+ Received'", ")", "}", "\\n", "`", ",", "''", ")", "}" ]
Highlights only style rules that were expected but were not found in the received computed styles
[ "Highlights", "only", "style", "rules", "that", "were", "expected", "but", "were", "not", "found", "in", "the", "received", "computed", "styles" ]
2bc084f175732e83b62ab7fb2517fe4f8369d2ac
https://github.com/testing-library/jest-dom/blob/2bc084f175732e83b62ab7fb2517fe4f8369d2ac/src/to-have-style.js#L32-L46
11,334
flatiron/director
lib/director/router.js
_flatten
function _flatten (arr) { var flat = []; for (var i = 0, n = arr.length; i < n; i++) { flat = flat.concat(arr[i]); } return flat; }
javascript
function _flatten (arr) { var flat = []; for (var i = 0, n = arr.length; i < n; i++) { flat = flat.concat(arr[i]); } return flat; }
[ "function", "_flatten", "(", "arr", ")", "{", "var", "flat", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "arr", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "flat", "=", "flat", ".", "concat", "(", "arr", "[", "i", "]", ")", ";", "}", "return", "flat", ";", "}" ]
Helper function to turn flatten an array.
[ "Helper", "function", "to", "turn", "flatten", "an", "array", "." ]
b507baed25cfd38307808ea41a0d6305ee6e1ebf
https://github.com/flatiron/director/blob/b507baed25cfd38307808ea41a0d6305ee6e1ebf/lib/director/router.js#L14-L22
11,335
flatiron/director
lib/director/router.js
_every
function _every (arr, iterator) { for (var i = 0; i < arr.length; i += 1) { if (iterator(arr[i], i, arr) === false) { return; } } }
javascript
function _every (arr, iterator) { for (var i = 0; i < arr.length; i += 1) { if (iterator(arr[i], i, arr) === false) { return; } } }
[ "function", "_every", "(", "arr", ",", "iterator", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "+=", "1", ")", "{", "if", "(", "iterator", "(", "arr", "[", "i", "]", ",", "i", ",", "arr", ")", "===", "false", ")", "{", "return", ";", "}", "}", "}" ]
Helper function for wrapping Array.every in the browser.
[ "Helper", "function", "for", "wrapping", "Array", ".", "every", "in", "the", "browser", "." ]
b507baed25cfd38307808ea41a0d6305ee6e1ebf
https://github.com/flatiron/director/blob/b507baed25cfd38307808ea41a0d6305ee6e1ebf/lib/director/router.js#L28-L34
11,336
flatiron/director
lib/director/router.js
_asyncEverySeries
function _asyncEverySeries (arr, iterator, callback) { if (!arr.length) { return callback(); } var completed = 0; (function iterate() { iterator(arr[completed], function (err) { if (err || err === false) { callback(err); callback = function () {}; } else { completed += 1; if (completed === arr.length) { callback(); } else { iterate(); } } }); })(); }
javascript
function _asyncEverySeries (arr, iterator, callback) { if (!arr.length) { return callback(); } var completed = 0; (function iterate() { iterator(arr[completed], function (err) { if (err || err === false) { callback(err); callback = function () {}; } else { completed += 1; if (completed === arr.length) { callback(); } else { iterate(); } } }); })(); }
[ "function", "_asyncEverySeries", "(", "arr", ",", "iterator", ",", "callback", ")", "{", "if", "(", "!", "arr", ".", "length", ")", "{", "return", "callback", "(", ")", ";", "}", "var", "completed", "=", "0", ";", "(", "function", "iterate", "(", ")", "{", "iterator", "(", "arr", "[", "completed", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", "||", "err", "===", "false", ")", "{", "callback", "(", "err", ")", ";", "callback", "=", "function", "(", ")", "{", "}", ";", "}", "else", "{", "completed", "+=", "1", ";", "if", "(", "completed", "===", "arr", ".", "length", ")", "{", "callback", "(", ")", ";", "}", "else", "{", "iterate", "(", ")", ";", "}", "}", "}", ")", ";", "}", ")", "(", ")", ";", "}" ]
Helper function for performing an asynchronous every in series in the browser and the server.
[ "Helper", "function", "for", "performing", "an", "asynchronous", "every", "in", "series", "in", "the", "browser", "and", "the", "server", "." ]
b507baed25cfd38307808ea41a0d6305ee6e1ebf
https://github.com/flatiron/director/blob/b507baed25cfd38307808ea41a0d6305ee6e1ebf/lib/director/router.js#L40-L63
11,337
prettier/eslint-plugin-prettier
eslint-plugin-prettier.js
reportDelete
function reportDelete(context, offset, text) { const start = context.getSourceCode().getLocFromIndex(offset); const end = context.getSourceCode().getLocFromIndex(offset + text.length); const range = [offset, offset + text.length]; context.report({ message: 'Delete `{{ code }}`', data: { code: showInvisibles(text) }, loc: { start, end }, fix(fixer) { return fixer.removeRange(range); } }); }
javascript
function reportDelete(context, offset, text) { const start = context.getSourceCode().getLocFromIndex(offset); const end = context.getSourceCode().getLocFromIndex(offset + text.length); const range = [offset, offset + text.length]; context.report({ message: 'Delete `{{ code }}`', data: { code: showInvisibles(text) }, loc: { start, end }, fix(fixer) { return fixer.removeRange(range); } }); }
[ "function", "reportDelete", "(", "context", ",", "offset", ",", "text", ")", "{", "const", "start", "=", "context", ".", "getSourceCode", "(", ")", ".", "getLocFromIndex", "(", "offset", ")", ";", "const", "end", "=", "context", ".", "getSourceCode", "(", ")", ".", "getLocFromIndex", "(", "offset", "+", "text", ".", "length", ")", ";", "const", "range", "=", "[", "offset", ",", "offset", "+", "text", ".", "length", "]", ";", "context", ".", "report", "(", "{", "message", ":", "'Delete `{{ code }}`'", ",", "data", ":", "{", "code", ":", "showInvisibles", "(", "text", ")", "}", ",", "loc", ":", "{", "start", ",", "end", "}", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "removeRange", "(", "range", ")", ";", "}", "}", ")", ";", "}" ]
Reports a "Delete ..." issue where text must be deleted. @param {RuleContext} context - The ESLint rule context. @param {number} offset - The source offset where to delete text. @param {string} text - The text to be deleted. @returns {void}
[ "Reports", "a", "Delete", "...", "issue", "where", "text", "must", "be", "deleted", "." ]
0bb7c1d361b581fddebd64bf172b5dedcad5149c
https://github.com/prettier/eslint-plugin-prettier/blob/0bb7c1d361b581fddebd64bf172b5dedcad5149c/eslint-plugin-prettier.js#L61-L73
11,338
prettier/eslint-plugin-prettier
eslint-plugin-prettier.js
reportReplace
function reportReplace(context, offset, deleteText, insertText) { const start = context.getSourceCode().getLocFromIndex(offset); const end = context .getSourceCode() .getLocFromIndex(offset + deleteText.length); const range = [offset, offset + deleteText.length]; context.report({ message: 'Replace `{{ deleteCode }}` with `{{ insertCode }}`', data: { deleteCode: showInvisibles(deleteText), insertCode: showInvisibles(insertText) }, loc: { start, end }, fix(fixer) { return fixer.replaceTextRange(range, insertText); } }); }
javascript
function reportReplace(context, offset, deleteText, insertText) { const start = context.getSourceCode().getLocFromIndex(offset); const end = context .getSourceCode() .getLocFromIndex(offset + deleteText.length); const range = [offset, offset + deleteText.length]; context.report({ message: 'Replace `{{ deleteCode }}` with `{{ insertCode }}`', data: { deleteCode: showInvisibles(deleteText), insertCode: showInvisibles(insertText) }, loc: { start, end }, fix(fixer) { return fixer.replaceTextRange(range, insertText); } }); }
[ "function", "reportReplace", "(", "context", ",", "offset", ",", "deleteText", ",", "insertText", ")", "{", "const", "start", "=", "context", ".", "getSourceCode", "(", ")", ".", "getLocFromIndex", "(", "offset", ")", ";", "const", "end", "=", "context", ".", "getSourceCode", "(", ")", ".", "getLocFromIndex", "(", "offset", "+", "deleteText", ".", "length", ")", ";", "const", "range", "=", "[", "offset", ",", "offset", "+", "deleteText", ".", "length", "]", ";", "context", ".", "report", "(", "{", "message", ":", "'Replace `{{ deleteCode }}` with `{{ insertCode }}`'", ",", "data", ":", "{", "deleteCode", ":", "showInvisibles", "(", "deleteText", ")", ",", "insertCode", ":", "showInvisibles", "(", "insertText", ")", "}", ",", "loc", ":", "{", "start", ",", "end", "}", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "replaceTextRange", "(", "range", ",", "insertText", ")", ";", "}", "}", ")", ";", "}" ]
Reports a "Replace ... with ..." issue where text must be replaced. @param {RuleContext} context - The ESLint rule context. @param {number} offset - The source offset where to replace deleted text with inserted text. @param {string} deleteText - The text to be deleted. @param {string} insertText - The text to be inserted. @returns {void}
[ "Reports", "a", "Replace", "...", "with", "...", "issue", "where", "text", "must", "be", "replaced", "." ]
0bb7c1d361b581fddebd64bf172b5dedcad5149c
https://github.com/prettier/eslint-plugin-prettier/blob/0bb7c1d361b581fddebd64bf172b5dedcad5149c/eslint-plugin-prettier.js#L84-L101
11,339
leanmotherfuckers/react-native-map-link
src/utils.js
isAppInstalled
function isAppInstalled(app, prefixes) { return new Promise((resolve) => { if (!(app in prefixes)) { return resolve(false) } Linking.canOpenURL(prefixes[app]) .then((result) => { resolve(!!result) }) .catch(() => resolve(false)) }) }
javascript
function isAppInstalled(app, prefixes) { return new Promise((resolve) => { if (!(app in prefixes)) { return resolve(false) } Linking.canOpenURL(prefixes[app]) .then((result) => { resolve(!!result) }) .catch(() => resolve(false)) }) }
[ "function", "isAppInstalled", "(", "app", ",", "prefixes", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "{", "if", "(", "!", "(", "app", "in", "prefixes", ")", ")", "{", "return", "resolve", "(", "false", ")", "}", "Linking", ".", "canOpenURL", "(", "prefixes", "[", "app", "]", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "resolve", "(", "!", "!", "result", ")", "}", ")", ".", "catch", "(", "(", ")", "=>", "resolve", "(", "false", ")", ")", "}", ")", "}" ]
Check if a given map app is installed. @param {string} app @returns {Promise<boolean>}
[ "Check", "if", "a", "given", "map", "app", "is", "installed", "." ]
873cf4c27a60433ef23e3fb051a57150670fbf71
https://github.com/leanmotherfuckers/react-native-map-link/blob/873cf4c27a60433ef23e3fb051a57150670fbf71/src/utils.js#L33-L45
11,340
MrSwitch/hello.js
dist/hello.all.js
function(r /*, a[, b[, ...]] */) { // Get the arguments as an array but ommit the initial item Array.prototype.slice.call(arguments, 1).forEach(function(a) { if (Array.isArray(r) && Array.isArray(a)) { Array.prototype.push.apply(r, a); } else if (r && (r instanceof Object || typeof r === 'object') && a && (a instanceof Object || typeof a === 'object') && r !== a) { for (var x in a) { r[x] = hello.utils.extend(r[x], a[x]); } } else { if (Array.isArray(a)) { // Clone it a = a.slice(0); } r = a; } }); return r; }
javascript
function(r /*, a[, b[, ...]] */) { // Get the arguments as an array but ommit the initial item Array.prototype.slice.call(arguments, 1).forEach(function(a) { if (Array.isArray(r) && Array.isArray(a)) { Array.prototype.push.apply(r, a); } else if (r && (r instanceof Object || typeof r === 'object') && a && (a instanceof Object || typeof a === 'object') && r !== a) { for (var x in a) { r[x] = hello.utils.extend(r[x], a[x]); } } else { if (Array.isArray(a)) { // Clone it a = a.slice(0); } r = a; } }); return r; }
[ "function", "(", "r", "/*, a[, b[, ...]] */", ")", "{", "// Get the arguments as an array but ommit the initial item", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ".", "forEach", "(", "function", "(", "a", ")", "{", "if", "(", "Array", ".", "isArray", "(", "r", ")", "&&", "Array", ".", "isArray", "(", "a", ")", ")", "{", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "r", ",", "a", ")", ";", "}", "else", "if", "(", "r", "&&", "(", "r", "instanceof", "Object", "||", "typeof", "r", "===", "'object'", ")", "&&", "a", "&&", "(", "a", "instanceof", "Object", "||", "typeof", "a", "===", "'object'", ")", "&&", "r", "!==", "a", ")", "{", "for", "(", "var", "x", "in", "a", ")", "{", "r", "[", "x", "]", "=", "hello", ".", "utils", ".", "extend", "(", "r", "[", "x", "]", ",", "a", "[", "x", "]", ")", ";", "}", "}", "else", "{", "if", "(", "Array", ".", "isArray", "(", "a", ")", ")", "{", "// Clone it", "a", "=", "a", ".", "slice", "(", "0", ")", ";", "}", "r", "=", "a", ";", "}", "}", ")", ";", "return", "r", ";", "}" ]
Extend the first object with the properties and methods of the second
[ "Extend", "the", "first", "object", "with", "the", "properties", "and", "methods", "of", "the", "second" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L173-L197
11,341
MrSwitch/hello.js
dist/hello.all.js
function(service) { // Create self, which inherits from its parent var self = Object.create(this); // Inherit the prototype from its parent self.settings = Object.create(this.settings); // Define the default service if (service) { self.settings.default_service = service; } // Create an instance of Events self.utils.Event.call(self); return self; }
javascript
function(service) { // Create self, which inherits from its parent var self = Object.create(this); // Inherit the prototype from its parent self.settings = Object.create(this.settings); // Define the default service if (service) { self.settings.default_service = service; } // Create an instance of Events self.utils.Event.call(self); return self; }
[ "function", "(", "service", ")", "{", "// Create self, which inherits from its parent", "var", "self", "=", "Object", ".", "create", "(", "this", ")", ";", "// Inherit the prototype from its parent", "self", ".", "settings", "=", "Object", ".", "create", "(", "this", ".", "settings", ")", ";", "// Define the default service", "if", "(", "service", ")", "{", "self", ".", "settings", ".", "default_service", "=", "service", ";", "}", "// Create an instance of Events", "self", ".", "utils", ".", "Event", ".", "call", "(", "self", ")", ";", "return", "self", ";", "}" ]
Use Define a new instance of the HelloJS library with a default service
[ "Use", "Define", "a", "new", "instance", "of", "the", "HelloJS", "library", "with", "a", "default", "service" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L262-L279
11,342
MrSwitch/hello.js
dist/hello.all.js
function(services, options) { var utils = this.utils; if (!services) { return this.services; } // Define provider credentials // Reformat the ID field for (var x in services) {if (services.hasOwnProperty(x)) { if (typeof (services[x]) !== 'object') { services[x] = {id: services[x]}; } }} // Merge services if there already exists some utils.extend(this.services, services); // Update the default settings with this one. if (options) { utils.extend(this.settings, options); // Do this immediatly incase the browser changes the current path. if ('redirect_uri' in options) { this.settings.redirect_uri = utils.url(options.redirect_uri).href; } } return this; }
javascript
function(services, options) { var utils = this.utils; if (!services) { return this.services; } // Define provider credentials // Reformat the ID field for (var x in services) {if (services.hasOwnProperty(x)) { if (typeof (services[x]) !== 'object') { services[x] = {id: services[x]}; } }} // Merge services if there already exists some utils.extend(this.services, services); // Update the default settings with this one. if (options) { utils.extend(this.settings, options); // Do this immediatly incase the browser changes the current path. if ('redirect_uri' in options) { this.settings.redirect_uri = utils.url(options.redirect_uri).href; } } return this; }
[ "function", "(", "services", ",", "options", ")", "{", "var", "utils", "=", "this", ".", "utils", ";", "if", "(", "!", "services", ")", "{", "return", "this", ".", "services", ";", "}", "// Define provider credentials", "// Reformat the ID field", "for", "(", "var", "x", "in", "services", ")", "{", "if", "(", "services", ".", "hasOwnProperty", "(", "x", ")", ")", "{", "if", "(", "typeof", "(", "services", "[", "x", "]", ")", "!==", "'object'", ")", "{", "services", "[", "x", "]", "=", "{", "id", ":", "services", "[", "x", "]", "}", ";", "}", "}", "}", "// Merge services if there already exists some", "utils", ".", "extend", "(", "this", ".", "services", ",", "services", ")", ";", "// Update the default settings with this one.", "if", "(", "options", ")", "{", "utils", ".", "extend", "(", "this", ".", "settings", ",", "options", ")", ";", "// Do this immediatly incase the browser changes the current path.", "if", "(", "'redirect_uri'", "in", "options", ")", "{", "this", ".", "settings", ".", "redirect_uri", "=", "utils", ".", "url", "(", "options", ".", "redirect_uri", ")", ".", "href", ";", "}", "}", "return", "this", ";", "}" ]
Initialize Define the client_ids for the endpoint services @param object o, contains a key value pair, service => clientId @param object opts, contains a key value pair of options used for defining the authentication defaults @param number timeout, timeout in seconds
[ "Initialize", "Define", "the", "client_ids", "for", "the", "endpoint", "services" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L286-L316
11,343
MrSwitch/hello.js
dist/hello.all.js
function() { var _this = this; var utils = _this.utils; var error = utils.error; // Create a new promise var promise = utils.Promise(); var p = utils.args({name:'s', options: 'o', callback: 'f'}, arguments); p.options = p.options || {}; // Add callback to events promise.proxy.then(p.callback, p.callback); // Trigger an event on the global listener function emit(s, value) { hello.emit(s, value); } promise.proxy.then(emit.bind(this, 'auth.logout auth'), emit.bind(this, 'error')); // Network p.name = p.name || this.settings.default_service; p.authResponse = utils.store(p.name); if (p.name && !(p.name in _this.services)) { promise.reject(error('invalid_network', 'The network was unrecognized')); } else if (p.name && p.authResponse) { // Define the callback var callback = function(opts) { // Remove from the store utils.store(p.name, null); // Emit events by default promise.fulfill(hello.utils.merge({network:p.name}, opts || {})); }; // Run an async operation to remove the users session var _opts = {}; if (p.options.force) { var logout = _this.services[p.name].logout; if (logout) { // Convert logout to URL string, // If no string is returned, then this function will handle the logout async style if (typeof (logout) === 'function') { logout = logout(callback, p); } // If logout is a string then assume URL and open in iframe. if (typeof (logout) === 'string') { utils.iframe(logout); _opts.force = null; _opts.message = 'Logout success on providers site was indeterminate'; } else if (logout === undefined) { // The callback function will handle the response. return promise.proxy; } } } // Remove local credentials callback(_opts); } else { promise.reject(error('invalid_session', 'There was no session to remove')); } return promise.proxy; }
javascript
function() { var _this = this; var utils = _this.utils; var error = utils.error; // Create a new promise var promise = utils.Promise(); var p = utils.args({name:'s', options: 'o', callback: 'f'}, arguments); p.options = p.options || {}; // Add callback to events promise.proxy.then(p.callback, p.callback); // Trigger an event on the global listener function emit(s, value) { hello.emit(s, value); } promise.proxy.then(emit.bind(this, 'auth.logout auth'), emit.bind(this, 'error')); // Network p.name = p.name || this.settings.default_service; p.authResponse = utils.store(p.name); if (p.name && !(p.name in _this.services)) { promise.reject(error('invalid_network', 'The network was unrecognized')); } else if (p.name && p.authResponse) { // Define the callback var callback = function(opts) { // Remove from the store utils.store(p.name, null); // Emit events by default promise.fulfill(hello.utils.merge({network:p.name}, opts || {})); }; // Run an async operation to remove the users session var _opts = {}; if (p.options.force) { var logout = _this.services[p.name].logout; if (logout) { // Convert logout to URL string, // If no string is returned, then this function will handle the logout async style if (typeof (logout) === 'function') { logout = logout(callback, p); } // If logout is a string then assume URL and open in iframe. if (typeof (logout) === 'string') { utils.iframe(logout); _opts.force = null; _opts.message = 'Logout success on providers site was indeterminate'; } else if (logout === undefined) { // The callback function will handle the response. return promise.proxy; } } } // Remove local credentials callback(_opts); } else { promise.reject(error('invalid_session', 'There was no session to remove')); } return promise.proxy; }
[ "function", "(", ")", "{", "var", "_this", "=", "this", ";", "var", "utils", "=", "_this", ".", "utils", ";", "var", "error", "=", "utils", ".", "error", ";", "// Create a new promise", "var", "promise", "=", "utils", ".", "Promise", "(", ")", ";", "var", "p", "=", "utils", ".", "args", "(", "{", "name", ":", "'s'", ",", "options", ":", "'o'", ",", "callback", ":", "'f'", "}", ",", "arguments", ")", ";", "p", ".", "options", "=", "p", ".", "options", "||", "{", "}", ";", "// Add callback to events", "promise", ".", "proxy", ".", "then", "(", "p", ".", "callback", ",", "p", ".", "callback", ")", ";", "// Trigger an event on the global listener", "function", "emit", "(", "s", ",", "value", ")", "{", "hello", ".", "emit", "(", "s", ",", "value", ")", ";", "}", "promise", ".", "proxy", ".", "then", "(", "emit", ".", "bind", "(", "this", ",", "'auth.logout auth'", ")", ",", "emit", ".", "bind", "(", "this", ",", "'error'", ")", ")", ";", "// Network", "p", ".", "name", "=", "p", ".", "name", "||", "this", ".", "settings", ".", "default_service", ";", "p", ".", "authResponse", "=", "utils", ".", "store", "(", "p", ".", "name", ")", ";", "if", "(", "p", ".", "name", "&&", "!", "(", "p", ".", "name", "in", "_this", ".", "services", ")", ")", "{", "promise", ".", "reject", "(", "error", "(", "'invalid_network'", ",", "'The network was unrecognized'", ")", ")", ";", "}", "else", "if", "(", "p", ".", "name", "&&", "p", ".", "authResponse", ")", "{", "// Define the callback", "var", "callback", "=", "function", "(", "opts", ")", "{", "// Remove from the store", "utils", ".", "store", "(", "p", ".", "name", ",", "null", ")", ";", "// Emit events by default", "promise", ".", "fulfill", "(", "hello", ".", "utils", ".", "merge", "(", "{", "network", ":", "p", ".", "name", "}", ",", "opts", "||", "{", "}", ")", ")", ";", "}", ";", "// Run an async operation to remove the users session", "var", "_opts", "=", "{", "}", ";", "if", "(", "p", ".", "options", ".", "force", ")", "{", "var", "logout", "=", "_this", ".", "services", "[", "p", ".", "name", "]", ".", "logout", ";", "if", "(", "logout", ")", "{", "// Convert logout to URL string,", "// If no string is returned, then this function will handle the logout async style", "if", "(", "typeof", "(", "logout", ")", "===", "'function'", ")", "{", "logout", "=", "logout", "(", "callback", ",", "p", ")", ";", "}", "// If logout is a string then assume URL and open in iframe.", "if", "(", "typeof", "(", "logout", ")", "===", "'string'", ")", "{", "utils", ".", "iframe", "(", "logout", ")", ";", "_opts", ".", "force", "=", "null", ";", "_opts", ".", "message", "=", "'Logout success on providers site was indeterminate'", ";", "}", "else", "if", "(", "logout", "===", "undefined", ")", "{", "// The callback function will handle the response.", "return", "promise", ".", "proxy", ";", "}", "}", "}", "// Remove local credentials", "callback", "(", "_opts", ")", ";", "}", "else", "{", "promise", ".", "reject", "(", "error", "(", "'invalid_session'", ",", "'There was no session to remove'", ")", ")", ";", "}", "return", "promise", ".", "proxy", ";", "}" ]
Remove any data associated with a given service @param string name of the service @param function callback
[ "Remove", "any", "data", "associated", "with", "a", "given", "service" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L596-L672
11,344
MrSwitch/hello.js
dist/hello.all.js
function(opts) { // Remove from the store utils.store(p.name, null); // Emit events by default promise.fulfill(hello.utils.merge({network:p.name}, opts || {})); }
javascript
function(opts) { // Remove from the store utils.store(p.name, null); // Emit events by default promise.fulfill(hello.utils.merge({network:p.name}, opts || {})); }
[ "function", "(", "opts", ")", "{", "// Remove from the store", "utils", ".", "store", "(", "p", ".", "name", ",", "null", ")", ";", "// Emit events by default", "promise", ".", "fulfill", "(", "hello", ".", "utils", ".", "merge", "(", "{", "network", ":", "p", ".", "name", "}", ",", "opts", "||", "{", "}", ")", ")", ";", "}" ]
Define the callback
[ "Define", "the", "callback" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L631-L638
11,345
MrSwitch/hello.js
dist/hello.all.js
function(service) { // If the service doesn't exist service = service || this.settings.default_service; if (!service || !(service in this.services)) { return null; } return this.utils.store(service) || null; }
javascript
function(service) { // If the service doesn't exist service = service || this.settings.default_service; if (!service || !(service in this.services)) { return null; } return this.utils.store(service) || null; }
[ "function", "(", "service", ")", "{", "// If the service doesn't exist", "service", "=", "service", "||", "this", ".", "settings", ".", "default_service", ";", "if", "(", "!", "service", "||", "!", "(", "service", "in", "this", ".", "services", ")", ")", "{", "return", "null", ";", "}", "return", "this", ".", "utils", ".", "store", "(", "service", ")", "||", "null", ";", "}" ]
Returns all the sessions that are subscribed too @param string optional, name of the service to get information about.
[ "Returns", "all", "the", "sessions", "that", "are", "subscribed", "too" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L676-L686
11,346
MrSwitch/hello.js
dist/hello.all.js
function(url, params, formatFunction) { if (params) { // Set default formatting function formatFunction = formatFunction || encodeURIComponent; // Override the items in the URL which already exist for (var x in params) { var str = '([\\?\\&])' + x + '=[^\\&]*'; var reg = new RegExp(str); if (url.match(reg)) { url = url.replace(reg, '$1' + x + '=' + formatFunction(params[x])); delete params[x]; } } } if (!this.isEmpty(params)) { return url + (url.indexOf('?') > -1 ? '&' : '?') + this.param(params, formatFunction); } return url; }
javascript
function(url, params, formatFunction) { if (params) { // Set default formatting function formatFunction = formatFunction || encodeURIComponent; // Override the items in the URL which already exist for (var x in params) { var str = '([\\?\\&])' + x + '=[^\\&]*'; var reg = new RegExp(str); if (url.match(reg)) { url = url.replace(reg, '$1' + x + '=' + formatFunction(params[x])); delete params[x]; } } } if (!this.isEmpty(params)) { return url + (url.indexOf('?') > -1 ? '&' : '?') + this.param(params, formatFunction); } return url; }
[ "function", "(", "url", ",", "params", ",", "formatFunction", ")", "{", "if", "(", "params", ")", "{", "// Set default formatting function", "formatFunction", "=", "formatFunction", "||", "encodeURIComponent", ";", "// Override the items in the URL which already exist", "for", "(", "var", "x", "in", "params", ")", "{", "var", "str", "=", "'([\\\\?\\\\&])'", "+", "x", "+", "'=[^\\\\&]*'", ";", "var", "reg", "=", "new", "RegExp", "(", "str", ")", ";", "if", "(", "url", ".", "match", "(", "reg", ")", ")", "{", "url", "=", "url", ".", "replace", "(", "reg", ",", "'$1'", "+", "x", "+", "'='", "+", "formatFunction", "(", "params", "[", "x", "]", ")", ")", ";", "delete", "params", "[", "x", "]", ";", "}", "}", "}", "if", "(", "!", "this", ".", "isEmpty", "(", "params", ")", ")", "{", "return", "url", "+", "(", "url", ".", "indexOf", "(", "'?'", ")", ">", "-", "1", "?", "'&'", ":", "'?'", ")", "+", "this", ".", "param", "(", "params", ",", "formatFunction", ")", ";", "}", "return", "url", ";", "}" ]
Append the querystring to a url @param string url @param object parameters
[ "Append", "the", "querystring", "to", "a", "url" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L708-L731
11,347
MrSwitch/hello.js
dist/hello.all.js
function(node, attr, target) { var n = typeof (node) === 'string' ? document.createElement(node) : node; if (typeof (attr) === 'object') { if ('tagName' in attr) { target = attr; } else { for (var x in attr) {if (attr.hasOwnProperty(x)) { if (typeof (attr[x]) === 'object') { for (var y in attr[x]) {if (attr[x].hasOwnProperty(y)) { n[x][y] = attr[x][y]; }} } else if (x === 'html') { n.innerHTML = attr[x]; } // IE doesn't like us setting methods with setAttribute else if (!/^on/.test(x)) { n.setAttribute(x, attr[x]); } else { n[x] = attr[x]; } }} } } if (target === 'body') { (function self() { if (document.body) { document.body.appendChild(n); } else { setTimeout(self, 16); } })(); } else if (typeof (target) === 'object') { target.appendChild(n); } else if (typeof (target) === 'string') { document.getElementsByTagName(target)[0].appendChild(n); } return n; }
javascript
function(node, attr, target) { var n = typeof (node) === 'string' ? document.createElement(node) : node; if (typeof (attr) === 'object') { if ('tagName' in attr) { target = attr; } else { for (var x in attr) {if (attr.hasOwnProperty(x)) { if (typeof (attr[x]) === 'object') { for (var y in attr[x]) {if (attr[x].hasOwnProperty(y)) { n[x][y] = attr[x][y]; }} } else if (x === 'html') { n.innerHTML = attr[x]; } // IE doesn't like us setting methods with setAttribute else if (!/^on/.test(x)) { n.setAttribute(x, attr[x]); } else { n[x] = attr[x]; } }} } } if (target === 'body') { (function self() { if (document.body) { document.body.appendChild(n); } else { setTimeout(self, 16); } })(); } else if (typeof (target) === 'object') { target.appendChild(n); } else if (typeof (target) === 'string') { document.getElementsByTagName(target)[0].appendChild(n); } return n; }
[ "function", "(", "node", ",", "attr", ",", "target", ")", "{", "var", "n", "=", "typeof", "(", "node", ")", "===", "'string'", "?", "document", ".", "createElement", "(", "node", ")", ":", "node", ";", "if", "(", "typeof", "(", "attr", ")", "===", "'object'", ")", "{", "if", "(", "'tagName'", "in", "attr", ")", "{", "target", "=", "attr", ";", "}", "else", "{", "for", "(", "var", "x", "in", "attr", ")", "{", "if", "(", "attr", ".", "hasOwnProperty", "(", "x", ")", ")", "{", "if", "(", "typeof", "(", "attr", "[", "x", "]", ")", "===", "'object'", ")", "{", "for", "(", "var", "y", "in", "attr", "[", "x", "]", ")", "{", "if", "(", "attr", "[", "x", "]", ".", "hasOwnProperty", "(", "y", ")", ")", "{", "n", "[", "x", "]", "[", "y", "]", "=", "attr", "[", "x", "]", "[", "y", "]", ";", "}", "}", "}", "else", "if", "(", "x", "===", "'html'", ")", "{", "n", ".", "innerHTML", "=", "attr", "[", "x", "]", ";", "}", "// IE doesn't like us setting methods with setAttribute", "else", "if", "(", "!", "/", "^on", "/", ".", "test", "(", "x", ")", ")", "{", "n", ".", "setAttribute", "(", "x", ",", "attr", "[", "x", "]", ")", ";", "}", "else", "{", "n", "[", "x", "]", "=", "attr", "[", "x", "]", ";", "}", "}", "}", "}", "}", "if", "(", "target", "===", "'body'", ")", "{", "(", "function", "self", "(", ")", "{", "if", "(", "document", ".", "body", ")", "{", "document", ".", "body", ".", "appendChild", "(", "n", ")", ";", "}", "else", "{", "setTimeout", "(", "self", ",", "16", ")", ";", "}", "}", ")", "(", ")", ";", "}", "else", "if", "(", "typeof", "(", "target", ")", "===", "'object'", ")", "{", "target", ".", "appendChild", "(", "n", ")", ";", "}", "else", "if", "(", "typeof", "(", "target", ")", "===", "'string'", ")", "{", "document", ".", "getElementsByTagName", "(", "target", ")", "[", "0", "]", ".", "appendChild", "(", "n", ")", ";", "}", "return", "n", ";", "}" ]
Create and Append new DOM elements @param node string @param attr object literal @param dom/string
[ "Create", "and", "Append", "new", "DOM", "elements" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L873-L921
11,348
MrSwitch/hello.js
dist/hello.all.js
function(src) { this.append('iframe', {src: src, style: {position:'absolute', left: '-1000px', bottom: 0, height: '1px', width: '1px'}}, 'body'); }
javascript
function(src) { this.append('iframe', {src: src, style: {position:'absolute', left: '-1000px', bottom: 0, height: '1px', width: '1px'}}, 'body'); }
[ "function", "(", "src", ")", "{", "this", ".", "append", "(", "'iframe'", ",", "{", "src", ":", "src", ",", "style", ":", "{", "position", ":", "'absolute'", ",", "left", ":", "'-1000px'", ",", "bottom", ":", "0", ",", "height", ":", "'1px'", ",", "width", ":", "'1px'", "}", "}", ",", "'body'", ")", ";", "}" ]
An easy way to create a hidden iframe @param string src
[ "An", "easy", "way", "to", "create", "a", "hidden", "iframe" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L925-L927
11,349
MrSwitch/hello.js
dist/hello.all.js
function(path) { // If the path is empty if (!path) { return window.location; } // Chrome and FireFox support new URL() to extract URL objects else if (window.URL && URL instanceof Function && URL.length !== 0) { return new URL(path, window.location); } // Ugly shim, it works! else { var a = document.createElement('a'); a.href = path; return a.cloneNode(false); } }
javascript
function(path) { // If the path is empty if (!path) { return window.location; } // Chrome and FireFox support new URL() to extract URL objects else if (window.URL && URL instanceof Function && URL.length !== 0) { return new URL(path, window.location); } // Ugly shim, it works! else { var a = document.createElement('a'); a.href = path; return a.cloneNode(false); } }
[ "function", "(", "path", ")", "{", "// If the path is empty", "if", "(", "!", "path", ")", "{", "return", "window", ".", "location", ";", "}", "// Chrome and FireFox support new URL() to extract URL objects", "else", "if", "(", "window", ".", "URL", "&&", "URL", "instanceof", "Function", "&&", "URL", ".", "length", "!==", "0", ")", "{", "return", "new", "URL", "(", "path", ",", "window", ".", "location", ")", ";", "}", "// Ugly shim, it works!", "else", "{", "var", "a", "=", "document", ".", "createElement", "(", "'a'", ")", ";", "a", ".", "href", "=", "path", ";", "return", "a", ".", "cloneNode", "(", "false", ")", ";", "}", "}" ]
Returns a URL instance
[ "Returns", "a", "URL", "instance" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L993-L1011
11,350
MrSwitch/hello.js
dist/hello.all.js
function(a, b) { if (a || !b) { var r = {}; for (var x in a) { // Does the property not exist? if (!(x in b)) { r[x] = a[x]; } } return r; } return a; }
javascript
function(a, b) { if (a || !b) { var r = {}; for (var x in a) { // Does the property not exist? if (!(x in b)) { r[x] = a[x]; } } return r; } return a; }
[ "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", "||", "!", "b", ")", "{", "var", "r", "=", "{", "}", ";", "for", "(", "var", "x", "in", "a", ")", "{", "// Does the property not exist?", "if", "(", "!", "(", "x", "in", "b", ")", ")", "{", "r", "[", "x", "]", "=", "a", "[", "x", "]", ";", "}", "}", "return", "r", ";", "}", "return", "a", ";", "}" ]
Get the different hash of properties unique to `a`, and not in `b`
[ "Get", "the", "different", "hash", "of", "properties", "unique", "to", "a", "and", "not", "in", "b" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L1020-L1034
11,351
MrSwitch/hello.js
dist/hello.all.js
function(a) { if (!Array.isArray(a)) { return []; } return a.filter(function(item, index) { // Is this the first location of item return a.indexOf(item) === index; }); }
javascript
function(a) { if (!Array.isArray(a)) { return []; } return a.filter(function(item, index) { // Is this the first location of item return a.indexOf(item) === index; }); }
[ "function", "(", "a", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "a", ")", ")", "{", "return", "[", "]", ";", "}", "return", "a", ".", "filter", "(", "function", "(", "item", ",", "index", ")", "{", "// Is this the first location of item", "return", "a", ".", "indexOf", "(", "item", ")", "===", "index", ";", "}", ")", ";", "}" ]
Unique Remove duplicate and null values from an array @param a array
[ "Unique", "Remove", "duplicate", "and", "null", "values", "from", "an", "array" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L1039-L1046
11,352
MrSwitch/hello.js
dist/hello.all.js
function(callback, guid) { // If the guid has not been supplied then create a new one. guid = guid || '_hellojs_' + parseInt(Math.random() * 1e12, 10).toString(36); // Define the callback function window[guid] = function() { // Trigger the callback try { if (callback.apply(this, arguments)) { delete window[guid]; } } catch (e) { console.error(e); } }; return guid; }
javascript
function(callback, guid) { // If the guid has not been supplied then create a new one. guid = guid || '_hellojs_' + parseInt(Math.random() * 1e12, 10).toString(36); // Define the callback function window[guid] = function() { // Trigger the callback try { if (callback.apply(this, arguments)) { delete window[guid]; } } catch (e) { console.error(e); } }; return guid; }
[ "function", "(", "callback", ",", "guid", ")", "{", "// If the guid has not been supplied then create a new one.", "guid", "=", "guid", "||", "'_hellojs_'", "+", "parseInt", "(", "Math", ".", "random", "(", ")", "*", "1e12", ",", "10", ")", ".", "toString", "(", "36", ")", ";", "// Define the callback function", "window", "[", "guid", "]", "=", "function", "(", ")", "{", "// Trigger the callback", "try", "{", "if", "(", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ")", "{", "delete", "window", "[", "guid", "]", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", ";", "}", "}", ";", "return", "guid", ";", "}" ]
Global Events Attach the callback to the window object Return its unique reference
[ "Global", "Events", "Attach", "the", "callback", "to", "the", "window", "object", "Return", "its", "unique", "reference" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L1364-L1382
11,353
MrSwitch/hello.js
dist/hello.all.js
function(url, redirectUri, options) { var documentElement = document.documentElement; // Multi Screen Popup Positioning (http://stackoverflow.com/a/16861050) // Credit: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html // Fixes dual-screen position Most browsers Firefox if (options.height && options.top === undefined) { var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top; var height = screen.height || window.innerHeight || documentElement.clientHeight; options.top = parseInt((height - options.height) / 2, 10) + dualScreenTop; } if (options.width && options.left === undefined) { var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left; var width = screen.width || window.innerWidth || documentElement.clientWidth; options.left = parseInt((width - options.width) / 2, 10) + dualScreenLeft; } // Convert options into an array var optionsArray = []; Object.keys(options).forEach(function(name) { var value = options[name]; optionsArray.push(name + (value !== null ? '=' + value : '')); }); // Call the open() function with the initial path // // OAuth redirect, fixes URI fragments from being lost in Safari // (URI Fragments within 302 Location URI are lost over HTTPS) // Loading the redirect.html before triggering the OAuth Flow seems to fix it. // // Firefox decodes URL fragments when calling location.hash. // - This is bad if the value contains break points which are escaped // - Hence the url must be encoded twice as it contains breakpoints. if (navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1) { url = redirectUri + '#oauth_redirect=' + encodeURIComponent(encodeURIComponent(url)); } var popup = window.open( url, '_blank', optionsArray.join(',') ); if (popup && popup.focus) { popup.focus(); } return popup; }
javascript
function(url, redirectUri, options) { var documentElement = document.documentElement; // Multi Screen Popup Positioning (http://stackoverflow.com/a/16861050) // Credit: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html // Fixes dual-screen position Most browsers Firefox if (options.height && options.top === undefined) { var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top; var height = screen.height || window.innerHeight || documentElement.clientHeight; options.top = parseInt((height - options.height) / 2, 10) + dualScreenTop; } if (options.width && options.left === undefined) { var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left; var width = screen.width || window.innerWidth || documentElement.clientWidth; options.left = parseInt((width - options.width) / 2, 10) + dualScreenLeft; } // Convert options into an array var optionsArray = []; Object.keys(options).forEach(function(name) { var value = options[name]; optionsArray.push(name + (value !== null ? '=' + value : '')); }); // Call the open() function with the initial path // // OAuth redirect, fixes URI fragments from being lost in Safari // (URI Fragments within 302 Location URI are lost over HTTPS) // Loading the redirect.html before triggering the OAuth Flow seems to fix it. // // Firefox decodes URL fragments when calling location.hash. // - This is bad if the value contains break points which are escaped // - Hence the url must be encoded twice as it contains breakpoints. if (navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1) { url = redirectUri + '#oauth_redirect=' + encodeURIComponent(encodeURIComponent(url)); } var popup = window.open( url, '_blank', optionsArray.join(',') ); if (popup && popup.focus) { popup.focus(); } return popup; }
[ "function", "(", "url", ",", "redirectUri", ",", "options", ")", "{", "var", "documentElement", "=", "document", ".", "documentElement", ";", "// Multi Screen Popup Positioning (http://stackoverflow.com/a/16861050)", "// Credit: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html", "// Fixes dual-screen position Most browsers Firefox", "if", "(", "options", ".", "height", "&&", "options", ".", "top", "===", "undefined", ")", "{", "var", "dualScreenTop", "=", "window", ".", "screenTop", "!==", "undefined", "?", "window", ".", "screenTop", ":", "screen", ".", "top", ";", "var", "height", "=", "screen", ".", "height", "||", "window", ".", "innerHeight", "||", "documentElement", ".", "clientHeight", ";", "options", ".", "top", "=", "parseInt", "(", "(", "height", "-", "options", ".", "height", ")", "/", "2", ",", "10", ")", "+", "dualScreenTop", ";", "}", "if", "(", "options", ".", "width", "&&", "options", ".", "left", "===", "undefined", ")", "{", "var", "dualScreenLeft", "=", "window", ".", "screenLeft", "!==", "undefined", "?", "window", ".", "screenLeft", ":", "screen", ".", "left", ";", "var", "width", "=", "screen", ".", "width", "||", "window", ".", "innerWidth", "||", "documentElement", ".", "clientWidth", ";", "options", ".", "left", "=", "parseInt", "(", "(", "width", "-", "options", ".", "width", ")", "/", "2", ",", "10", ")", "+", "dualScreenLeft", ";", "}", "// Convert options into an array", "var", "optionsArray", "=", "[", "]", ";", "Object", ".", "keys", "(", "options", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "value", "=", "options", "[", "name", "]", ";", "optionsArray", ".", "push", "(", "name", "+", "(", "value", "!==", "null", "?", "'='", "+", "value", ":", "''", ")", ")", ";", "}", ")", ";", "// Call the open() function with the initial path", "//", "// OAuth redirect, fixes URI fragments from being lost in Safari", "// (URI Fragments within 302 Location URI are lost over HTTPS)", "// Loading the redirect.html before triggering the OAuth Flow seems to fix it.", "//", "// Firefox decodes URL fragments when calling location.hash.", "// - This is bad if the value contains break points which are escaped", "// - Hence the url must be encoded twice as it contains breakpoints.", "if", "(", "navigator", ".", "userAgent", ".", "indexOf", "(", "'Safari'", ")", "!==", "-", "1", "&&", "navigator", ".", "userAgent", ".", "indexOf", "(", "'Chrome'", ")", "===", "-", "1", ")", "{", "url", "=", "redirectUri", "+", "'#oauth_redirect='", "+", "encodeURIComponent", "(", "encodeURIComponent", "(", "url", ")", ")", ";", "}", "var", "popup", "=", "window", ".", "open", "(", "url", ",", "'_blank'", ",", "optionsArray", ".", "join", "(", "','", ")", ")", ";", "if", "(", "popup", "&&", "popup", ".", "focus", ")", "{", "popup", ".", "focus", "(", ")", ";", "}", "return", "popup", ";", "}" ]
Trigger a clientside popup This has been augmented to support PhoneGap
[ "Trigger", "a", "clientside", "popup", "This", "has", "been", "augmented", "to", "support", "PhoneGap" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L1386-L1437
11,354
MrSwitch/hello.js
dist/hello.all.js
authCallback
function authCallback(obj, window, parent) { var cb = obj.callback; var network = obj.network; // Trigger the callback on the parent _this.store(network, obj); // If this is a page request it has no parent or opener window to handle callbacks if (('display' in obj) && obj.display === 'page') { return; } // Remove from session object if (parent && cb && cb in parent) { try { delete obj.callback; } catch (e) {} // Update store _this.store(network, obj); // Call the globalEvent function on the parent // It's safer to pass back a string to the parent, // Rather than an object/array (better for IE8) var str = JSON.stringify(obj); try { callback(parent, cb)(str); } catch (e) { // Error thrown whilst executing parent callback } } closeWindow(); }
javascript
function authCallback(obj, window, parent) { var cb = obj.callback; var network = obj.network; // Trigger the callback on the parent _this.store(network, obj); // If this is a page request it has no parent or opener window to handle callbacks if (('display' in obj) && obj.display === 'page') { return; } // Remove from session object if (parent && cb && cb in parent) { try { delete obj.callback; } catch (e) {} // Update store _this.store(network, obj); // Call the globalEvent function on the parent // It's safer to pass back a string to the parent, // Rather than an object/array (better for IE8) var str = JSON.stringify(obj); try { callback(parent, cb)(str); } catch (e) { // Error thrown whilst executing parent callback } } closeWindow(); }
[ "function", "authCallback", "(", "obj", ",", "window", ",", "parent", ")", "{", "var", "cb", "=", "obj", ".", "callback", ";", "var", "network", "=", "obj", ".", "network", ";", "// Trigger the callback on the parent", "_this", ".", "store", "(", "network", ",", "obj", ")", ";", "// If this is a page request it has no parent or opener window to handle callbacks", "if", "(", "(", "'display'", "in", "obj", ")", "&&", "obj", ".", "display", "===", "'page'", ")", "{", "return", ";", "}", "// Remove from session object", "if", "(", "parent", "&&", "cb", "&&", "cb", "in", "parent", ")", "{", "try", "{", "delete", "obj", ".", "callback", ";", "}", "catch", "(", "e", ")", "{", "}", "// Update store", "_this", ".", "store", "(", "network", ",", "obj", ")", ";", "// Call the globalEvent function on the parent", "// It's safer to pass back a string to the parent,", "// Rather than an object/array (better for IE8)", "var", "str", "=", "JSON", ".", "stringify", "(", "obj", ")", ";", "try", "{", "callback", "(", "parent", ",", "cb", ")", "(", "str", ")", ";", "}", "catch", "(", "e", ")", "{", "// Error thrown whilst executing parent callback", "}", "}", "closeWindow", "(", ")", ";", "}" ]
Trigger a callback to authenticate
[ "Trigger", "a", "callback", "to", "authenticate" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L1550-L1588
11,355
MrSwitch/hello.js
dist/hello.all.js
getPath
function getPath(url) { // Format the string if it needs it url = url.replace(/\@\{([a-z\_\-]+)(\|.*?)?\}/gi, function(m, key, defaults) { var val = defaults ? defaults.replace(/^\|/, '') : ''; if (key in p.query) { val = p.query[key]; delete p.query[key]; } else if (p.data && key in p.data) { val = p.data[key]; delete p.data[key]; } else if (!defaults) { promise.reject(error('missing_attribute', 'The attribute ' + key + ' is missing from the request')); } return val; }); // Add base if (!url.match(/^https?:\/\//)) { url = o.base + url; } // Define the request URL p.url = url; // Make the HTTP request with the curated request object // CALLBACK HANDLER // @ response object // @ statusCode integer if available utils.request(p, function(r, headers) { // Is this a raw response? if (!p.formatResponse) { // Bad request? error statusCode or otherwise contains an error response vis JSONP? if (typeof headers === 'object' ? (headers.statusCode >= 400) : (typeof r === 'object' && 'error' in r)) { promise.reject(r); } else { promise.fulfill(r); } return; } // Should this be an object if (r === true) { r = {success:true}; } else if (!r) { r = {}; } // The delete callback needs a better response if (p.method === 'delete') { r = (!r || utils.isEmpty(r)) ? {success:true} : r; } // FORMAT RESPONSE? // Does self request have a corresponding formatter if (o.wrap && ((p.path in o.wrap) || ('default' in o.wrap))) { var wrap = (p.path in o.wrap ? p.path : 'default'); var time = (new Date()).getTime(); // FORMAT RESPONSE var b = o.wrap[wrap](r, headers, p); // Has the response been utterly overwritten? // Typically self augments the existing object.. but for those rare occassions if (b) { r = b; } } // Is there a next_page defined in the response? if (r && 'paging' in r && r.paging.next) { // Add the relative path if it is missing from the paging/next path if (r.paging.next[0] === '?') { r.paging.next = p.path + r.paging.next; } // The relative path has been defined, lets markup the handler in the HashFragment else { r.paging.next += '#' + p.path; } } // Dispatch to listeners // Emit events which pertain to the formatted response if (!r || 'error' in r) { promise.reject(r); } else { promise.fulfill(r); } }); }
javascript
function getPath(url) { // Format the string if it needs it url = url.replace(/\@\{([a-z\_\-]+)(\|.*?)?\}/gi, function(m, key, defaults) { var val = defaults ? defaults.replace(/^\|/, '') : ''; if (key in p.query) { val = p.query[key]; delete p.query[key]; } else if (p.data && key in p.data) { val = p.data[key]; delete p.data[key]; } else if (!defaults) { promise.reject(error('missing_attribute', 'The attribute ' + key + ' is missing from the request')); } return val; }); // Add base if (!url.match(/^https?:\/\//)) { url = o.base + url; } // Define the request URL p.url = url; // Make the HTTP request with the curated request object // CALLBACK HANDLER // @ response object // @ statusCode integer if available utils.request(p, function(r, headers) { // Is this a raw response? if (!p.formatResponse) { // Bad request? error statusCode or otherwise contains an error response vis JSONP? if (typeof headers === 'object' ? (headers.statusCode >= 400) : (typeof r === 'object' && 'error' in r)) { promise.reject(r); } else { promise.fulfill(r); } return; } // Should this be an object if (r === true) { r = {success:true}; } else if (!r) { r = {}; } // The delete callback needs a better response if (p.method === 'delete') { r = (!r || utils.isEmpty(r)) ? {success:true} : r; } // FORMAT RESPONSE? // Does self request have a corresponding formatter if (o.wrap && ((p.path in o.wrap) || ('default' in o.wrap))) { var wrap = (p.path in o.wrap ? p.path : 'default'); var time = (new Date()).getTime(); // FORMAT RESPONSE var b = o.wrap[wrap](r, headers, p); // Has the response been utterly overwritten? // Typically self augments the existing object.. but for those rare occassions if (b) { r = b; } } // Is there a next_page defined in the response? if (r && 'paging' in r && r.paging.next) { // Add the relative path if it is missing from the paging/next path if (r.paging.next[0] === '?') { r.paging.next = p.path + r.paging.next; } // The relative path has been defined, lets markup the handler in the HashFragment else { r.paging.next += '#' + p.path; } } // Dispatch to listeners // Emit events which pertain to the formatted response if (!r || 'error' in r) { promise.reject(r); } else { promise.fulfill(r); } }); }
[ "function", "getPath", "(", "url", ")", "{", "// Format the string if it needs it", "url", "=", "url", ".", "replace", "(", "/", "\\@\\{([a-z\\_\\-]+)(\\|.*?)?\\}", "/", "gi", ",", "function", "(", "m", ",", "key", ",", "defaults", ")", "{", "var", "val", "=", "defaults", "?", "defaults", ".", "replace", "(", "/", "^\\|", "/", ",", "''", ")", ":", "''", ";", "if", "(", "key", "in", "p", ".", "query", ")", "{", "val", "=", "p", ".", "query", "[", "key", "]", ";", "delete", "p", ".", "query", "[", "key", "]", ";", "}", "else", "if", "(", "p", ".", "data", "&&", "key", "in", "p", ".", "data", ")", "{", "val", "=", "p", ".", "data", "[", "key", "]", ";", "delete", "p", ".", "data", "[", "key", "]", ";", "}", "else", "if", "(", "!", "defaults", ")", "{", "promise", ".", "reject", "(", "error", "(", "'missing_attribute'", ",", "'The attribute '", "+", "key", "+", "' is missing from the request'", ")", ")", ";", "}", "return", "val", ";", "}", ")", ";", "// Add base", "if", "(", "!", "url", ".", "match", "(", "/", "^https?:\\/\\/", "/", ")", ")", "{", "url", "=", "o", ".", "base", "+", "url", ";", "}", "// Define the request URL", "p", ".", "url", "=", "url", ";", "// Make the HTTP request with the curated request object", "// CALLBACK HANDLER", "// @ response object", "// @ statusCode integer if available", "utils", ".", "request", "(", "p", ",", "function", "(", "r", ",", "headers", ")", "{", "// Is this a raw response?", "if", "(", "!", "p", ".", "formatResponse", ")", "{", "// Bad request? error statusCode or otherwise contains an error response vis JSONP?", "if", "(", "typeof", "headers", "===", "'object'", "?", "(", "headers", ".", "statusCode", ">=", "400", ")", ":", "(", "typeof", "r", "===", "'object'", "&&", "'error'", "in", "r", ")", ")", "{", "promise", ".", "reject", "(", "r", ")", ";", "}", "else", "{", "promise", ".", "fulfill", "(", "r", ")", ";", "}", "return", ";", "}", "// Should this be an object", "if", "(", "r", "===", "true", ")", "{", "r", "=", "{", "success", ":", "true", "}", ";", "}", "else", "if", "(", "!", "r", ")", "{", "r", "=", "{", "}", ";", "}", "// The delete callback needs a better response", "if", "(", "p", ".", "method", "===", "'delete'", ")", "{", "r", "=", "(", "!", "r", "||", "utils", ".", "isEmpty", "(", "r", ")", ")", "?", "{", "success", ":", "true", "}", ":", "r", ";", "}", "// FORMAT RESPONSE?", "// Does self request have a corresponding formatter", "if", "(", "o", ".", "wrap", "&&", "(", "(", "p", ".", "path", "in", "o", ".", "wrap", ")", "||", "(", "'default'", "in", "o", ".", "wrap", ")", ")", ")", "{", "var", "wrap", "=", "(", "p", ".", "path", "in", "o", ".", "wrap", "?", "p", ".", "path", ":", "'default'", ")", ";", "var", "time", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", ";", "// FORMAT RESPONSE", "var", "b", "=", "o", ".", "wrap", "[", "wrap", "]", "(", "r", ",", "headers", ",", "p", ")", ";", "// Has the response been utterly overwritten?", "// Typically self augments the existing object.. but for those rare occassions", "if", "(", "b", ")", "{", "r", "=", "b", ";", "}", "}", "// Is there a next_page defined in the response?", "if", "(", "r", "&&", "'paging'", "in", "r", "&&", "r", ".", "paging", ".", "next", ")", "{", "// Add the relative path if it is missing from the paging/next path", "if", "(", "r", ".", "paging", ".", "next", "[", "0", "]", "===", "'?'", ")", "{", "r", ".", "paging", ".", "next", "=", "p", ".", "path", "+", "r", ".", "paging", ".", "next", ";", "}", "// The relative path has been defined, lets markup the handler in the HashFragment", "else", "{", "r", ".", "paging", ".", "next", "+=", "'#'", "+", "p", ".", "path", ";", "}", "}", "// Dispatch to listeners", "// Emit events which pertain to the formatted response", "if", "(", "!", "r", "||", "'error'", "in", "r", ")", "{", "promise", ".", "reject", "(", "r", ")", ";", "}", "else", "{", "promise", ".", "fulfill", "(", "r", ")", ";", "}", "}", ")", ";", "}" ]
If url needs a base Wrap everything in
[ "If", "url", "needs", "a", "base", "Wrap", "everything", "in" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L1934-L2033
11,356
MrSwitch/hello.js
dist/hello.all.js
formatUrl
function formatUrl(p, callback) { // Are we signing the request? var sign; // OAuth1 // Remove the token from the query before signing if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) { // OAUTH SIGNING PROXY sign = p.query.access_token; // Remove the access_token delete p.query.access_token; // Enfore use of Proxy p.proxy = true; } // POST body to querystring if (p.data && (p.method === 'get' || p.method === 'delete')) { // Attach the p.data to the querystring. _this.extend(p.query, p.data); p.data = null; } // Construct the path var path = _this.qs(p.url, p.query); // Proxy the request through a server // Used for signing OAuth1 // And circumventing services without Access-Control Headers if (p.proxy) { // Use the proxy as a path path = _this.qs(p.oauth_proxy, { path: path, access_token: sign || '', // This will prompt the request to be signed as though it is OAuth1 then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'), method: p.method.toLowerCase(), suppress_response_codes: true }); } callback(path); }
javascript
function formatUrl(p, callback) { // Are we signing the request? var sign; // OAuth1 // Remove the token from the query before signing if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) { // OAUTH SIGNING PROXY sign = p.query.access_token; // Remove the access_token delete p.query.access_token; // Enfore use of Proxy p.proxy = true; } // POST body to querystring if (p.data && (p.method === 'get' || p.method === 'delete')) { // Attach the p.data to the querystring. _this.extend(p.query, p.data); p.data = null; } // Construct the path var path = _this.qs(p.url, p.query); // Proxy the request through a server // Used for signing OAuth1 // And circumventing services without Access-Control Headers if (p.proxy) { // Use the proxy as a path path = _this.qs(p.oauth_proxy, { path: path, access_token: sign || '', // This will prompt the request to be signed as though it is OAuth1 then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'), method: p.method.toLowerCase(), suppress_response_codes: true }); } callback(path); }
[ "function", "formatUrl", "(", "p", ",", "callback", ")", "{", "// Are we signing the request?", "var", "sign", ";", "// OAuth1", "// Remove the token from the query before signing", "if", "(", "p", ".", "authResponse", "&&", "p", ".", "authResponse", ".", "oauth", "&&", "parseInt", "(", "p", ".", "authResponse", ".", "oauth", ".", "version", ",", "10", ")", "===", "1", ")", "{", "// OAUTH SIGNING PROXY", "sign", "=", "p", ".", "query", ".", "access_token", ";", "// Remove the access_token", "delete", "p", ".", "query", ".", "access_token", ";", "// Enfore use of Proxy", "p", ".", "proxy", "=", "true", ";", "}", "// POST body to querystring", "if", "(", "p", ".", "data", "&&", "(", "p", ".", "method", "===", "'get'", "||", "p", ".", "method", "===", "'delete'", ")", ")", "{", "// Attach the p.data to the querystring.", "_this", ".", "extend", "(", "p", ".", "query", ",", "p", ".", "data", ")", ";", "p", ".", "data", "=", "null", ";", "}", "// Construct the path", "var", "path", "=", "_this", ".", "qs", "(", "p", ".", "url", ",", "p", ".", "query", ")", ";", "// Proxy the request through a server", "// Used for signing OAuth1", "// And circumventing services without Access-Control Headers", "if", "(", "p", ".", "proxy", ")", "{", "// Use the proxy as a path", "path", "=", "_this", ".", "qs", "(", "p", ".", "oauth_proxy", ",", "{", "path", ":", "path", ",", "access_token", ":", "sign", "||", "''", ",", "// This will prompt the request to be signed as though it is OAuth1", "then", ":", "p", ".", "proxy_response_type", "||", "(", "p", ".", "method", ".", "toLowerCase", "(", ")", "===", "'get'", "?", "'redirect'", ":", "'proxy'", ")", ",", "method", ":", "p", ".", "method", ".", "toLowerCase", "(", ")", ",", "suppress_response_codes", ":", "true", "}", ")", ";", "}", "callback", "(", "path", ")", ";", "}" ]
Format URL Constructs the request URL, optionally wraps the URL through a call to a proxy server Returns the formatted URL
[ "Format", "URL", "Constructs", "the", "request", "URL", "optionally", "wraps", "the", "URL", "through", "a", "call", "to", "a", "proxy", "server", "Returns", "the", "formatted", "URL" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2147-L2193
11,357
MrSwitch/hello.js
dist/hello.all.js
function(type, data) { var test = 'HTML' + (type || '').replace( /^[a-z]/, function(m) { return m.toUpperCase(); } ) + 'Element'; if (!data) { return false; } if (window[test]) { return data instanceof window[test]; } else if (window.Element) { return data instanceof window.Element && (!type || (data.tagName && data.tagName.toLowerCase() === type)); } else { return (!(data instanceof Object || data instanceof Array || data instanceof String || data instanceof Number) && data.tagName && data.tagName.toLowerCase() === type); } }
javascript
function(type, data) { var test = 'HTML' + (type || '').replace( /^[a-z]/, function(m) { return m.toUpperCase(); } ) + 'Element'; if (!data) { return false; } if (window[test]) { return data instanceof window[test]; } else if (window.Element) { return data instanceof window.Element && (!type || (data.tagName && data.tagName.toLowerCase() === type)); } else { return (!(data instanceof Object || data instanceof Array || data instanceof String || data instanceof Number) && data.tagName && data.tagName.toLowerCase() === type); } }
[ "function", "(", "type", ",", "data", ")", "{", "var", "test", "=", "'HTML'", "+", "(", "type", "||", "''", ")", ".", "replace", "(", "/", "^[a-z]", "/", ",", "function", "(", "m", ")", "{", "return", "m", ".", "toUpperCase", "(", ")", ";", "}", ")", "+", "'Element'", ";", "if", "(", "!", "data", ")", "{", "return", "false", ";", "}", "if", "(", "window", "[", "test", "]", ")", "{", "return", "data", "instanceof", "window", "[", "test", "]", ";", "}", "else", "if", "(", "window", ".", "Element", ")", "{", "return", "data", "instanceof", "window", ".", "Element", "&&", "(", "!", "type", "||", "(", "data", ".", "tagName", "&&", "data", ".", "tagName", ".", "toLowerCase", "(", ")", "===", "type", ")", ")", ";", "}", "else", "{", "return", "(", "!", "(", "data", "instanceof", "Object", "||", "data", "instanceof", "Array", "||", "data", "instanceof", "String", "||", "data", "instanceof", "Number", ")", "&&", "data", ".", "tagName", "&&", "data", ".", "tagName", ".", "toLowerCase", "(", ")", "===", "type", ")", ";", "}", "}" ]
Return the type of DOM object
[ "Return", "the", "type", "of", "DOM", "object" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2202-L2224
11,358
MrSwitch/hello.js
dist/hello.all.js
function(obj) { // Does not clone DOM elements, nor Binary data, e.g. Blobs, Filelists if (obj === null || typeof (obj) !== 'object' || obj instanceof Date || 'nodeName' in obj || this.isBinary(obj) || (typeof FormData === 'function' && obj instanceof FormData)) { return obj; } if (Array.isArray(obj)) { // Clone each item in the array return obj.map(this.clone.bind(this)); } // But does clone everything else. var clone = {}; for (var x in obj) { clone[x] = this.clone(obj[x]); } return clone; }
javascript
function(obj) { // Does not clone DOM elements, nor Binary data, e.g. Blobs, Filelists if (obj === null || typeof (obj) !== 'object' || obj instanceof Date || 'nodeName' in obj || this.isBinary(obj) || (typeof FormData === 'function' && obj instanceof FormData)) { return obj; } if (Array.isArray(obj)) { // Clone each item in the array return obj.map(this.clone.bind(this)); } // But does clone everything else. var clone = {}; for (var x in obj) { clone[x] = this.clone(obj[x]); } return clone; }
[ "function", "(", "obj", ")", "{", "// Does not clone DOM elements, nor Binary data, e.g. Blobs, Filelists", "if", "(", "obj", "===", "null", "||", "typeof", "(", "obj", ")", "!==", "'object'", "||", "obj", "instanceof", "Date", "||", "'nodeName'", "in", "obj", "||", "this", ".", "isBinary", "(", "obj", ")", "||", "(", "typeof", "FormData", "===", "'function'", "&&", "obj", "instanceof", "FormData", ")", ")", "{", "return", "obj", ";", "}", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "// Clone each item in the array", "return", "obj", ".", "map", "(", "this", ".", "clone", ".", "bind", "(", "this", ")", ")", ";", "}", "// But does clone everything else.", "var", "clone", "=", "{", "}", ";", "for", "(", "var", "x", "in", "obj", ")", "{", "clone", "[", "x", "]", "=", "this", ".", "clone", "(", "obj", "[", "x", "]", ")", ";", "}", "return", "clone", ";", "}" ]
Create a clone of an object
[ "Create", "a", "clone", "of", "an", "object" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2227-L2245
11,359
MrSwitch/hello.js
dist/hello.all.js
headersToJSON
function headersToJSON(s) { var r = {}; var reg = /([a-z\-]+):\s?(.*);?/gi; var m; while ((m = reg.exec(s))) { r[m[1]] = m[2]; } return r; }
javascript
function headersToJSON(s) { var r = {}; var reg = /([a-z\-]+):\s?(.*);?/gi; var m; while ((m = reg.exec(s))) { r[m[1]] = m[2]; } return r; }
[ "function", "headersToJSON", "(", "s", ")", "{", "var", "r", "=", "{", "}", ";", "var", "reg", "=", "/", "([a-z\\-]+):\\s?(.*);?", "/", "gi", ";", "var", "m", ";", "while", "(", "(", "m", "=", "reg", ".", "exec", "(", "s", ")", ")", ")", "{", "r", "[", "m", "[", "1", "]", "]", "=", "m", "[", "2", "]", ";", "}", "return", "r", ";", "}" ]
Headers are returned as a string
[ "Headers", "are", "returned", "as", "a", "string" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2340-L2349
11,360
MrSwitch/hello.js
dist/hello.all.js
function(url, callback, callbackID, timeout) { var _this = this; var error = _this.error; // Change the name of the callback var bool = 0; var head = document.getElementsByTagName('head')[0]; var operaFix; var result = error('server_error', 'server_error'); var cb = function() { if (!(bool++)) { window.setTimeout(function() { callback(result); head.removeChild(script); }, 0); } }; // Add callback to the window object callbackID = _this.globalEvent(function(json) { result = json; return true; // Mark callback as done }, callbackID); // The URL is a function for some cases and as such // Determine its value with a callback containing the new parameters of this function. url = url.replace(new RegExp('=\\?(&|$)'), '=' + callbackID + '$1'); // Build script tag var script = _this.append('script', { id: callbackID, name: callbackID, src: url, async: true, onload: cb, onerror: cb, onreadystatechange: function() { if (/loaded|complete/i.test(this.readyState)) { cb(); } } }); // Opera fix error // Problem: If an error occurs with script loading Opera fails to trigger the script.onerror handler we specified // // Fix: // By setting the request to synchronous we can trigger the error handler when all else fails. // This action will be ignored if we've already called the callback handler "cb" with a successful onload event if (window.navigator.userAgent.toLowerCase().indexOf('opera') > -1) { operaFix = _this.append('script', { text: 'document.getElementById(\'' + callbackID + '\').onerror();' }); script.async = false; } // Add timeout if (timeout) { window.setTimeout(function() { result = error('timeout', 'timeout'); cb(); }, timeout); } // TODO: add fix for IE, // However: unable recreate the bug of firing off the onreadystatechange before the script content has been executed and the value of "result" has been defined. // Inject script tag into the head element head.appendChild(script); // Append Opera Fix to run after our script if (operaFix) { head.appendChild(operaFix); } }
javascript
function(url, callback, callbackID, timeout) { var _this = this; var error = _this.error; // Change the name of the callback var bool = 0; var head = document.getElementsByTagName('head')[0]; var operaFix; var result = error('server_error', 'server_error'); var cb = function() { if (!(bool++)) { window.setTimeout(function() { callback(result); head.removeChild(script); }, 0); } }; // Add callback to the window object callbackID = _this.globalEvent(function(json) { result = json; return true; // Mark callback as done }, callbackID); // The URL is a function for some cases and as such // Determine its value with a callback containing the new parameters of this function. url = url.replace(new RegExp('=\\?(&|$)'), '=' + callbackID + '$1'); // Build script tag var script = _this.append('script', { id: callbackID, name: callbackID, src: url, async: true, onload: cb, onerror: cb, onreadystatechange: function() { if (/loaded|complete/i.test(this.readyState)) { cb(); } } }); // Opera fix error // Problem: If an error occurs with script loading Opera fails to trigger the script.onerror handler we specified // // Fix: // By setting the request to synchronous we can trigger the error handler when all else fails. // This action will be ignored if we've already called the callback handler "cb" with a successful onload event if (window.navigator.userAgent.toLowerCase().indexOf('opera') > -1) { operaFix = _this.append('script', { text: 'document.getElementById(\'' + callbackID + '\').onerror();' }); script.async = false; } // Add timeout if (timeout) { window.setTimeout(function() { result = error('timeout', 'timeout'); cb(); }, timeout); } // TODO: add fix for IE, // However: unable recreate the bug of firing off the onreadystatechange before the script content has been executed and the value of "result" has been defined. // Inject script tag into the head element head.appendChild(script); // Append Opera Fix to run after our script if (operaFix) { head.appendChild(operaFix); } }
[ "function", "(", "url", ",", "callback", ",", "callbackID", ",", "timeout", ")", "{", "var", "_this", "=", "this", ";", "var", "error", "=", "_this", ".", "error", ";", "// Change the name of the callback", "var", "bool", "=", "0", ";", "var", "head", "=", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ";", "var", "operaFix", ";", "var", "result", "=", "error", "(", "'server_error'", ",", "'server_error'", ")", ";", "var", "cb", "=", "function", "(", ")", "{", "if", "(", "!", "(", "bool", "++", ")", ")", "{", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "callback", "(", "result", ")", ";", "head", ".", "removeChild", "(", "script", ")", ";", "}", ",", "0", ")", ";", "}", "}", ";", "// Add callback to the window object", "callbackID", "=", "_this", ".", "globalEvent", "(", "function", "(", "json", ")", "{", "result", "=", "json", ";", "return", "true", ";", "// Mark callback as done", "}", ",", "callbackID", ")", ";", "// The URL is a function for some cases and as such", "// Determine its value with a callback containing the new parameters of this function.", "url", "=", "url", ".", "replace", "(", "new", "RegExp", "(", "'=\\\\?(&|$)'", ")", ",", "'='", "+", "callbackID", "+", "'$1'", ")", ";", "// Build script tag", "var", "script", "=", "_this", ".", "append", "(", "'script'", ",", "{", "id", ":", "callbackID", ",", "name", ":", "callbackID", ",", "src", ":", "url", ",", "async", ":", "true", ",", "onload", ":", "cb", ",", "onerror", ":", "cb", ",", "onreadystatechange", ":", "function", "(", ")", "{", "if", "(", "/", "loaded|complete", "/", "i", ".", "test", "(", "this", ".", "readyState", ")", ")", "{", "cb", "(", ")", ";", "}", "}", "}", ")", ";", "// Opera fix error", "// Problem: If an error occurs with script loading Opera fails to trigger the script.onerror handler we specified", "//", "// Fix:", "// By setting the request to synchronous we can trigger the error handler when all else fails.", "// This action will be ignored if we've already called the callback handler \"cb\" with a successful onload event", "if", "(", "window", ".", "navigator", ".", "userAgent", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "'opera'", ")", ">", "-", "1", ")", "{", "operaFix", "=", "_this", ".", "append", "(", "'script'", ",", "{", "text", ":", "'document.getElementById(\\''", "+", "callbackID", "+", "'\\').onerror();'", "}", ")", ";", "script", ".", "async", "=", "false", ";", "}", "// Add timeout", "if", "(", "timeout", ")", "{", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "result", "=", "error", "(", "'timeout'", ",", "'timeout'", ")", ";", "cb", "(", ")", ";", "}", ",", "timeout", ")", ";", "}", "// TODO: add fix for IE,", "// However: unable recreate the bug of firing off the onreadystatechange before the script content has been executed and the value of \"result\" has been defined.", "// Inject script tag into the head element", "head", ".", "appendChild", "(", "script", ")", ";", "// Append Opera Fix to run after our script", "if", "(", "operaFix", ")", "{", "head", ".", "appendChild", "(", "operaFix", ")", ";", "}", "}" ]
JSONP Injects a script tag into the DOM to be executed and appends a callback function to the window object @param string/function pathFunc either a string of the URL or a callback function pathFunc(querystringhash, continueFunc); @param function callback a function to call on completion;
[ "JSONP", "Injects", "a", "script", "tag", "into", "the", "DOM", "to", "be", "executed", "and", "appends", "a", "callback", "function", "to", "the", "window", "object" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2356-L2433
11,361
MrSwitch/hello.js
dist/hello.all.js
function(data) { for (var x in data) if (data.hasOwnProperty(x)) { if (this.isBinary(data[x])) { return true; } } return false; }
javascript
function(data) { for (var x in data) if (data.hasOwnProperty(x)) { if (this.isBinary(data[x])) { return true; } } return false; }
[ "function", "(", "data", ")", "{", "for", "(", "var", "x", "in", "data", ")", "if", "(", "data", ".", "hasOwnProperty", "(", "x", ")", ")", "{", "if", "(", "this", ".", "isBinary", "(", "data", "[", "x", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Some of the providers require that only multipart is used with non-binary forms. This function checks whether the form contains binary data
[ "Some", "of", "the", "providers", "require", "that", "only", "multipart", "is", "used", "with", "non", "-", "binary", "forms", ".", "This", "function", "checks", "whether", "the", "form", "contains", "binary", "data" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2654-L2662
11,362
MrSwitch/hello.js
dist/hello.all.js
function(data) { return data instanceof Object && ( (this.domInstance('input', data) && data.type === 'file') || ('FileList' in window && data instanceof window.FileList) || ('File' in window && data instanceof window.File) || ('Blob' in window && data instanceof window.Blob)); }
javascript
function(data) { return data instanceof Object && ( (this.domInstance('input', data) && data.type === 'file') || ('FileList' in window && data instanceof window.FileList) || ('File' in window && data instanceof window.File) || ('Blob' in window && data instanceof window.Blob)); }
[ "function", "(", "data", ")", "{", "return", "data", "instanceof", "Object", "&&", "(", "(", "this", ".", "domInstance", "(", "'input'", ",", "data", ")", "&&", "data", ".", "type", "===", "'file'", ")", "||", "(", "'FileList'", "in", "window", "&&", "data", "instanceof", "window", ".", "FileList", ")", "||", "(", "'File'", "in", "window", "&&", "data", "instanceof", "window", ".", "File", ")", "||", "(", "'Blob'", "in", "window", "&&", "data", "instanceof", "window", ".", "Blob", ")", ")", ";", "}" ]
Determines if a variable Either Is or like a FormInput has the value of a Blob
[ "Determines", "if", "a", "variable", "Either", "Is", "or", "like", "a", "FormInput", "has", "the", "value", "of", "a", "Blob" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2666-L2674
11,363
MrSwitch/hello.js
dist/hello.all.js
function(p) { var _this = this; var w = window; var data = p.data; // Is data a form object if (_this.domInstance('form', data)) { data = _this.nodeListToJSON(data.elements); } else if ('NodeList' in w && data instanceof NodeList) { data = _this.nodeListToJSON(data); } else if (_this.domInstance('input', data)) { data = _this.nodeListToJSON([data]); } // Is data a blob, File, FileList? if (('File' in w && data instanceof w.File) || ('Blob' in w && data instanceof w.Blob) || ('FileList' in w && data instanceof w.FileList)) { data = {file: data}; } // Loop through data if it's not form data it must now be a JSON object if (!('FormData' in w && data instanceof w.FormData)) { for (var x in data) if (data.hasOwnProperty(x)) { if ('FileList' in w && data[x] instanceof w.FileList) { if (data[x].length === 1) { data[x] = data[x][0]; } } else if (_this.domInstance('input', data[x]) && data[x].type === 'file') { continue; } else if (_this.domInstance('input', data[x]) || _this.domInstance('select', data[x]) || _this.domInstance('textArea', data[x])) { data[x] = data[x].value; } else if (_this.domInstance(null, data[x])) { data[x] = data[x].innerHTML || data[x].innerText; } } } p.data = data; return data; }
javascript
function(p) { var _this = this; var w = window; var data = p.data; // Is data a form object if (_this.domInstance('form', data)) { data = _this.nodeListToJSON(data.elements); } else if ('NodeList' in w && data instanceof NodeList) { data = _this.nodeListToJSON(data); } else if (_this.domInstance('input', data)) { data = _this.nodeListToJSON([data]); } // Is data a blob, File, FileList? if (('File' in w && data instanceof w.File) || ('Blob' in w && data instanceof w.Blob) || ('FileList' in w && data instanceof w.FileList)) { data = {file: data}; } // Loop through data if it's not form data it must now be a JSON object if (!('FormData' in w && data instanceof w.FormData)) { for (var x in data) if (data.hasOwnProperty(x)) { if ('FileList' in w && data[x] instanceof w.FileList) { if (data[x].length === 1) { data[x] = data[x][0]; } } else if (_this.domInstance('input', data[x]) && data[x].type === 'file') { continue; } else if (_this.domInstance('input', data[x]) || _this.domInstance('select', data[x]) || _this.domInstance('textArea', data[x])) { data[x] = data[x].value; } else if (_this.domInstance(null, data[x])) { data[x] = data[x].innerHTML || data[x].innerText; } } } p.data = data; return data; }
[ "function", "(", "p", ")", "{", "var", "_this", "=", "this", ";", "var", "w", "=", "window", ";", "var", "data", "=", "p", ".", "data", ";", "// Is data a form object", "if", "(", "_this", ".", "domInstance", "(", "'form'", ",", "data", ")", ")", "{", "data", "=", "_this", ".", "nodeListToJSON", "(", "data", ".", "elements", ")", ";", "}", "else", "if", "(", "'NodeList'", "in", "w", "&&", "data", "instanceof", "NodeList", ")", "{", "data", "=", "_this", ".", "nodeListToJSON", "(", "data", ")", ";", "}", "else", "if", "(", "_this", ".", "domInstance", "(", "'input'", ",", "data", ")", ")", "{", "data", "=", "_this", ".", "nodeListToJSON", "(", "[", "data", "]", ")", ";", "}", "// Is data a blob, File, FileList?", "if", "(", "(", "'File'", "in", "w", "&&", "data", "instanceof", "w", ".", "File", ")", "||", "(", "'Blob'", "in", "w", "&&", "data", "instanceof", "w", ".", "Blob", ")", "||", "(", "'FileList'", "in", "w", "&&", "data", "instanceof", "w", ".", "FileList", ")", ")", "{", "data", "=", "{", "file", ":", "data", "}", ";", "}", "// Loop through data if it's not form data it must now be a JSON object", "if", "(", "!", "(", "'FormData'", "in", "w", "&&", "data", "instanceof", "w", ".", "FormData", ")", ")", "{", "for", "(", "var", "x", "in", "data", ")", "if", "(", "data", ".", "hasOwnProperty", "(", "x", ")", ")", "{", "if", "(", "'FileList'", "in", "w", "&&", "data", "[", "x", "]", "instanceof", "w", ".", "FileList", ")", "{", "if", "(", "data", "[", "x", "]", ".", "length", "===", "1", ")", "{", "data", "[", "x", "]", "=", "data", "[", "x", "]", "[", "0", "]", ";", "}", "}", "else", "if", "(", "_this", ".", "domInstance", "(", "'input'", ",", "data", "[", "x", "]", ")", "&&", "data", "[", "x", "]", ".", "type", "===", "'file'", ")", "{", "continue", ";", "}", "else", "if", "(", "_this", ".", "domInstance", "(", "'input'", ",", "data", "[", "x", "]", ")", "||", "_this", ".", "domInstance", "(", "'select'", ",", "data", "[", "x", "]", ")", "||", "_this", ".", "domInstance", "(", "'textArea'", ",", "data", "[", "x", "]", ")", ")", "{", "data", "[", "x", "]", "=", "data", "[", "x", "]", ".", "value", ";", "}", "else", "if", "(", "_this", ".", "domInstance", "(", "null", ",", "data", "[", "x", "]", ")", ")", "{", "data", "[", "x", "]", "=", "data", "[", "x", "]", ".", "innerHTML", "||", "data", "[", "x", "]", ".", "innerText", ";", "}", "}", "}", "p", ".", "data", "=", "data", ";", "return", "data", ";", "}" ]
DataToJSON This takes a FormElement|NodeList|InputElement|MixedObjects and convers the data object to JSON.
[ "DataToJSON", "This", "takes", "a", "FormElement|NodeList|InputElement|MixedObjects", "and", "convers", "the", "data", "object", "to", "JSON", "." ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2707-L2757
11,364
MrSwitch/hello.js
dist/hello.all.js
function(nodelist) { var json = {}; // Create a data string for (var i = 0; i < nodelist.length; i++) { var input = nodelist[i]; // If the name of the input is empty or diabled, dont add it. if (input.disabled || !input.name) { continue; } // Is this a file, does the browser not support 'files' and 'FormData'? if (input.type === 'file') { json[input.name] = input; } else { json[input.name] = input.value || input.innerHTML; } } return json; }
javascript
function(nodelist) { var json = {}; // Create a data string for (var i = 0; i < nodelist.length; i++) { var input = nodelist[i]; // If the name of the input is empty or diabled, dont add it. if (input.disabled || !input.name) { continue; } // Is this a file, does the browser not support 'files' and 'FormData'? if (input.type === 'file') { json[input.name] = input; } else { json[input.name] = input.value || input.innerHTML; } } return json; }
[ "function", "(", "nodelist", ")", "{", "var", "json", "=", "{", "}", ";", "// Create a data string", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodelist", ".", "length", ";", "i", "++", ")", "{", "var", "input", "=", "nodelist", "[", "i", "]", ";", "// If the name of the input is empty or diabled, dont add it.", "if", "(", "input", ".", "disabled", "||", "!", "input", ".", "name", ")", "{", "continue", ";", "}", "// Is this a file, does the browser not support 'files' and 'FormData'?", "if", "(", "input", ".", "type", "===", "'file'", ")", "{", "json", "[", "input", ".", "name", "]", "=", "input", ";", "}", "else", "{", "json", "[", "input", ".", "name", "]", "=", "input", ".", "value", "||", "input", ".", "innerHTML", ";", "}", "}", "return", "json", ";", "}" ]
NodeListToJSON Given a list of elements extrapolate their values and return as a json object
[ "NodeListToJSON", "Given", "a", "list", "of", "elements", "extrapolate", "their", "values", "and", "return", "as", "a", "json", "object" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L2761-L2785
11,365
MrSwitch/hello.js
dist/hello.all.js
function(p) { // The proxy supports allow-cross-origin-resource // Alas that's the only thing we're using. if (p.data && p.data.file) { var file = p.data.file; if (file) { if (file.files) { p.data = file.files[0]; } else { p.data = file; } } } if (p.method === 'delete') { p.method = 'post'; } return true; }
javascript
function(p) { // The proxy supports allow-cross-origin-resource // Alas that's the only thing we're using. if (p.data && p.data.file) { var file = p.data.file; if (file) { if (file.files) { p.data = file.files[0]; } else { p.data = file; } } } if (p.method === 'delete') { p.method = 'post'; } return true; }
[ "function", "(", "p", ")", "{", "// The proxy supports allow-cross-origin-resource", "// Alas that's the only thing we're using.", "if", "(", "p", ".", "data", "&&", "p", ".", "data", ".", "file", ")", "{", "var", "file", "=", "p", ".", "data", ".", "file", ";", "if", "(", "file", ")", "{", "if", "(", "file", ".", "files", ")", "{", "p", ".", "data", "=", "file", ".", "files", "[", "0", "]", ";", "}", "else", "{", "p", ".", "data", "=", "file", ";", "}", "}", "}", "if", "(", "p", ".", "method", "===", "'delete'", ")", "{", "p", ".", "method", "=", "'post'", ";", "}", "return", "true", ";", "}" ]
Doesn't return the CORS headers
[ "Doesn", "t", "return", "the", "CORS", "headers" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L3201-L3222
11,366
MrSwitch/hello.js
dist/hello.all.js
function(p, qs) { if (p.method === 'get' || p.method === 'post') { qs.suppress_response_codes = true; } // Is this a post with a data-uri? if (p.method === 'post' && p.data && typeof (p.data.file) === 'string') { // Convert the Data-URI to a Blob p.data.file = hello.utils.toBlob(p.data.file); } return true; }
javascript
function(p, qs) { if (p.method === 'get' || p.method === 'post') { qs.suppress_response_codes = true; } // Is this a post with a data-uri? if (p.method === 'post' && p.data && typeof (p.data.file) === 'string') { // Convert the Data-URI to a Blob p.data.file = hello.utils.toBlob(p.data.file); } return true; }
[ "function", "(", "p", ",", "qs", ")", "{", "if", "(", "p", ".", "method", "===", "'get'", "||", "p", ".", "method", "===", "'post'", ")", "{", "qs", ".", "suppress_response_codes", "=", "true", ";", "}", "// Is this a post with a data-uri?", "if", "(", "p", ".", "method", "===", "'post'", "&&", "p", ".", "data", "&&", "typeof", "(", "p", ".", "data", ".", "file", ")", "===", "'string'", ")", "{", "// Convert the Data-URI to a Blob", "p", ".", "data", ".", "file", "=", "hello", ".", "utils", ".", "toBlob", "(", "p", ".", "data", ".", "file", ")", ";", "}", "return", "true", ";", "}" ]
Special requirements for handling XHR
[ "Special", "requirements", "for", "handling", "XHR" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L3401-L3413
11,367
MrSwitch/hello.js
dist/hello.all.js
function(p, qs) { var m = p.method; if (m !== 'get' && !hello.utils.hasBinary(p.data)) { p.data.method = m; p.method = 'get'; } else if (p.method === 'delete') { qs.method = 'delete'; p.method = 'post'; } }
javascript
function(p, qs) { var m = p.method; if (m !== 'get' && !hello.utils.hasBinary(p.data)) { p.data.method = m; p.method = 'get'; } else if (p.method === 'delete') { qs.method = 'delete'; p.method = 'post'; } }
[ "function", "(", "p", ",", "qs", ")", "{", "var", "m", "=", "p", ".", "method", ";", "if", "(", "m", "!==", "'get'", "&&", "!", "hello", ".", "utils", ".", "hasBinary", "(", "p", ".", "data", ")", ")", "{", "p", ".", "data", ".", "method", "=", "m", ";", "p", ".", "method", "=", "'get'", ";", "}", "else", "if", "(", "p", ".", "method", "===", "'delete'", ")", "{", "qs", ".", "method", "=", "'delete'", ";", "p", ".", "method", "=", "'post'", ";", "}", "}" ]
Special requirements for handling JSONP fallback
[ "Special", "requirements", "for", "handling", "JSONP", "fallback" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L3416-L3426
11,368
MrSwitch/hello.js
dist/hello.all.js
withUser
function withUser(cb) { var auth = hello.getAuthResponse('flickr'); cb(auth && auth.user_nsid ? auth.user_nsid : null); }
javascript
function withUser(cb) { var auth = hello.getAuthResponse('flickr'); cb(auth && auth.user_nsid ? auth.user_nsid : null); }
[ "function", "withUser", "(", "cb", ")", "{", "var", "auth", "=", "hello", ".", "getAuthResponse", "(", "'flickr'", ")", ";", "cb", "(", "auth", "&&", "auth", ".", "user_nsid", "?", "auth", ".", "user_nsid", ":", "null", ")", ";", "}" ]
This is not exactly neat but avoid to call The method 'flickr.test.login' for each api call
[ "This", "is", "not", "exactly", "neat", "but", "avoid", "to", "call", "The", "method", "flickr", ".", "test", ".", "login", "for", "each", "api", "call" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L3608-L3611
11,369
MrSwitch/hello.js
dist/hello.all.js
gEntry
function gEntry(o) { paging(o); if ('feed' in o && 'entry' in o.feed) { o.data = o.feed.entry.map(formatEntry); delete o.feed; } // Old style: Picasa, etc. else if ('entry' in o) { return formatEntry(o.entry); } // New style: Google Drive else if ('items' in o) { o.data = o.items.map(formatItem); delete o.items; } else { formatItem(o); } return o; }
javascript
function gEntry(o) { paging(o); if ('feed' in o && 'entry' in o.feed) { o.data = o.feed.entry.map(formatEntry); delete o.feed; } // Old style: Picasa, etc. else if ('entry' in o) { return formatEntry(o.entry); } // New style: Google Drive else if ('items' in o) { o.data = o.items.map(formatItem); delete o.items; } else { formatItem(o); } return o; }
[ "function", "gEntry", "(", "o", ")", "{", "paging", "(", "o", ")", ";", "if", "(", "'feed'", "in", "o", "&&", "'entry'", "in", "o", ".", "feed", ")", "{", "o", ".", "data", "=", "o", ".", "feed", ".", "entry", ".", "map", "(", "formatEntry", ")", ";", "delete", "o", ".", "feed", ";", "}", "// Old style: Picasa, etc.", "else", "if", "(", "'entry'", "in", "o", ")", "{", "return", "formatEntry", "(", "o", ".", "entry", ")", ";", "}", "// New style: Google Drive", "else", "if", "(", "'items'", "in", "o", ")", "{", "o", ".", "data", "=", "o", ".", "items", ".", "map", "(", "formatItem", ")", ";", "delete", "o", ".", "items", ";", "}", "else", "{", "formatItem", "(", "o", ")", ";", "}", "return", "o", ";", "}" ]
Google has a horrible JSON API
[ "Google", "has", "a", "horrible", "JSON", "API" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L4173-L4196
11,370
MrSwitch/hello.js
dist/hello.all.js
Multipart
function Multipart() { // Internal body var body = []; var boundary = (Math.random() * 1e10).toString(32); var counter = 0; var lineBreak = '\r\n'; var delim = lineBreak + '--' + boundary; var ready = function() {}; var dataUri = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i; // Add file function addFile(item) { var fr = new FileReader(); fr.onload = function(e) { addContent(btoa(e.target.result), item.type + lineBreak + 'Content-Transfer-Encoding: base64'); }; fr.readAsBinaryString(item); } // Add content function addContent(content, type) { body.push(lineBreak + 'Content-Type: ' + type + lineBreak + lineBreak + content); counter--; ready(); } // Add new things to the object this.append = function(content, type) { // Does the content have an array if (typeof (content) === 'string' || !('length' in Object(content))) { // Converti to multiples content = [content]; } for (var i = 0; i < content.length; i++) { counter++; var item = content[i]; // Is this a file? // Files can be either Blobs or File types if ( (typeof (File) !== 'undefined' && item instanceof File) || (typeof (Blob) !== 'undefined' && item instanceof Blob) ) { // Read the file in addFile(item); } // Data-URI? // Data:[<mime type>][;charset=<charset>][;base64],<encoded data> // /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i else if (typeof (item) === 'string' && item.match(dataUri)) { var m = item.match(dataUri); addContent(item.replace(dataUri, ''), m[1] + lineBreak + 'Content-Transfer-Encoding: base64'); } // Regular string else { addContent(item, type); } } }; this.onready = function(fn) { ready = function() { if (counter === 0) { // Trigger ready body.unshift(''); body.push('--'); fn(body.join(delim), boundary); body = []; } }; ready(); }; }
javascript
function Multipart() { // Internal body var body = []; var boundary = (Math.random() * 1e10).toString(32); var counter = 0; var lineBreak = '\r\n'; var delim = lineBreak + '--' + boundary; var ready = function() {}; var dataUri = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i; // Add file function addFile(item) { var fr = new FileReader(); fr.onload = function(e) { addContent(btoa(e.target.result), item.type + lineBreak + 'Content-Transfer-Encoding: base64'); }; fr.readAsBinaryString(item); } // Add content function addContent(content, type) { body.push(lineBreak + 'Content-Type: ' + type + lineBreak + lineBreak + content); counter--; ready(); } // Add new things to the object this.append = function(content, type) { // Does the content have an array if (typeof (content) === 'string' || !('length' in Object(content))) { // Converti to multiples content = [content]; } for (var i = 0; i < content.length; i++) { counter++; var item = content[i]; // Is this a file? // Files can be either Blobs or File types if ( (typeof (File) !== 'undefined' && item instanceof File) || (typeof (Blob) !== 'undefined' && item instanceof Blob) ) { // Read the file in addFile(item); } // Data-URI? // Data:[<mime type>][;charset=<charset>][;base64],<encoded data> // /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i else if (typeof (item) === 'string' && item.match(dataUri)) { var m = item.match(dataUri); addContent(item.replace(dataUri, ''), m[1] + lineBreak + 'Content-Transfer-Encoding: base64'); } // Regular string else { addContent(item, type); } } }; this.onready = function(fn) { ready = function() { if (counter === 0) { // Trigger ready body.unshift(''); body.push('--'); fn(body.join(delim), boundary); body = []; } }; ready(); }; }
[ "function", "Multipart", "(", ")", "{", "// Internal body", "var", "body", "=", "[", "]", ";", "var", "boundary", "=", "(", "Math", ".", "random", "(", ")", "*", "1e10", ")", ".", "toString", "(", "32", ")", ";", "var", "counter", "=", "0", ";", "var", "lineBreak", "=", "'\\r\\n'", ";", "var", "delim", "=", "lineBreak", "+", "'--'", "+", "boundary", ";", "var", "ready", "=", "function", "(", ")", "{", "}", ";", "var", "dataUri", "=", "/", "^data\\:([^;,]+(\\;charset=[^;,]+)?)(\\;base64)?,", "/", "i", ";", "// Add file", "function", "addFile", "(", "item", ")", "{", "var", "fr", "=", "new", "FileReader", "(", ")", ";", "fr", ".", "onload", "=", "function", "(", "e", ")", "{", "addContent", "(", "btoa", "(", "e", ".", "target", ".", "result", ")", ",", "item", ".", "type", "+", "lineBreak", "+", "'Content-Transfer-Encoding: base64'", ")", ";", "}", ";", "fr", ".", "readAsBinaryString", "(", "item", ")", ";", "}", "// Add content", "function", "addContent", "(", "content", ",", "type", ")", "{", "body", ".", "push", "(", "lineBreak", "+", "'Content-Type: '", "+", "type", "+", "lineBreak", "+", "lineBreak", "+", "content", ")", ";", "counter", "--", ";", "ready", "(", ")", ";", "}", "// Add new things to the object", "this", ".", "append", "=", "function", "(", "content", ",", "type", ")", "{", "// Does the content have an array", "if", "(", "typeof", "(", "content", ")", "===", "'string'", "||", "!", "(", "'length'", "in", "Object", "(", "content", ")", ")", ")", "{", "// Converti to multiples", "content", "=", "[", "content", "]", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "content", ".", "length", ";", "i", "++", ")", "{", "counter", "++", ";", "var", "item", "=", "content", "[", "i", "]", ";", "// Is this a file?", "// Files can be either Blobs or File types", "if", "(", "(", "typeof", "(", "File", ")", "!==", "'undefined'", "&&", "item", "instanceof", "File", ")", "||", "(", "typeof", "(", "Blob", ")", "!==", "'undefined'", "&&", "item", "instanceof", "Blob", ")", ")", "{", "// Read the file in", "addFile", "(", "item", ")", ";", "}", "// Data-URI?", "// Data:[<mime type>][;charset=<charset>][;base64],<encoded data>", "// /^data\\:([^;,]+(\\;charset=[^;,]+)?)(\\;base64)?,/i", "else", "if", "(", "typeof", "(", "item", ")", "===", "'string'", "&&", "item", ".", "match", "(", "dataUri", ")", ")", "{", "var", "m", "=", "item", ".", "match", "(", "dataUri", ")", ";", "addContent", "(", "item", ".", "replace", "(", "dataUri", ",", "''", ")", ",", "m", "[", "1", "]", "+", "lineBreak", "+", "'Content-Transfer-Encoding: base64'", ")", ";", "}", "// Regular string", "else", "{", "addContent", "(", "item", ",", "type", ")", ";", "}", "}", "}", ";", "this", ".", "onready", "=", "function", "(", "fn", ")", "{", "ready", "=", "function", "(", ")", "{", "if", "(", "counter", "===", "0", ")", "{", "// Trigger ready", "body", ".", "unshift", "(", "''", ")", ";", "body", ".", "push", "(", "'--'", ")", ";", "fn", "(", "body", ".", "join", "(", "delim", ")", ",", "boundary", ")", ";", "body", "=", "[", "]", ";", "}", "}", ";", "ready", "(", ")", ";", "}", ";", "}" ]
Construct a multipart message
[ "Construct", "a", "multipart", "message" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L4338-L4420
11,371
MrSwitch/hello.js
dist/hello.all.js
function(p, qs) { var method = p.method; var proxy = method !== 'get'; if (proxy) { if ((method === 'post' || method === 'put') && p.query.access_token) { p.data.access_token = p.query.access_token; delete p.query.access_token; } // No access control headers // Use the proxy instead p.proxy = proxy; } return proxy; }
javascript
function(p, qs) { var method = p.method; var proxy = method !== 'get'; if (proxy) { if ((method === 'post' || method === 'put') && p.query.access_token) { p.data.access_token = p.query.access_token; delete p.query.access_token; } // No access control headers // Use the proxy instead p.proxy = proxy; } return proxy; }
[ "function", "(", "p", ",", "qs", ")", "{", "var", "method", "=", "p", ".", "method", ";", "var", "proxy", "=", "method", "!==", "'get'", ";", "if", "(", "proxy", ")", "{", "if", "(", "(", "method", "===", "'post'", "||", "method", "===", "'put'", ")", "&&", "p", ".", "query", ".", "access_token", ")", "{", "p", ".", "data", ".", "access_token", "=", "p", ".", "query", ".", "access_token", ";", "delete", "p", ".", "query", ".", "access_token", ";", "}", "// No access control headers", "// Use the proxy instead", "p", ".", "proxy", "=", "proxy", ";", "}", "return", "proxy", ";", "}" ]
Instagram does not return any CORS Headers So besides JSONP we're stuck with proxy
[ "Instagram", "does", "not", "return", "any", "CORS", "Headers", "So", "besides", "JSONP", "we", "re", "stuck", "with", "proxy" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L4638-L4656
11,372
MrSwitch/hello.js
dist/hello.all.js
formatRequest
function formatRequest(p, qs) { var token = qs.access_token; delete qs.access_token; p.headers.Authorization = 'Bearer ' + token; return true; }
javascript
function formatRequest(p, qs) { var token = qs.access_token; delete qs.access_token; p.headers.Authorization = 'Bearer ' + token; return true; }
[ "function", "formatRequest", "(", "p", ",", "qs", ")", "{", "var", "token", "=", "qs", ".", "access_token", ";", "delete", "qs", ".", "access_token", ";", "p", ".", "headers", ".", "Authorization", "=", "'Bearer '", "+", "token", ";", "return", "true", ";", "}" ]
Move the access token from the request body to the request header
[ "Move", "the", "access", "token", "from", "the", "request", "body", "to", "the", "request", "header" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/dist/hello.all.js#L5228-L5234
11,373
MrSwitch/hello.js
demos/Collage/fabric.js
getSizeInPixels
function getSizeInPixels(el, value) { if (/px$/i.test(value)) return parseFloat(value); var style = el.style.left, runtimeStyle = el.runtimeStyle.left; el.runtimeStyle.left = el.currentStyle.left; el.style.left = value; var result = el.style.pixelLeft; el.style.left = style; el.runtimeStyle.left = runtimeStyle; return result; }
javascript
function getSizeInPixels(el, value) { if (/px$/i.test(value)) return parseFloat(value); var style = el.style.left, runtimeStyle = el.runtimeStyle.left; el.runtimeStyle.left = el.currentStyle.left; el.style.left = value; var result = el.style.pixelLeft; el.style.left = style; el.runtimeStyle.left = runtimeStyle; return result; }
[ "function", "getSizeInPixels", "(", "el", ",", "value", ")", "{", "if", "(", "/", "px$", "/", "i", ".", "test", "(", "value", ")", ")", "return", "parseFloat", "(", "value", ")", ";", "var", "style", "=", "el", ".", "style", ".", "left", ",", "runtimeStyle", "=", "el", ".", "runtimeStyle", ".", "left", ";", "el", ".", "runtimeStyle", ".", "left", "=", "el", ".", "currentStyle", ".", "left", ";", "el", ".", "style", ".", "left", "=", "value", ";", "var", "result", "=", "el", ".", "style", ".", "pixelLeft", ";", "el", ".", "style", ".", "left", "=", "style", ";", "el", ".", "runtimeStyle", ".", "left", "=", "runtimeStyle", ";", "return", "result", ";", "}" ]
Original by Dead Edwards. Combined with getFontSizeInPixels it also works with relative units.
[ "Original", "by", "Dead", "Edwards", ".", "Combined", "with", "getFontSizeInPixels", "it", "also", "works", "with", "relative", "units", "." ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L1062-L1071
11,374
MrSwitch/hello.js
demos/Collage/fabric.js
function(eventName, handler) { if (!this.__eventListeners) { this.__eventListeners = { }; } // one object with key/value pairs was passed if (arguments.length === 1) { for (var prop in eventName) { this.on(prop, eventName[prop]); } } else { if (!this.__eventListeners[eventName]) { this.__eventListeners[eventName] = [ ]; } this.__eventListeners[eventName].push(handler); } }
javascript
function(eventName, handler) { if (!this.__eventListeners) { this.__eventListeners = { }; } // one object with key/value pairs was passed if (arguments.length === 1) { for (var prop in eventName) { this.on(prop, eventName[prop]); } } else { if (!this.__eventListeners[eventName]) { this.__eventListeners[eventName] = [ ]; } this.__eventListeners[eventName].push(handler); } }
[ "function", "(", "eventName", ",", "handler", ")", "{", "if", "(", "!", "this", ".", "__eventListeners", ")", "{", "this", ".", "__eventListeners", "=", "{", "}", ";", "}", "// one object with key/value pairs was passed", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "for", "(", "var", "prop", "in", "eventName", ")", "{", "this", ".", "on", "(", "prop", ",", "eventName", "[", "prop", "]", ")", ";", "}", "}", "else", "{", "if", "(", "!", "this", ".", "__eventListeners", "[", "eventName", "]", ")", "{", "this", ".", "__eventListeners", "[", "eventName", "]", "=", "[", "]", ";", "}", "this", ".", "__eventListeners", "[", "eventName", "]", ".", "push", "(", "handler", ")", ";", "}", "}" ]
Observes specified event @method observe @depracated Since 0.8.34. Use `on` instead. @param {String} eventName @param {Function} handler
[ "Observes", "specified", "event" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L1757-L1773
11,375
MrSwitch/hello.js
demos/Collage/fabric.js
function(eventName, handler) { if (!this.__eventListeners) { this.__eventListeners = { }; } if (this.__eventListeners[eventName]) { fabric.util.removeFromArray(this.__eventListeners[eventName], handler); } }
javascript
function(eventName, handler) { if (!this.__eventListeners) { this.__eventListeners = { }; } if (this.__eventListeners[eventName]) { fabric.util.removeFromArray(this.__eventListeners[eventName], handler); } }
[ "function", "(", "eventName", ",", "handler", ")", "{", "if", "(", "!", "this", ".", "__eventListeners", ")", "{", "this", ".", "__eventListeners", "=", "{", "}", ";", "}", "if", "(", "this", ".", "__eventListeners", "[", "eventName", "]", ")", "{", "fabric", ".", "util", ".", "removeFromArray", "(", "this", ".", "__eventListeners", "[", "eventName", "]", ",", "handler", ")", ";", "}", "}" ]
Stops event observing for a particular event handler @method stopObserving @depracated Since 0.8.34. Use `off` instead. @param {String} eventName @param {Function} handler
[ "Stops", "event", "observing", "for", "a", "particular", "event", "handler" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L1782-L1789
11,376
MrSwitch/hello.js
demos/Collage/fabric.js
function(eventName, options) { if (!this.__eventListeners) { this.__eventListeners = { } } var listenersForEvent = this.__eventListeners[eventName]; if (!listenersForEvent) return; for (var i = 0, len = listenersForEvent.length; i < len; i++) { // avoiding try/catch for perf. reasons listenersForEvent[i](options || { }); } }
javascript
function(eventName, options) { if (!this.__eventListeners) { this.__eventListeners = { } } var listenersForEvent = this.__eventListeners[eventName]; if (!listenersForEvent) return; for (var i = 0, len = listenersForEvent.length; i < len; i++) { // avoiding try/catch for perf. reasons listenersForEvent[i](options || { }); } }
[ "function", "(", "eventName", ",", "options", ")", "{", "if", "(", "!", "this", ".", "__eventListeners", ")", "{", "this", ".", "__eventListeners", "=", "{", "}", "}", "var", "listenersForEvent", "=", "this", ".", "__eventListeners", "[", "eventName", "]", ";", "if", "(", "!", "listenersForEvent", ")", "return", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "listenersForEvent", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "// avoiding try/catch for perf. reasons", "listenersForEvent", "[", "i", "]", "(", "options", "||", "{", "}", ")", ";", "}", "}" ]
Fires event with an optional options object @method fire @param {String} eventName @param {Object} [options]
[ "Fires", "event", "with", "an", "optional", "options", "object" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L1797-L1807
11,377
MrSwitch/hello.js
demos/Collage/fabric.js
animate
function animate(options) { options || (options = { }); var start = +new Date(), duration = options.duration || 500, finish = start + duration, time, pos, onChange = options.onChange || function() { }, abort = options.abort || function() { return false; }, easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t/d * (Math.PI/2)) + c + b;}, startValue = 'startValue' in options ? options.startValue : 0, endValue = 'endValue' in options ? options.endValue : 100; byValue = options.byValue || endValue - startValue; options.onStart && options.onStart(); (function tick() { time = +new Date(); currentTime = time > finish ? duration : (time - start); onChange(easing(currentTime, startValue, byValue, duration)); if (time > finish || abort()) { options.onComplete && options.onComplete(); return; } requestAnimFrame(tick); })(); }
javascript
function animate(options) { options || (options = { }); var start = +new Date(), duration = options.duration || 500, finish = start + duration, time, pos, onChange = options.onChange || function() { }, abort = options.abort || function() { return false; }, easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t/d * (Math.PI/2)) + c + b;}, startValue = 'startValue' in options ? options.startValue : 0, endValue = 'endValue' in options ? options.endValue : 100; byValue = options.byValue || endValue - startValue; options.onStart && options.onStart(); (function tick() { time = +new Date(); currentTime = time > finish ? duration : (time - start); onChange(easing(currentTime, startValue, byValue, duration)); if (time > finish || abort()) { options.onComplete && options.onComplete(); return; } requestAnimFrame(tick); })(); }
[ "function", "animate", "(", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "var", "start", "=", "+", "new", "Date", "(", ")", ",", "duration", "=", "options", ".", "duration", "||", "500", ",", "finish", "=", "start", "+", "duration", ",", "time", ",", "pos", ",", "onChange", "=", "options", ".", "onChange", "||", "function", "(", ")", "{", "}", ",", "abort", "=", "options", ".", "abort", "||", "function", "(", ")", "{", "return", "false", ";", "}", ",", "easing", "=", "options", ".", "easing", "||", "function", "(", "t", ",", "b", ",", "c", ",", "d", ")", "{", "return", "-", "c", "*", "Math", ".", "cos", "(", "t", "/", "d", "*", "(", "Math", ".", "PI", "/", "2", ")", ")", "+", "c", "+", "b", ";", "}", ",", "startValue", "=", "'startValue'", "in", "options", "?", "options", ".", "startValue", ":", "0", ",", "endValue", "=", "'endValue'", "in", "options", "?", "options", ".", "endValue", ":", "100", ";", "byValue", "=", "options", ".", "byValue", "||", "endValue", "-", "startValue", ";", "options", ".", "onStart", "&&", "options", ".", "onStart", "(", ")", ";", "(", "function", "tick", "(", ")", "{", "time", "=", "+", "new", "Date", "(", ")", ";", "currentTime", "=", "time", ">", "finish", "?", "duration", ":", "(", "time", "-", "start", ")", ";", "onChange", "(", "easing", "(", "currentTime", ",", "startValue", ",", "byValue", ",", "duration", ")", ")", ";", "if", "(", "time", ">", "finish", "||", "abort", "(", ")", ")", "{", "options", ".", "onComplete", "&&", "options", ".", "onComplete", "(", ")", ";", "return", ";", "}", "requestAnimFrame", "(", "tick", ")", ";", "}", ")", "(", ")", ";", "}" ]
Changes value from one to another within certain period of time, invoking callbacks as value is being changed. @method animate @memberOf fabric.util @param {Object} [options] Animation options @param {Function} [options.onChange] Callback; invoked on every value change @param {Function} [options.onComplete] Callback; invoked when value change is completed @param {Number} [options.startValue=0] Starting value @param {Number} [options.endValue=100] Ending value @param {Number} [options.byValue=100] Value to modify the property by @param {Function} [options.easing] Easing function @param {Number} [options.duration=500] Duration of change
[ "Changes", "value", "from", "one", "to", "another", "within", "certain", "period", "of", "time", "invoking", "callbacks", "as", "value", "is", "being", "changed", "." ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L1911-L1937
11,378
MrSwitch/hello.js
demos/Collage/fabric.js
loadImage
function loadImage(url, callback, context) { if (url) { var img = new Image(); /** @ignore */ img.onload = function () { callback && callback.call(context, img); img = img.onload = null; }; img.src = url; } else { callback && callback.call(context, url); } }
javascript
function loadImage(url, callback, context) { if (url) { var img = new Image(); /** @ignore */ img.onload = function () { callback && callback.call(context, img); img = img.onload = null; }; img.src = url; } else { callback && callback.call(context, url); } }
[ "function", "loadImage", "(", "url", ",", "callback", ",", "context", ")", "{", "if", "(", "url", ")", "{", "var", "img", "=", "new", "Image", "(", ")", ";", "/** @ignore */", "img", ".", "onload", "=", "function", "(", ")", "{", "callback", "&&", "callback", ".", "call", "(", "context", ",", "img", ")", ";", "img", "=", "img", ".", "onload", "=", "null", ";", "}", ";", "img", ".", "src", "=", "url", ";", "}", "else", "{", "callback", "&&", "callback", ".", "call", "(", "context", ",", "url", ")", ";", "}", "}" ]
Loads image element from given url and passes it to a callback @method loadImage @memberOf fabric.util @param {String} url URL representing an image @param {Function} callback Callback; invoked with loaded image @param {Any} context optional Context to invoke callback in
[ "Loads", "image", "element", "from", "given", "url", "and", "passes", "it", "to", "a", "callback" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L1966-L1979
11,379
MrSwitch/hello.js
demos/Collage/fabric.js
invoke
function invoke(array, method) { var args = slice.call(arguments, 2), result = [ ]; for (var i = 0, len = array.length; i < len; i++) { result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]); } return result; }
javascript
function invoke(array, method) { var args = slice.call(arguments, 2), result = [ ]; for (var i = 0, len = array.length; i < len; i++) { result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]); } return result; }
[ "function", "invoke", "(", "array", ",", "method", ")", "{", "var", "args", "=", "slice", ".", "call", "(", "arguments", ",", "2", ")", ",", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "array", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "args", ".", "length", "?", "array", "[", "i", "]", "[", "method", "]", ".", "apply", "(", "array", "[", "i", "]", ",", "args", ")", ":", "array", "[", "i", "]", "[", "method", "]", ".", "call", "(", "array", "[", "i", "]", ")", ";", "}", "return", "result", ";", "}" ]
Invokes method on all items in a given array @method invoke @memberOf fabric.util.array @param {Array} array Array to iterate over @param {String} method Name of a method to invoke
[ "Invokes", "method", "on", "all", "items", "in", "a", "given", "array" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2172-L2178
11,380
MrSwitch/hello.js
demos/Collage/fabric.js
camelize
function camelize(string) { return string.replace(/-+(.)?/g, function(match, character) { return character ? character.toUpperCase() : ''; }); }
javascript
function camelize(string) { return string.replace(/-+(.)?/g, function(match, character) { return character ? character.toUpperCase() : ''; }); }
[ "function", "camelize", "(", "string", ")", "{", "return", "string", ".", "replace", "(", "/", "-+(.)?", "/", "g", ",", "function", "(", "match", ",", "character", ")", "{", "return", "character", "?", "character", ".", "toUpperCase", "(", ")", ":", "''", ";", "}", ")", ";", "}" ]
Camelizes a string @memberOf fabric.util.string @method camelize @param {String} string String to camelize @return {String} Camelized version of a string
[ "Camelizes", "a", "string" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2302-L2306
11,381
MrSwitch/hello.js
demos/Collage/fabric.js
createClass
function createClass() { var parent = null, properties = slice.call(arguments, 0); if (typeof properties[0] === 'function') { parent = properties.shift(); } function klass() { this.initialize.apply(this, arguments); } klass.superclass = parent; klass.subclasses = [ ]; if (parent) { subclass.prototype = parent.prototype; klass.prototype = new subclass; parent.subclasses.push(klass); } for (var i = 0, length = properties.length; i < length; i++) { addMethods(klass, properties[i], parent); } if (!klass.prototype.initialize) { klass.prototype.initialize = emptyFunction; } klass.prototype.constructor = klass; return klass; }
javascript
function createClass() { var parent = null, properties = slice.call(arguments, 0); if (typeof properties[0] === 'function') { parent = properties.shift(); } function klass() { this.initialize.apply(this, arguments); } klass.superclass = parent; klass.subclasses = [ ]; if (parent) { subclass.prototype = parent.prototype; klass.prototype = new subclass; parent.subclasses.push(klass); } for (var i = 0, length = properties.length; i < length; i++) { addMethods(klass, properties[i], parent); } if (!klass.prototype.initialize) { klass.prototype.initialize = emptyFunction; } klass.prototype.constructor = klass; return klass; }
[ "function", "createClass", "(", ")", "{", "var", "parent", "=", "null", ",", "properties", "=", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "if", "(", "typeof", "properties", "[", "0", "]", "===", "'function'", ")", "{", "parent", "=", "properties", ".", "shift", "(", ")", ";", "}", "function", "klass", "(", ")", "{", "this", ".", "initialize", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "klass", ".", "superclass", "=", "parent", ";", "klass", ".", "subclasses", "=", "[", "]", ";", "if", "(", "parent", ")", "{", "subclass", ".", "prototype", "=", "parent", ".", "prototype", ";", "klass", ".", "prototype", "=", "new", "subclass", ";", "parent", ".", "subclasses", ".", "push", "(", "klass", ")", ";", "}", "for", "(", "var", "i", "=", "0", ",", "length", "=", "properties", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "addMethods", "(", "klass", ",", "properties", "[", "i", "]", ",", "parent", ")", ";", "}", "if", "(", "!", "klass", ".", "prototype", ".", "initialize", ")", "{", "klass", ".", "prototype", ".", "initialize", "=", "emptyFunction", ";", "}", "klass", ".", "prototype", ".", "constructor", "=", "klass", ";", "return", "klass", ";", "}" ]
Helper for creation of "classes" @method createClass @memberOf fabric.util
[ "Helper", "for", "creation", "of", "classes" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2422-L2449
11,382
MrSwitch/hello.js
demos/Collage/fabric.js
setStyle
function setStyle(element, styles) { var elementStyle = element.style, match; if (!elementStyle) { return element; } if (typeof styles === 'string') { element.style.cssText += ';' + styles; return styles.indexOf('opacity') > -1 ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; } for (var property in styles) { if (property === 'opacity') { setOpacity(element, styles[property]); } else { var normalizedProperty = (property === 'float' || property === 'cssFloat') ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat') : property; elementStyle[normalizedProperty] = styles[property]; } } return element; }
javascript
function setStyle(element, styles) { var elementStyle = element.style, match; if (!elementStyle) { return element; } if (typeof styles === 'string') { element.style.cssText += ';' + styles; return styles.indexOf('opacity') > -1 ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; } for (var property in styles) { if (property === 'opacity') { setOpacity(element, styles[property]); } else { var normalizedProperty = (property === 'float' || property === 'cssFloat') ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat') : property; elementStyle[normalizedProperty] = styles[property]; } } return element; }
[ "function", "setStyle", "(", "element", ",", "styles", ")", "{", "var", "elementStyle", "=", "element", ".", "style", ",", "match", ";", "if", "(", "!", "elementStyle", ")", "{", "return", "element", ";", "}", "if", "(", "typeof", "styles", "===", "'string'", ")", "{", "element", ".", "style", ".", "cssText", "+=", "';'", "+", "styles", ";", "return", "styles", ".", "indexOf", "(", "'opacity'", ")", ">", "-", "1", "?", "setOpacity", "(", "element", ",", "styles", ".", "match", "(", "/", "opacity:\\s*(\\d?\\.?\\d*)", "/", ")", "[", "1", "]", ")", ":", "element", ";", "}", "for", "(", "var", "property", "in", "styles", ")", "{", "if", "(", "property", "===", "'opacity'", ")", "{", "setOpacity", "(", "element", ",", "styles", "[", "property", "]", ")", ";", "}", "else", "{", "var", "normalizedProperty", "=", "(", "property", "===", "'float'", "||", "property", "===", "'cssFloat'", ")", "?", "(", "typeof", "elementStyle", ".", "styleFloat", "===", "'undefined'", "?", "'cssFloat'", ":", "'styleFloat'", ")", ":", "property", ";", "elementStyle", "[", "normalizedProperty", "]", "=", "styles", "[", "property", "]", ";", "}", "}", "return", "element", ";", "}" ]
Cross-browser wrapper for setting element's style @method setStyle @memberOf fabric.util @param {HTMLElement} element @param {Object} styles @return {HTMLElement} Element that was passed as a first argument
[ "Cross", "-", "browser", "wrapper", "for", "setting", "element", "s", "style" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2683-L2706
11,383
MrSwitch/hello.js
demos/Collage/fabric.js
makeElement
function makeElement(tagName, attributes) { var el = fabric.document.createElement(tagName); for (var prop in attributes) { if (prop === 'class') { el.className = attributes[prop]; } else if (prop === 'for') { el.htmlFor = attributes[prop]; } else { el.setAttribute(prop, attributes[prop]); } } return el; }
javascript
function makeElement(tagName, attributes) { var el = fabric.document.createElement(tagName); for (var prop in attributes) { if (prop === 'class') { el.className = attributes[prop]; } else if (prop === 'for') { el.htmlFor = attributes[prop]; } else { el.setAttribute(prop, attributes[prop]); } } return el; }
[ "function", "makeElement", "(", "tagName", ",", "attributes", ")", "{", "var", "el", "=", "fabric", ".", "document", ".", "createElement", "(", "tagName", ")", ";", "for", "(", "var", "prop", "in", "attributes", ")", "{", "if", "(", "prop", "===", "'class'", ")", "{", "el", ".", "className", "=", "attributes", "[", "prop", "]", ";", "}", "else", "if", "(", "prop", "===", "'for'", ")", "{", "el", ".", "htmlFor", "=", "attributes", "[", "prop", "]", ";", "}", "else", "{", "el", ".", "setAttribute", "(", "prop", ",", "attributes", "[", "prop", "]", ")", ";", "}", "}", "return", "el", ";", "}" ]
Creates specified element with specified attributes @method makeElement @memberOf fabric.util @param {String} tagName Type of an element to create @param {Object} [attributes] Attributes to set on an element @return {HTMLElement} Newly created element
[ "Creates", "specified", "element", "with", "specified", "attributes" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2795-L2809
11,384
MrSwitch/hello.js
demos/Collage/fabric.js
addClass
function addClass(element, className) { if ((' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) { element.className += (element.className ? ' ' : '') + className; } }
javascript
function addClass(element, className) { if ((' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) { element.className += (element.className ? ' ' : '') + className; } }
[ "function", "addClass", "(", "element", ",", "className", ")", "{", "if", "(", "(", "' '", "+", "element", ".", "className", "+", "' '", ")", ".", "indexOf", "(", "' '", "+", "className", "+", "' '", ")", "===", "-", "1", ")", "{", "element", ".", "className", "+=", "(", "element", ".", "className", "?", "' '", ":", "''", ")", "+", "className", ";", "}", "}" ]
Adds class to an element @method addClass @memberOf fabric.util @param {HTMLElement} element Element to add class to @param {String} className Class to add to an element
[ "Adds", "class", "to", "an", "element" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2818-L2822
11,385
MrSwitch/hello.js
demos/Collage/fabric.js
wrapElement
function wrapElement(element, wrapper, attributes) { if (typeof wrapper === 'string') { wrapper = makeElement(wrapper, attributes); } if (element.parentNode) { element.parentNode.replaceChild(wrapper, element); } wrapper.appendChild(element); return wrapper; }
javascript
function wrapElement(element, wrapper, attributes) { if (typeof wrapper === 'string') { wrapper = makeElement(wrapper, attributes); } if (element.parentNode) { element.parentNode.replaceChild(wrapper, element); } wrapper.appendChild(element); return wrapper; }
[ "function", "wrapElement", "(", "element", ",", "wrapper", ",", "attributes", ")", "{", "if", "(", "typeof", "wrapper", "===", "'string'", ")", "{", "wrapper", "=", "makeElement", "(", "wrapper", ",", "attributes", ")", ";", "}", "if", "(", "element", ".", "parentNode", ")", "{", "element", ".", "parentNode", ".", "replaceChild", "(", "wrapper", ",", "element", ")", ";", "}", "wrapper", ".", "appendChild", "(", "element", ")", ";", "return", "wrapper", ";", "}" ]
Wraps element with another element @method wrapElement @memberOf fabric.util @param {HTMLElement} element Element to wrap @param {HTMLElement|String} wrapper Element to wrap with @param {Object} [attributes] Attributes to set on a wrapper @return {HTMLElement} wrapper
[ "Wraps", "element", "with", "another", "element" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2833-L2842
11,386
MrSwitch/hello.js
demos/Collage/fabric.js
makeElementUnselectable
function makeElementUnselectable(element) { if (typeof element.onselectstart !== 'undefined') { element.onselectstart = fabric.util.falseFunction; } if (selectProp) { element.style[selectProp] = 'none'; } else if (typeof element.unselectable == 'string') { element.unselectable = 'on'; } return element; }
javascript
function makeElementUnselectable(element) { if (typeof element.onselectstart !== 'undefined') { element.onselectstart = fabric.util.falseFunction; } if (selectProp) { element.style[selectProp] = 'none'; } else if (typeof element.unselectable == 'string') { element.unselectable = 'on'; } return element; }
[ "function", "makeElementUnselectable", "(", "element", ")", "{", "if", "(", "typeof", "element", ".", "onselectstart", "!==", "'undefined'", ")", "{", "element", ".", "onselectstart", "=", "fabric", ".", "util", ".", "falseFunction", ";", "}", "if", "(", "selectProp", ")", "{", "element", ".", "style", "[", "selectProp", "]", "=", "'none'", ";", "}", "else", "if", "(", "typeof", "element", ".", "unselectable", "==", "'string'", ")", "{", "element", ".", "unselectable", "=", "'on'", ";", "}", "return", "element", ";", "}" ]
Makes element unselectable @method makeElementUnselectable @memberOf fabric.util @param {HTMLElement} element Element to make unselectable @return {HTMLElement} Element that was passed in
[ "Makes", "element", "unselectable" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2884-L2895
11,387
MrSwitch/hello.js
demos/Collage/fabric.js
makeElementSelectable
function makeElementSelectable(element) { if (typeof element.onselectstart !== 'undefined') { element.onselectstart = null; } if (selectProp) { element.style[selectProp] = ''; } else if (typeof element.unselectable == 'string') { element.unselectable = ''; } return element; }
javascript
function makeElementSelectable(element) { if (typeof element.onselectstart !== 'undefined') { element.onselectstart = null; } if (selectProp) { element.style[selectProp] = ''; } else if (typeof element.unselectable == 'string') { element.unselectable = ''; } return element; }
[ "function", "makeElementSelectable", "(", "element", ")", "{", "if", "(", "typeof", "element", ".", "onselectstart", "!==", "'undefined'", ")", "{", "element", ".", "onselectstart", "=", "null", ";", "}", "if", "(", "selectProp", ")", "{", "element", ".", "style", "[", "selectProp", "]", "=", "''", ";", "}", "else", "if", "(", "typeof", "element", ".", "unselectable", "==", "'string'", ")", "{", "element", ".", "unselectable", "=", "''", ";", "}", "return", "element", ";", "}" ]
Makes element selectable @method makeElementSelectable @memberOf fabric.util @param {HTMLElement} element Element to make selectable @return {HTMLElement} Element that was passed in
[ "Makes", "element", "selectable" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L2904-L2915
11,388
MrSwitch/hello.js
demos/Collage/fabric.js
request
function request(url, options) { options || (options = { }); var method = options.method ? options.method.toUpperCase() : 'GET', onComplete = options.onComplete || function() { }, request = makeXHR(), body; /** @ignore */ request.onreadystatechange = function() { if (request.readyState === 4) { onComplete(request); request.onreadystatechange = emptyFn; } }; if (method === 'GET') { body = null; if (typeof options.parameters == 'string') { url = addParamToUrl(url, options.parameters); } } request.open(method, url, true); if (method === 'POST' || method === 'PUT') { request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } request.send(body); return request; }
javascript
function request(url, options) { options || (options = { }); var method = options.method ? options.method.toUpperCase() : 'GET', onComplete = options.onComplete || function() { }, request = makeXHR(), body; /** @ignore */ request.onreadystatechange = function() { if (request.readyState === 4) { onComplete(request); request.onreadystatechange = emptyFn; } }; if (method === 'GET') { body = null; if (typeof options.parameters == 'string') { url = addParamToUrl(url, options.parameters); } } request.open(method, url, true); if (method === 'POST' || method === 'PUT') { request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } request.send(body); return request; }
[ "function", "request", "(", "url", ",", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "var", "method", "=", "options", ".", "method", "?", "options", ".", "method", ".", "toUpperCase", "(", ")", ":", "'GET'", ",", "onComplete", "=", "options", ".", "onComplete", "||", "function", "(", ")", "{", "}", ",", "request", "=", "makeXHR", "(", ")", ",", "body", ";", "/** @ignore */", "request", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "request", ".", "readyState", "===", "4", ")", "{", "onComplete", "(", "request", ")", ";", "request", ".", "onreadystatechange", "=", "emptyFn", ";", "}", "}", ";", "if", "(", "method", "===", "'GET'", ")", "{", "body", "=", "null", ";", "if", "(", "typeof", "options", ".", "parameters", "==", "'string'", ")", "{", "url", "=", "addParamToUrl", "(", "url", ",", "options", ".", "parameters", ")", ";", "}", "}", "request", ".", "open", "(", "method", ",", "url", ",", "true", ")", ";", "if", "(", "method", "===", "'POST'", "||", "method", "===", "'PUT'", ")", "{", "request", ".", "setRequestHeader", "(", "'Content-Type'", ",", "'application/x-www-form-urlencoded'", ")", ";", "}", "request", ".", "send", "(", "body", ")", ";", "return", "request", ";", "}" ]
Cross-browser abstraction for sending XMLHttpRequest @method request @memberOf fabric.util @param {String} url URL to send XMLHttpRequest to @param {Object} [options] Options object @param {String} [options.method="GET"] @param {Function} options.onComplete Callback to invoke when request is completed @return {XMLHttpRequest} request
[ "Cross", "-", "browser", "abstraction", "for", "sending", "XMLHttpRequest" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L3002-L3034
11,389
MrSwitch/hello.js
demos/Collage/fabric.js
parsePointsAttribute
function parsePointsAttribute(points) { // points attribute is required and must not be empty if (!points) return null; points = points.trim(); var asPairs = points.indexOf(',') > -1; points = points.split(/\s+/); var parsedPoints = [ ]; // points could look like "10,20 30,40" or "10 20 30 40" if (asPairs) { for (var i = 0, len = points.length; i < len; i++) { var pair = points[i].split(','); parsedPoints.push({ x: parseFloat(pair[0]), y: parseFloat(pair[1]) }); } } else { for (var i = 0, len = points.length; i < len; i+=2) { parsedPoints.push({ x: parseFloat(points[i]), y: parseFloat(points[i+1]) }); } } // odd number of points is an error if (parsedPoints.length % 2 !== 0) { // return null; } return parsedPoints; }
javascript
function parsePointsAttribute(points) { // points attribute is required and must not be empty if (!points) return null; points = points.trim(); var asPairs = points.indexOf(',') > -1; points = points.split(/\s+/); var parsedPoints = [ ]; // points could look like "10,20 30,40" or "10 20 30 40" if (asPairs) { for (var i = 0, len = points.length; i < len; i++) { var pair = points[i].split(','); parsedPoints.push({ x: parseFloat(pair[0]), y: parseFloat(pair[1]) }); } } else { for (var i = 0, len = points.length; i < len; i+=2) { parsedPoints.push({ x: parseFloat(points[i]), y: parseFloat(points[i+1]) }); } } // odd number of points is an error if (parsedPoints.length % 2 !== 0) { // return null; } return parsedPoints; }
[ "function", "parsePointsAttribute", "(", "points", ")", "{", "// points attribute is required and must not be empty", "if", "(", "!", "points", ")", "return", "null", ";", "points", "=", "points", ".", "trim", "(", ")", ";", "var", "asPairs", "=", "points", ".", "indexOf", "(", "','", ")", ">", "-", "1", ";", "points", "=", "points", ".", "split", "(", "/", "\\s+", "/", ")", ";", "var", "parsedPoints", "=", "[", "]", ";", "// points could look like \"10,20 30,40\" or \"10 20 30 40\"", "if", "(", "asPairs", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "points", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "pair", "=", "points", "[", "i", "]", ".", "split", "(", "','", ")", ";", "parsedPoints", ".", "push", "(", "{", "x", ":", "parseFloat", "(", "pair", "[", "0", "]", ")", ",", "y", ":", "parseFloat", "(", "pair", "[", "1", "]", ")", "}", ")", ";", "}", "}", "else", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "points", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "2", ")", "{", "parsedPoints", ".", "push", "(", "{", "x", ":", "parseFloat", "(", "points", "[", "i", "]", ")", ",", "y", ":", "parseFloat", "(", "points", "[", "i", "+", "1", "]", ")", "}", ")", ";", "}", "}", "// odd number of points is an error", "if", "(", "parsedPoints", ".", "length", "%", "2", "!==", "0", ")", "{", "// return null;", "}", "return", "parsedPoints", ";", "}" ]
Parses "points" attribute, returning an array of values @static @memberOf fabric @method parsePointsAttribute @param points {String} points attribute string @return {Array} array of points
[ "Parses", "points", "attribute", "returning", "an", "array", "of", "values" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L3582-L3612
11,390
MrSwitch/hello.js
demos/Collage/fabric.js
parseStyleAttribute
function parseStyleAttribute(element) { var oStyle = { }, style = element.getAttribute('style'); if (style) { if (typeof style == 'string') { style = style.replace(/;$/, '').split(';').forEach(function (current) { var attr = current.split(':'); oStyle[normalizeAttr(attr[0].trim().toLowerCase())] = attr[1].trim(); }); } else { for (var prop in style) { if (typeof style[prop] !== 'undefined') { oStyle[normalizeAttr(prop.toLowerCase())] = style[prop]; } } } } return oStyle; }
javascript
function parseStyleAttribute(element) { var oStyle = { }, style = element.getAttribute('style'); if (style) { if (typeof style == 'string') { style = style.replace(/;$/, '').split(';').forEach(function (current) { var attr = current.split(':'); oStyle[normalizeAttr(attr[0].trim().toLowerCase())] = attr[1].trim(); }); } else { for (var prop in style) { if (typeof style[prop] !== 'undefined') { oStyle[normalizeAttr(prop.toLowerCase())] = style[prop]; } } } } return oStyle; }
[ "function", "parseStyleAttribute", "(", "element", ")", "{", "var", "oStyle", "=", "{", "}", ",", "style", "=", "element", ".", "getAttribute", "(", "'style'", ")", ";", "if", "(", "style", ")", "{", "if", "(", "typeof", "style", "==", "'string'", ")", "{", "style", "=", "style", ".", "replace", "(", "/", ";$", "/", ",", "''", ")", ".", "split", "(", "';'", ")", ".", "forEach", "(", "function", "(", "current", ")", "{", "var", "attr", "=", "current", ".", "split", "(", "':'", ")", ";", "oStyle", "[", "normalizeAttr", "(", "attr", "[", "0", "]", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ")", "]", "=", "attr", "[", "1", "]", ".", "trim", "(", ")", ";", "}", ")", ";", "}", "else", "{", "for", "(", "var", "prop", "in", "style", ")", "{", "if", "(", "typeof", "style", "[", "prop", "]", "!==", "'undefined'", ")", "{", "oStyle", "[", "normalizeAttr", "(", "prop", ".", "toLowerCase", "(", ")", ")", "]", "=", "style", "[", "prop", "]", ";", "}", "}", "}", "}", "return", "oStyle", ";", "}" ]
Parses "style" attribute, retuning an object with values @static @memberOf fabric @method parseStyleAttribute @param {SVGElement} element Element to parse @return {Object} Objects with values parsed from style attribute of an element
[ "Parses", "style", "attribute", "retuning", "an", "object", "with", "values" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L3622-L3640
11,391
MrSwitch/hello.js
demos/Collage/fabric.js
getCSSRules
function getCSSRules(doc) { var styles = doc.getElementsByTagName('style'), allRules = { }, rules; // very crude parsing of style contents for (var i = 0, len = styles.length; i < len; i++) { var styleContents = styles[0].textContent; // remove comments styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, ''); rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g); rules = rules.map(function(rule) { return rule.trim() }); rules.forEach(function(rule) { var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/), rule = match[1], declaration = match[2].trim(), propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/); if (!allRules[rule]) { allRules[rule] = { }; } for (var i = 0, len = propertyValuePairs.length; i < len; i++) { var pair = propertyValuePairs[i].split(/\s*:\s*/), property = pair[0], value = pair[1]; allRules[rule][property] = value; } }); } return allRules; }
javascript
function getCSSRules(doc) { var styles = doc.getElementsByTagName('style'), allRules = { }, rules; // very crude parsing of style contents for (var i = 0, len = styles.length; i < len; i++) { var styleContents = styles[0].textContent; // remove comments styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, ''); rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g); rules = rules.map(function(rule) { return rule.trim() }); rules.forEach(function(rule) { var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/), rule = match[1], declaration = match[2].trim(), propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/); if (!allRules[rule]) { allRules[rule] = { }; } for (var i = 0, len = propertyValuePairs.length; i < len; i++) { var pair = propertyValuePairs[i].split(/\s*:\s*/), property = pair[0], value = pair[1]; allRules[rule][property] = value; } }); } return allRules; }
[ "function", "getCSSRules", "(", "doc", ")", "{", "var", "styles", "=", "doc", ".", "getElementsByTagName", "(", "'style'", ")", ",", "allRules", "=", "{", "}", ",", "rules", ";", "// very crude parsing of style contents", "for", "(", "var", "i", "=", "0", ",", "len", "=", "styles", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "styleContents", "=", "styles", "[", "0", "]", ".", "textContent", ";", "// remove comments", "styleContents", "=", "styleContents", ".", "replace", "(", "/", "\\/\\*[\\s\\S]*?\\*\\/", "/", "g", ",", "''", ")", ";", "rules", "=", "styleContents", ".", "match", "(", "/", "[^{]*\\{[\\s\\S]*?\\}", "/", "g", ")", ";", "rules", "=", "rules", ".", "map", "(", "function", "(", "rule", ")", "{", "return", "rule", ".", "trim", "(", ")", "}", ")", ";", "rules", ".", "forEach", "(", "function", "(", "rule", ")", "{", "var", "match", "=", "rule", ".", "match", "(", "/", "([\\s\\S]*?)\\s*\\{([^}]*)\\}", "/", ")", ",", "rule", "=", "match", "[", "1", "]", ",", "declaration", "=", "match", "[", "2", "]", ".", "trim", "(", ")", ",", "propertyValuePairs", "=", "declaration", ".", "replace", "(", "/", ";$", "/", ",", "''", ")", ".", "split", "(", "/", "\\s*;\\s*", "/", ")", ";", "if", "(", "!", "allRules", "[", "rule", "]", ")", "{", "allRules", "[", "rule", "]", "=", "{", "}", ";", "}", "for", "(", "var", "i", "=", "0", ",", "len", "=", "propertyValuePairs", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "pair", "=", "propertyValuePairs", "[", "i", "]", ".", "split", "(", "/", "\\s*:\\s*", "/", ")", ",", "property", "=", "pair", "[", "0", "]", ",", "value", "=", "pair", "[", "1", "]", ";", "allRules", "[", "rule", "]", "[", "property", "]", "=", "value", ";", "}", "}", ")", ";", "}", "return", "allRules", ";", "}" ]
Returns CSS rules for a given SVG document @static @function @memberOf fabric @method getCSSRules @param {SVGDocument} doc SVG document to parse @return {Object} CSS rules of this document
[ "Returns", "CSS", "rules", "for", "a", "given", "SVG", "document" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L3721-L3757
11,392
MrSwitch/hello.js
demos/Collage/fabric.js
loadSVGFromURL
function loadSVGFromURL(url, callback, reviver) { url = url.replace(/^\n\s*/, '').trim(); svgCache.has(url, function (hasUrl) { if (hasUrl) { svgCache.get(url, function (value) { var enlivedRecord = _enlivenCachedObject(value); callback(enlivedRecord.objects, enlivedRecord.options); }); } else { new fabric.util.request(url, { method: 'get', onComplete: onComplete }); } }); function onComplete(r) { var xml = r.responseXML; if (!xml.documentElement && fabric.window.ActiveXObject && r.responseText) { xml = new ActiveXObject('Microsoft.XMLDOM'); xml.async = 'false'; //IE chokes on DOCTYPE xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,'')); } if (!xml.documentElement) return; fabric.parseSVGDocument(xml.documentElement, function (results, options) { svgCache.set(url, { objects: fabric.util.array.invoke(results, 'toObject'), options: options }); callback(results, options); }, reviver); } }
javascript
function loadSVGFromURL(url, callback, reviver) { url = url.replace(/^\n\s*/, '').trim(); svgCache.has(url, function (hasUrl) { if (hasUrl) { svgCache.get(url, function (value) { var enlivedRecord = _enlivenCachedObject(value); callback(enlivedRecord.objects, enlivedRecord.options); }); } else { new fabric.util.request(url, { method: 'get', onComplete: onComplete }); } }); function onComplete(r) { var xml = r.responseXML; if (!xml.documentElement && fabric.window.ActiveXObject && r.responseText) { xml = new ActiveXObject('Microsoft.XMLDOM'); xml.async = 'false'; //IE chokes on DOCTYPE xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,'')); } if (!xml.documentElement) return; fabric.parseSVGDocument(xml.documentElement, function (results, options) { svgCache.set(url, { objects: fabric.util.array.invoke(results, 'toObject'), options: options }); callback(results, options); }, reviver); } }
[ "function", "loadSVGFromURL", "(", "url", ",", "callback", ",", "reviver", ")", "{", "url", "=", "url", ".", "replace", "(", "/", "^\\n\\s*", "/", ",", "''", ")", ".", "trim", "(", ")", ";", "svgCache", ".", "has", "(", "url", ",", "function", "(", "hasUrl", ")", "{", "if", "(", "hasUrl", ")", "{", "svgCache", ".", "get", "(", "url", ",", "function", "(", "value", ")", "{", "var", "enlivedRecord", "=", "_enlivenCachedObject", "(", "value", ")", ";", "callback", "(", "enlivedRecord", ".", "objects", ",", "enlivedRecord", ".", "options", ")", ";", "}", ")", ";", "}", "else", "{", "new", "fabric", ".", "util", ".", "request", "(", "url", ",", "{", "method", ":", "'get'", ",", "onComplete", ":", "onComplete", "}", ")", ";", "}", "}", ")", ";", "function", "onComplete", "(", "r", ")", "{", "var", "xml", "=", "r", ".", "responseXML", ";", "if", "(", "!", "xml", ".", "documentElement", "&&", "fabric", ".", "window", ".", "ActiveXObject", "&&", "r", ".", "responseText", ")", "{", "xml", "=", "new", "ActiveXObject", "(", "'Microsoft.XMLDOM'", ")", ";", "xml", ".", "async", "=", "'false'", ";", "//IE chokes on DOCTYPE", "xml", ".", "loadXML", "(", "r", ".", "responseText", ".", "replace", "(", "/", "<!DOCTYPE[\\s\\S]*?(\\[[\\s\\S]*\\])*?>", "/", "i", ",", "''", ")", ")", ";", "}", "if", "(", "!", "xml", ".", "documentElement", ")", "return", ";", "fabric", ".", "parseSVGDocument", "(", "xml", ".", "documentElement", ",", "function", "(", "results", ",", "options", ")", "{", "svgCache", ".", "set", "(", "url", ",", "{", "objects", ":", "fabric", ".", "util", ".", "array", ".", "invoke", "(", "results", ",", "'toObject'", ")", ",", "options", ":", "options", "}", ")", ";", "callback", "(", "results", ",", "options", ")", ";", "}", ",", "reviver", ")", ";", "}", "}" ]
Takes url corresponding to an SVG document, and parses it into a set of fabric objects @method loadSVGFromURL @param {String} url @param {Function} callback @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
[ "Takes", "url", "corresponding", "to", "an", "SVG", "document", "and", "parses", "it", "into", "a", "set", "of", "fabric", "objects" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L3922-L3960
11,393
MrSwitch/hello.js
demos/Collage/fabric.js
loadSVGFromString
function loadSVGFromString(string, callback, reviver) { string = string.trim(); var doc; if (typeof DOMParser !== 'undefined') { var parser = new DOMParser(); if (parser && parser.parseFromString) { doc = parser.parseFromString(string, 'text/xml'); } } else if (fabric.window.ActiveXObject) { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; //IE chokes on DOCTYPE doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,'')); } fabric.parseSVGDocument(doc.documentElement, function (results, options) { callback(results, options); }, reviver); }
javascript
function loadSVGFromString(string, callback, reviver) { string = string.trim(); var doc; if (typeof DOMParser !== 'undefined') { var parser = new DOMParser(); if (parser && parser.parseFromString) { doc = parser.parseFromString(string, 'text/xml'); } } else if (fabric.window.ActiveXObject) { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; //IE chokes on DOCTYPE doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,'')); } fabric.parseSVGDocument(doc.documentElement, function (results, options) { callback(results, options); }, reviver); }
[ "function", "loadSVGFromString", "(", "string", ",", "callback", ",", "reviver", ")", "{", "string", "=", "string", ".", "trim", "(", ")", ";", "var", "doc", ";", "if", "(", "typeof", "DOMParser", "!==", "'undefined'", ")", "{", "var", "parser", "=", "new", "DOMParser", "(", ")", ";", "if", "(", "parser", "&&", "parser", ".", "parseFromString", ")", "{", "doc", "=", "parser", ".", "parseFromString", "(", "string", ",", "'text/xml'", ")", ";", "}", "}", "else", "if", "(", "fabric", ".", "window", ".", "ActiveXObject", ")", "{", "var", "doc", "=", "new", "ActiveXObject", "(", "'Microsoft.XMLDOM'", ")", ";", "doc", ".", "async", "=", "'false'", ";", "//IE chokes on DOCTYPE", "doc", ".", "loadXML", "(", "string", ".", "replace", "(", "/", "<!DOCTYPE[\\s\\S]*?(\\[[\\s\\S]*\\])*?>", "/", "i", ",", "''", ")", ")", ";", "}", "fabric", ".", "parseSVGDocument", "(", "doc", ".", "documentElement", ",", "function", "(", "results", ",", "options", ")", "{", "callback", "(", "results", ",", "options", ")", ";", "}", ",", "reviver", ")", ";", "}" ]
Takes string corresponding to an SVG document, and parses it into a set of fabric objects @method loadSVGFromString @param {String} string @param {Function} callback @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
[ "Takes", "string", "corresponding", "to", "an", "SVG", "document", "and", "parses", "it", "into", "a", "set", "of", "fabric", "objects" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L3984-L4003
11,394
MrSwitch/hello.js
demos/Collage/fabric.js
getGradientDefs
function getGradientDefs(doc) { var linearGradientEls = doc.getElementsByTagName('linearGradient'), radialGradientEls = doc.getElementsByTagName('radialGradient'), el, gradientDefs = { }; for (var i = linearGradientEls.length; i--; ) { el = linearGradientEls[i]; gradientDefs[el.getAttribute('id')] = el; } for (var i = radialGradientEls.length; i--; ) { el = radialGradientEls[i]; gradientDefs[el.getAttribute('id')] = el; } return gradientDefs; }
javascript
function getGradientDefs(doc) { var linearGradientEls = doc.getElementsByTagName('linearGradient'), radialGradientEls = doc.getElementsByTagName('radialGradient'), el, gradientDefs = { }; for (var i = linearGradientEls.length; i--; ) { el = linearGradientEls[i]; gradientDefs[el.getAttribute('id')] = el; } for (var i = radialGradientEls.length; i--; ) { el = radialGradientEls[i]; gradientDefs[el.getAttribute('id')] = el; } return gradientDefs; }
[ "function", "getGradientDefs", "(", "doc", ")", "{", "var", "linearGradientEls", "=", "doc", ".", "getElementsByTagName", "(", "'linearGradient'", ")", ",", "radialGradientEls", "=", "doc", ".", "getElementsByTagName", "(", "'radialGradient'", ")", ",", "el", ",", "gradientDefs", "=", "{", "}", ";", "for", "(", "var", "i", "=", "linearGradientEls", ".", "length", ";", "i", "--", ";", ")", "{", "el", "=", "linearGradientEls", "[", "i", "]", ";", "gradientDefs", "[", "el", ".", "getAttribute", "(", "'id'", ")", "]", "=", "el", ";", "}", "for", "(", "var", "i", "=", "radialGradientEls", ".", "length", ";", "i", "--", ";", ")", "{", "el", "=", "radialGradientEls", "[", "i", "]", ";", "gradientDefs", "[", "el", ".", "getAttribute", "(", "'id'", ")", "]", "=", "el", ";", "}", "return", "gradientDefs", ";", "}" ]
Parses an SVG document, returning all of the gradient declarations found in it @static @function @memberOf fabric @method getGradientDefs @param {SVGDocument} doc SVG document to parse @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element
[ "Parses", "an", "SVG", "document", "returning", "all", "of", "the", "gradient", "declarations", "found", "in", "it" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L4215-L4232
11,395
MrSwitch/hello.js
demos/Collage/fabric.js
function() { var source = this.getSource(); var r = source[0].toString(16); r = (r.length == 1) ? ('0' + r) : r; var g = source[1].toString(16); g = (g.length == 1) ? ('0' + g) : g; var b = source[2].toString(16); b = (b.length == 1) ? ('0' + b) : b; return r.toUpperCase() + g.toUpperCase() + b.toUpperCase(); }
javascript
function() { var source = this.getSource(); var r = source[0].toString(16); r = (r.length == 1) ? ('0' + r) : r; var g = source[1].toString(16); g = (g.length == 1) ? ('0' + g) : g; var b = source[2].toString(16); b = (b.length == 1) ? ('0' + b) : b; return r.toUpperCase() + g.toUpperCase() + b.toUpperCase(); }
[ "function", "(", ")", "{", "var", "source", "=", "this", ".", "getSource", "(", ")", ";", "var", "r", "=", "source", "[", "0", "]", ".", "toString", "(", "16", ")", ";", "r", "=", "(", "r", ".", "length", "==", "1", ")", "?", "(", "'0'", "+", "r", ")", ":", "r", ";", "var", "g", "=", "source", "[", "1", "]", ".", "toString", "(", "16", ")", ";", "g", "=", "(", "g", ".", "length", "==", "1", ")", "?", "(", "'0'", "+", "g", ")", ":", "g", ";", "var", "b", "=", "source", "[", "2", "]", ".", "toString", "(", "16", ")", ";", "b", "=", "(", "b", ".", "length", "==", "1", ")", "?", "(", "'0'", "+", "b", ")", ":", "b", ";", "return", "r", ".", "toUpperCase", "(", ")", "+", "g", ".", "toUpperCase", "(", ")", "+", "b", ".", "toUpperCase", "(", ")", ";", "}" ]
Returns color represenation in HEX format @method toHex @return {String} ex: FF5555
[ "Returns", "color", "represenation", "in", "HEX", "format" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L4671-L4684
11,396
MrSwitch/hello.js
demos/Collage/fabric.js
function() { var source = this.getSource(), average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10), currentAlpha = source[3]; this.setSource([average, average, average, currentAlpha]); return this; }
javascript
function() { var source = this.getSource(), average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10), currentAlpha = source[3]; this.setSource([average, average, average, currentAlpha]); return this; }
[ "function", "(", ")", "{", "var", "source", "=", "this", ".", "getSource", "(", ")", ",", "average", "=", "parseInt", "(", "(", "source", "[", "0", "]", "*", "0.3", "+", "source", "[", "1", "]", "*", "0.59", "+", "source", "[", "2", "]", "*", "0.11", ")", ".", "toFixed", "(", "0", ")", ",", "10", ")", ",", "currentAlpha", "=", "source", "[", "3", "]", ";", "this", ".", "setSource", "(", "[", "average", ",", "average", ",", "average", ",", "currentAlpha", "]", ")", ";", "return", "this", ";", "}" ]
Transforms color to its grayscale representation @method toGrayscale @return {fabric.Color} thisArg
[ "Transforms", "color", "to", "its", "grayscale", "representation" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L4713-L4719
11,397
MrSwitch/hello.js
demos/Collage/fabric.js
function(threshold) { var source = this.getSource(), average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), currentAlpha = source[3], threshold = threshold || 127; average = (Number(average) < Number(threshold)) ? 0 : 255; this.setSource([average, average, average, currentAlpha]); return this; }
javascript
function(threshold) { var source = this.getSource(), average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), currentAlpha = source[3], threshold = threshold || 127; average = (Number(average) < Number(threshold)) ? 0 : 255; this.setSource([average, average, average, currentAlpha]); return this; }
[ "function", "(", "threshold", ")", "{", "var", "source", "=", "this", ".", "getSource", "(", ")", ",", "average", "=", "(", "source", "[", "0", "]", "*", "0.3", "+", "source", "[", "1", "]", "*", "0.59", "+", "source", "[", "2", "]", "*", "0.11", ")", ".", "toFixed", "(", "0", ")", ",", "currentAlpha", "=", "source", "[", "3", "]", ",", "threshold", "=", "threshold", "||", "127", ";", "average", "=", "(", "Number", "(", "average", ")", "<", "Number", "(", "threshold", ")", ")", "?", "0", ":", "255", ";", "this", ".", "setSource", "(", "[", "average", ",", "average", ",", "average", ",", "currentAlpha", "]", ")", ";", "return", "this", ";", "}" ]
Transforms color to its black and white representation @method toGrayscale @return {fabric.Color} thisArg
[ "Transforms", "color", "to", "its", "black", "and", "white", "representation" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L4726-L4735
11,398
MrSwitch/hello.js
demos/Collage/fabric.js
function(otherColor) { if (!(otherColor instanceof Color)) { otherColor = new Color(otherColor); } var result = [], alpha = this.getAlpha(), otherAlpha = 0.5, source = this.getSource(), otherSource = otherColor.getSource(); for (var i = 0; i < 3; i++) { result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha))); } result[3] = alpha; this.setSource(result); return this; }
javascript
function(otherColor) { if (!(otherColor instanceof Color)) { otherColor = new Color(otherColor); } var result = [], alpha = this.getAlpha(), otherAlpha = 0.5, source = this.getSource(), otherSource = otherColor.getSource(); for (var i = 0; i < 3; i++) { result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha))); } result[3] = alpha; this.setSource(result); return this; }
[ "function", "(", "otherColor", ")", "{", "if", "(", "!", "(", "otherColor", "instanceof", "Color", ")", ")", "{", "otherColor", "=", "new", "Color", "(", "otherColor", ")", ";", "}", "var", "result", "=", "[", "]", ",", "alpha", "=", "this", ".", "getAlpha", "(", ")", ",", "otherAlpha", "=", "0.5", ",", "source", "=", "this", ".", "getSource", "(", ")", ",", "otherSource", "=", "otherColor", ".", "getSource", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "3", ";", "i", "++", ")", "{", "result", ".", "push", "(", "Math", ".", "round", "(", "(", "source", "[", "i", "]", "*", "(", "1", "-", "otherAlpha", ")", ")", "+", "(", "otherSource", "[", "i", "]", "*", "otherAlpha", ")", ")", ")", ";", "}", "result", "[", "3", "]", "=", "alpha", ";", "this", ".", "setSource", "(", "result", ")", ";", "return", "this", ";", "}" ]
Overlays color with another color @method overlayWith @param {String|fabric.Color} otherColor @return {fabric.Color} thisArg
[ "Overlays", "color", "with", "another", "color" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L4743-L4761
11,399
MrSwitch/hello.js
demos/Collage/fabric.js
function (url, callback) { // TODO (kangax): test callback fabric.util.loadImage(url, function(img) { this.overlayImage = img; callback && callback(); }, this); return this; }
javascript
function (url, callback) { // TODO (kangax): test callback fabric.util.loadImage(url, function(img) { this.overlayImage = img; callback && callback(); }, this); return this; }
[ "function", "(", "url", ",", "callback", ")", "{", "// TODO (kangax): test callback", "fabric", ".", "util", ".", "loadImage", "(", "url", ",", "function", "(", "img", ")", "{", "this", ".", "overlayImage", "=", "img", ";", "callback", "&&", "callback", "(", ")", ";", "}", ",", "this", ")", ";", "return", "this", ";", "}" ]
Sets overlay image for this canvas @method setOverlayImage @param {String} url url of an image to set overlay to @param {Function} callback callback to invoke when image is loaded and set as an overlay @return {fabric.Canvas} thisArg @chainable
[ "Sets", "overlay", "image", "for", "this", "canvas" ]
50b2b792d758774fc08e8da911fd4415ea3831ba
https://github.com/MrSwitch/hello.js/blob/50b2b792d758774fc08e8da911fd4415ea3831ba/demos/Collage/fabric.js#L5014-L5020