code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/** * @author Gilles Coomans <gilles.coomans@gmail.com> * */ if (typeof define !== 'function') { var define = require('amdefine')(module); } define(["require", "./marked", "./directives-parser", "./directives", "./utils"], function(require, marked, directivesParser, directives, utils){ var makro = function(src, opt){ opt = opt || {}; opt = marked.merge({}, marked.defaults, makro.opt, opt); return marked(src, opt || makro.opt); }; //_________________________________________________________________________ //_________________________________________________________________________ INLINE LEXER marked.InlineLexer.prototype.custom = function(src, out) { var cap; //_________________________________________________________________________________ DIRECT MACRO if (cap = this.rules.direct_macro.exec(src)) { src = src.substring(cap[0].length); var dir = []; src = directivesParser.directive(src, dir); dir = dir[0]; out += this.renderer.inline_macro(dir, this.options); return { src:src, out:out }; } //_________________________________________________________________________________ REPLACE MACRO if (cap = this.rules.replace_macro.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.replace_macro(cap[1], this.options); return { src:src, out:out }; } return null; }; marked.InlineLexer.prototype.customiseRules = function() { // customise native text rule this.rules.text = /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|\{\{|@\.|$)/; // adding new rules this.rules.direct_macro = /^@\./; this.rules.replace_macro = /^\{\{\s*([^\n\r]*)(?=\}\})\}\}/; }; //_________________________________________________________________________ //_________________________________________________________________________ LEXER marked.Lexer.prototype.custom = function(src, top, bq) { //________________________________________________________________________________________ Direct MACROS // direct macro if (cap = this.rules.direct_macro.exec(src)) { src = src.substring(cap[0].length); var dir = [], content = ""; src = directivesParser.directive(src, dir); cap = this.rules.endOfLine.exec(src); if(cap) { src = src.substring(cap[0].length); content = cap[0]; } this.tokens.push({ type: 'direct_macro', directives: dir, content:content }); return { src:src, top:top, bq:bq }; } //_________________________________________________________________________________ Raw MACRO // raw macro if (cap = this.rules.raw_macro.exec(src)) { src = src.substring(cap[0].length); var directives = directivesParser.analyse(src, this.rules.raw_directives_end); src = directives.src; cap = this.rules.raw_macro_end.exec(src); if(!cap) throw new Error("bad raw macro declaration : missing end of block.") src = src.substring(cap[0].length); var obj = { type: 'raw_macro', directives: directives.tokens, content:cap[1] }; this.tokens.push(obj); return { src:src, top:top, bq:bq }; } //________________________________________________________________________________________ BLOCK MACRO START // block_macro_start if (cap = this.rules.block_macro_start.exec(src)) { src = src.substring(cap[0].length); var directives = directivesParser.analyse(src, this.rules.endBlockDirectives); if(!directives.tokens.length) throw new Error("bad block macro declaration : missing directives.") src = directives.src; this.tokens.push({ type: 'block_macro_start', directives: directives.tokens }); return { src:src, top:top, bq:bq }; } //________________________________________________________________________________________ BLOCK MACRO END // block_macro_end if (cap = this.rules.block_macro_end.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'block_macro_end', }); return { src:src, top:top, bq:bq }; } //________________________________________________________________________________________ REPLACE MACROS // replace macro if (cap = this.rules.replace_macro.exec(src)) { src = src.substring(cap[0].length); var obj = { type: 'replace_macro', text: cap[1] }; this.tokens.push(obj); return { src:src, top:top, bq:bq }; } return null; }; marked.Lexer.prototype.customiseRules = function() { // customise paragraph from native rules this.rules.paragraph = /^\s*([\s\S]+?)(?=%\}|\n\n|$)/; // adding new rules this.rules.block_macro_start = /^\s*\{%\s*/; this.rules.endBlockDirectives = /^\s*(\n|(%\}))/; this.rules.block_macro_end = /^\s*%\}\s*($|\n)/; this.rules.raw_macro = /^\s*\{\!\s*/; this.rules.raw_directives_end = /^\s*(\n|(\!\}))/; this.rules.raw_macro_end = /^\n?([\s\S]*?(?=\!\}))\!\}/; this.rules.replace_macro = /^\s*\{\{\s*([^\n]*)(?=\}\})\}\}/; this.rules.direct_macro = /^@\./; this.rules.endOfLine =/^[^\n]*/; }; //_________________________________________________________________________ //__________________________________________________________________ PARSER marked.Parser.prototype.custom = function(){ switch (this.token.type) { case 'direct_macro': return this.renderer.block_macro(this.token.directives, this.token.content, this.options); case 'raw_macro': return this.renderer.block_macro(this.token.directives, this.token.content, this.options); case 'replace_macro': return this.renderer.replace_macro(this.token.text, this.options); case 'block_macro_start': var body = ''; var toky = this.token, next = this.next(); while (next && next.type !== 'block_macro_end') { body += this.tok(); next = this.next(); } if(!next) throw new Error("block macros not ended !"); return this.renderer.block_macro(toky.directives, body, this.options); } } //_________________________________________________________________________ //_________________________________________________________________________ RENDERER //____________________________________________________________ BLOCK MACRO marked.Renderer.prototype.block_macro = function(directives, content, options) { // console.log("render block macro : ", directives, content); //var res = (typeof content === 'undefined')?"":content; var res = (!content && content !== "")?"":content; for(var i = directives.length; --i >= 0;) { var dir = directives[i]; var mcr = makro.getDirectives(dir.name, "block"); if(!mcr) res = makro.directives.blockDefault(dir, res); else res = mcr(dir.args, res, options); } return res; }; //_____________________________________________________________ DIRECT MACRO marked.Renderer.prototype.inline_macro = function(directive, options) { var mcr = makro.getDirectives(directive.name, "inline"); if(!mcr) return makro.directives.inlineDefault(directive); else return mcr(directive.args, options); }; //_____________________________________________________________ REPLACE MACRO var trimSpace = /\s*$/; marked.Renderer.prototype.replace_macro = function(content, options) { var toRem = trimSpace.exec(content)[0].length; content = content.substring(0, content.length-toRem); if(options.context) return utils.fromPath(options.context, content); return '[(replaced)' + content + ']'; }; //_______________________________________________________________________ //_______________________________________________________________________ COMPILE marked.compile = function(src, opt){ try { opt = opt || {}; opt = marked.merge({}, marked.defaults, makro.opt, opt); var tokens = marked.Lexer.lex(src, opt); return function(context){ // console.log("tokens : ", tokens); opt.context = context; var tok = tokens.slice(); tok.links = tokens.links; var res = marked.Parser.parse(tok, opt); return res; } } catch (e) { e.message += '\nPlease report this to https://github.com/chjj/marked.'; if ((opt || marked.defaults).silent) { return '<p>An error occured:</p><pre>' + escape(e.message + '', true) + '</pre>'; } throw e; } }; //______________________________________________________________________________________ makro.opt = { renderer: new marked.Renderer(), codespaces:false }; marked.setOptions(makro.opt); makro.compile = marked.compile; makro.directives = directives; makro.getDirectives = function(name, type){ var dir = makro.directives[name]; if(!dir) return null; if(typeof dir === 'function') return dir; return dir[type] || null; }; makro.setOptions = function(opt){ marked.merge(makro.opt, opt); marked.setOptions(opt); }; makro.marked = marked; return makro; });
deepjs/deepjs.github.io
libs/kroked/lib/makro.js
JavaScript
apache-2.0
8,751
var gulp = require('gulp'); var istanbul = require('gulp-istanbul'); var mocha = require('gulp-mocha'); var gp_deploy = require('gulp-gh-pages'); var open = require("gulp-open"); var rename = require("gulp-rename"); require('shelljs/global'); gulp.task('test', function (cb) { gulp.src(['db/**/*.js']) .pipe(istanbul()) // Covering files .on('finish', function () { gulp.src(['test/*.js']) .pipe(mocha({ ui : 'bdd', reporter: 'spec' })) .pipe(istanbul.writeReports()) // Creating the reports after tests runned .on('end', cb); }); }); gulp.task('default',['test'], function() { gulp.watch(['./db/**/*','./test/**/*'], ['test']); }); gulp.task('watch',['test'], function() { gulp.watch(['./db/**/*','./test/**/*'], ['test']); }); var options = {} gulp.task('deploy', function () { return gulp.src('./preview/**/*') .pipe(gp_deploy(options)); }); gulp.task('rename',function () { if (exec('cp ./preview/README.html ./preview/index.html').code !== 0) { echo('Error: rename exec failed'); exit(1); } }); gulp.task('generate',function () { // Run external tool synchronously if (exec('sh ./generate.sh').code !== 0) { echo('Error: generate.sh exec failed'); exit(1); } }); gulp.task('doc',['generate', 'rename', 'deploy'] ,function () { console.log('default'); });
i5ting/ichat
server/gulpfile.js
JavaScript
apache-2.0
1,365
var MSG = { title: "Còdixi", blocks: "Brocus", linkTooltip: "Sarva e alliòngia a is brocus.", runTooltip: "Arròllia su programa cumpostu de is brocus in s'àrea de traballu.", badCode: "Errori in su Programa:\n%1", timeout: "Giai lòmpius a su màssimu numeru de repicus.", discard: "Scancellu su %1 de is brocus?", trashTooltip: "Boganci totu is brocus.", catMinecraft:'Minecraft', catLogic: "Lògica", catLoops: "Lòrigas", catMath: "Matemàtica", catText: "Testu", catLists: "Lista", catColour: "Colori", catVariables: "Variabilis", catFunctions: "Funtzionis", listVariable: "lista", textVariable: "testu", httpRequestError: "Ddui fut unu problema cun sa pregunta", linkAlert: "Poni is brocus tuus in custu acàpiu:\n\n(Ctrl-C or Cmd-C to copy link)", hashError: "Mi dispraxit, '%1' non torrat a pari cun nimancu unu de is programas sarvaus.", xmlError: "Non potzu carrigai su file sarvau. Fortzis est stètiu fatu cun d-una versioni diferenti de Blockly?", badXml: "Errori in s'anàlisi XML:\n%1\n\nCraca 'OK' po perdi is mudàntzias 'Anudda' po sighì a scriri su XML." };
markocelan/blockly-minecraft
minecraft/msg/sc.js
JavaScript
apache-2.0
1,129
module.exports = { "version": "1.2.0", "timeStamp": 1422863440.043, "count": 38, "id": 1212, "file": "/Users/baranovs/Desktop/texts.psd", "bounds": { "top": 0, "left": 0, "bottom": 1024, "right": 1024 }, "selection": [ 6 ], "resolution": 144, "globalLight": { "angle": 120, "altitude": 30 }, "generatorSettings": false, "layers": [ { "id": 3, "index": 8, "type": "textLayer", "name": "thin ultrathin thin italic medium light oblique book slanted", "bounds": { "top": 76, "left": 381, "bottom": 897, "right": 784 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "thin\rultrathin\rthin italic\rmedium\rlight oblique\rbook\rslanted", "textClickPoint": { "horizontal": { "value": 36.111069, "units": "percentUnit" }, "vertical": { "value": 12.471008, "units": "percentUnit" } }, "boundingBox": { "left": 12.15625, "top": -51, "right": 412.885193, "bottom": 768.997375 }, "bounds": { "left": 11.640747, "top": -61.703613, "right": 413.793274, "bottom": 788.735596 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 5, "textStyle": { "fontName": "Helvetica Neue", "fontStyleName": "Thin", "size": 72, "fontPostScriptName": "HelveticaNeue-Thin", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "fontTechnology": 1, "leading": 111, "tracking": 5 } }, { "from": 5, "to": 15, "textStyle": { "fontName": "Helvetica Neue", "fontStyleName": "UltraLight", "size": 72, "fontPostScriptName": "HelveticaNeue-UltraLight", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "fontTechnology": 1, "leading": 111, "tracking": 5 } }, { "from": 15, "to": 27, "textStyle": { "fontName": "Helvetica Neue", "fontStyleName": "Thin Italic", "size": 72, "fontPostScriptName": "HelveticaNeue-ThinItalic", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "fontTechnology": 1, "leading": 111, "tracking": 5 } }, { "from": 27, "to": 34, "textStyle": { "fontName": "Helvetica Neue", "fontStyleName": "Medium", "size": 72, "fontPostScriptName": "HelveticaNeue-Medium", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "fontTechnology": 1, "leading": 111, "tracking": 5 } }, { "from": 34, "to": 48, "textStyle": { "fontName": "Helvetica", "fontStyleName": "Light Oblique", "size": 72, "fontPostScriptName": "Helvetica-LightOblique", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "fontTechnology": 1, "leading": 111, "tracking": 5 } }, { "from": 48, "to": 53, "textStyle": { "fontName": "Bodoni 72", "fontStyleName": "Book", "size": 72, "fontPostScriptName": "BodoniSvtyTwoITCTT-Book", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "fontTechnology": 1, "leading": 111, "tracking": 5 } }, { "from": 53, "to": 61, "textStyle": { "fontName": "Letter Gothic Std", "fontStyleName": "Slanted", "size": 72, "fontPostScriptName": "LetterGothicStd-Slanted", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 5, "paragraphStyle": { "align": "left", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } }, { "from": 5, "to": 15, "paragraphStyle": { "align": "left", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } }, { "from": 15, "to": 27, "paragraphStyle": { "align": "left", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } }, { "from": 27, "to": 34, "paragraphStyle": { "align": "left", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } }, { "from": 34, "to": 48, "paragraphStyle": { "align": "left", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } }, { "from": 48, "to": 53, "paragraphStyle": { "align": "left", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } }, { "from": 53, "to": 61, "paragraphStyle": { "align": "left", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 4, "index": 7, "type": "textLayer", "name": "1 copy", "bounds": { "top": 76, "left": 84, "bottom": 120, "right": 97 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "1", "textClickPoint": { "horizontal": { "value": 8.47435, "units": "percentUnit" }, "vertical": { "value": 14.619446, "units": "percentUnit" } }, "boundingBox": { "left": -2.017883, "top": -73.155258, "right": 9.958511, "bottom": -30.435028 }, "bounds": { "left": -12.979004, "top": -92.130203, "right": 27.53437, "bottom": 30.41423 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 2, "textStyle": { "fontName": "Source Sans Pro", "fontStyleName": "ExtraLight", "size": 111, "fontPostScriptName": "SourceSansPro-ExtraLight", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 2, "paragraphStyle": { "align": "center", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 9, "index": 6, "type": "textLayer", "name": "7", "bounds": { "top": 846, "left": 84, "bottom": 890, "right": 119 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "7", "textClickPoint": { "horizontal": { "value": 8.47435, "units": "percentUnit" }, "vertical": { "value": 89.814758, "units": "percentUnit" } }, "boundingBox": { "left": -1.361084, "top": -73.998917, "right": 32.513947, "bottom": -30.714111 }, "bounds": { "left": -13.423584, "top": -92.130203, "right": 32.528885, "bottom": 33.522217 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 2, "textStyle": { "fontName": "Source Sans Pro", "fontStyleName": "Black Italic", "size": 111, "fontPostScriptName": "SourceSansPro-BlackIt", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 2, "paragraphStyle": { "align": "center", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 8, "index": 5, "type": "textLayer", "name": "6", "bounds": { "top": 721, "left": 76, "bottom": 768, "right": 112 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "6", "textClickPoint": { "horizontal": { "value": 8.47435, "units": "percentUnit" }, "vertical": { "value": 77.607727, "units": "percentUnit" } }, "boundingBox": { "left": -10.933105, "top": -73.720901, "right": 23.848175, "bottom": -28.062515 }, "bounds": { "left": -14.089355, "top": -92.130203, "right": 28.644493, "bottom": 45.288528 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 2, "textStyle": { "fontName": "Source Sans Pro", "fontStyleName": "Black", "size": 111, "fontPostScriptName": "SourceSansPro-Black", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 2, "paragraphStyle": { "align": "center", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 7, "index": 4, "type": "textLayer", "name": "5", "bounds": { "top": 597, "left": 76, "bottom": 643, "right": 111 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "5", "textClickPoint": { "horizontal": { "value": 8.47435, "units": "percentUnit" }, "vertical": { "value": 65.400696, "units": "percentUnit" } }, "boundingBox": { "left": -10.410049, "top": -72.88739, "right": 24.015182, "bottom": -28.062515 }, "bounds": { "left": -13.867432, "top": -92.130203, "right": 28.422661, "bottom": 42.624298 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 2, "textStyle": { "fontName": "Source Sans Pro", "fontStyleName": "Bold", "size": 111, "fontPostScriptName": "SourceSansPro-Bold", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 2, "paragraphStyle": { "align": "center", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 6, "index": 3, "type": "textLayer", "name": "4", "bounds": { "top": 466, "left": 77, "bottom": 510, "right": 113 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "4", "textClickPoint": { "horizontal": { "value": 8.47435, "units": "percentUnit" }, "vertical": { "value": 52.607727, "units": "percentUnit" } }, "boundingBox": { "left": -9.356903, "top": -73.070053, "right": 25.635834, "bottom": -29.611984 }, "bounds": { "left": -13.645508, "top": -92.130203, "right": 28.200829, "bottom": 39.294434 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 2, "textStyle": { "fontName": "Source Sans Pro", "fontStyleName": "Semibold", "size": 111, "fontPostScriptName": "SourceSansPro-Semibold", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 2, "paragraphStyle": { "align": "center", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 5, "index": 2, "type": "textLayer", "name": "3", "bounds": { "top": 339, "left": 77, "bottom": 386, "right": 109 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "3", "textClickPoint": { "horizontal": { "value": 8.47435, "units": "percentUnit" }, "vertical": { "value": 40.400696, "units": "percentUnit" } }, "boundingBox": { "left": -9.723495, "top": -74.013489, "right": 21.569855, "bottom": -28.156265 }, "bounds": { "left": -13.367676, "top": -92.130203, "right": 27.923119, "bottom": 35.852783 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 2, "textStyle": { "fontName": "Source Sans Pro", "fontStyleName": "Regular", "size": 111, "fontPostScriptName": "SourceSansPro-Regular", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 2, "paragraphStyle": { "align": "center", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 2, "index": 1, "type": "textLayer", "name": "2", "bounds": { "top": 211, "left": 79, "bottom": 257, "right": 109 }, "visible": true, "clipped": false, "generatorSettings": false, "text": { "textKey": "2", "textClickPoint": { "horizontal": { "value": 8.47435, "units": "percentUnit" }, "vertical": { "value": 27.900696, "units": "percentUnit" } }, "boundingBox": { "left": -7.448776, "top": -74.000046, "right": 21.399536, "bottom": -30.113144 }, "bounds": { "left": -13.09082, "top": -92.130203, "right": 27.646126, "bottom": 31.857285 }, "textShape": [ { "char": "paint", "orientation": "horizontal", "transform": { "xx": 1, "xy": 0, "yx": 0, "yy": 1, "tx": 0, "ty": 0 }, "rowCount": 1, "columnCount": 1, "rowMajorOrder": true, "rowGutter": 0, "columnGutter": 0, "spacing": 0, "frameBaselineAlignment": "alignByAscent", "firstBaselineMinimum": 0, "base": { "horizontal": 0, "vertical": 0 } } ], "antiAlias": "antiAliasPlatformGray", "textGridding": "none", "textStyleRange": [ { "from": 0, "to": 2, "textStyle": { "fontName": "Source Sans Pro", "fontStyleName": "Light", "size": 111, "fontPostScriptName": "SourceSansPro-Light", "autoLeading": false, "altligature": true, "fractions": true, "stylisticAlternates": true, "baselineDirection": "withStream", "textLanguage": "russianLanguage", "japaneseAlternate": "defaultForm", "contextualLigatures": true, "digitSet": "arabicDigits", "markYDistFromBaseline": 0, "leading": 111, "tracking": 5 } } ], "paragraphStyleRange": [ { "from": 0, "to": 2, "paragraphStyle": { "align": "center", "firstLineIndent": 7, "startIndent": 5, "endIndent": 6, "spaceBefore": 8, "spaceAfter": 9, "impliedFirstLineIndent": 7, "impliedStartIndent": 5, "impliedEndIndent": 6, "impliedSpaceBefore": 8, "impliedSpaceAfter": 9 } } ] } }, { "id": 1, "index": 0, "type": "backgroundLayer", "name": "Background", "protection": { "transparency": true, "position": true }, "bounds": { "top": 0, "left": 0, "bottom": 1024, "right": 1024 }, "visible": true, "clipped": false, "pixels": true, "generatorSettings": false } ] }
adobe-research/svgObjectModelGenerator
tests/data/text-styling2-data.js
JavaScript
apache-2.0
45,623
/*var article=require('./request/article.js'); console.log(article);*/ /** * 导出所有模块需要用到接口 * 一级属性:模块名 * 一级属性中的方法:当前模块需要用的接口 * @type {Object} */ var request=[{ module:'user', name:'用户管理', list:require('./request/user.js') },{ module:'article', name:'文章管理', list:require('./request/article.js') },{ module:'order', name:'订单管理', list:require('./request/order.js') },{ module:'system', name:'系统设置', list:require('./request/system.js') },{ module:'open', name:'第三方接入', list:require('./request/open.js') }]; module.exports=request;
liliangali/qudao
vue2/src/config/request.js
JavaScript
apache-2.0
669
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A DragListGroup is a class representing a group of one or more * "drag lists" with items that can be dragged within them and between them. * * @see ../demos/draglistgroup.html */ goog.provide('goog.fx.DragListDirection'); goog.provide('goog.fx.DragListGroup'); goog.provide('goog.fx.DragListGroup.EventType'); goog.provide('goog.fx.DragListGroupEvent'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.classlist'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.fx.Dragger'); goog.require('goog.math.Coordinate'); goog.require('goog.string'); goog.require('goog.style'); /** * A class representing a group of one or more "drag lists" with items that can * be dragged within them and between them. * * Example usage: * var dragListGroup = new goog.fx.DragListGroup(); * dragListGroup.setDragItemHandleHoverClass(className1, className2); * dragListGroup.setDraggerElClass(className3); * dragListGroup.addDragList(vertList, goog.fx.DragListDirection.DOWN); * dragListGroup.addDragList(horizList, goog.fx.DragListDirection.RIGHT); * dragListGroup.init(); * * @extends {goog.events.EventTarget} * @constructor */ goog.fx.DragListGroup = function() { goog.events.EventTarget.call(this); /** * The drag lists. * @type {Array.<Element>} * @private */ this.dragLists_ = []; /** * All the drag items. Set by init(). * @type {Array.<Element>} * @private */ this.dragItems_ = []; /** * Which drag item corresponds to a given handle. Set by init(). * Specifically, this maps from the unique ID (as given by goog.getUid) * of the handle to the drag item. * @type {Object} * @private */ this.dragItemForHandle_ = {}; /** * The event handler for this instance. * @type {goog.events.EventHandler.<!goog.fx.DragListGroup>} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); /** * Whether the setup has been done to make all items in all lists draggable. * @type {boolean} * @private */ this.isInitialized_ = false; /** * Whether the currDragItem is always displayed. By default the list * collapses, the currDragItem's display is set to none, when we do not * hover over a draglist. * @type {boolean} * @private */ this.isCurrDragItemAlwaysDisplayed_ = false; /** * Whether to update the position of the currDragItem as we drag, i.e., * insert the currDragItem each time to the position where it would land if * we were to end the drag at that point. Defaults to true. * @type {boolean} * @private */ this.updateWhileDragging_ = true; }; goog.inherits(goog.fx.DragListGroup, goog.events.EventTarget); /** * Enum to indicate the direction that a drag list grows. * @enum {number} */ goog.fx.DragListDirection = { DOWN: 0, // common RIGHT: 2, // common LEFT: 3, // uncommon (except perhaps for right-to-left interfaces) RIGHT_2D: 4, // common + handles multiple lines if items are wrapped LEFT_2D: 5 // for rtl languages }; /** * Events dispatched by this class. * @type {Object} */ goog.fx.DragListGroup.EventType = { BEFOREDRAGSTART: 'beforedragstart', DRAGSTART: 'dragstart', BEFOREDRAGMOVE: 'beforedragmove', DRAGMOVE: 'dragmove', BEFOREDRAGEND: 'beforedragend', DRAGEND: 'dragend' }; // The next 4 are user-supplied CSS classes. /** * The user-supplied CSS classes to add to a drag item on hover (not during a * drag action). * @type {Array|undefined} * @private */ goog.fx.DragListGroup.prototype.dragItemHoverClasses_; /** * The user-supplied CSS classes to add to a drag item handle on hover (not * during a drag action). * @type {Array|undefined} * @private */ goog.fx.DragListGroup.prototype.dragItemHandleHoverClasses_; /** * The user-supplied CSS classes to add to the current drag item (during a drag * action). * @type {Array|undefined} * @private */ goog.fx.DragListGroup.prototype.currDragItemClasses_; /** * The user-supplied CSS classes to add to the clone of the current drag item * that's actually being dragged around (during a drag action). * @type {Array.<string>|undefined} * @private */ goog.fx.DragListGroup.prototype.draggerElClasses_; // The next 5 are info applicable during a drag action. /** * The current drag item being moved. * Note: This is only defined while a drag action is happening. * @type {Element} * @private */ goog.fx.DragListGroup.prototype.currDragItem_; /** * The drag list that {@code this.currDragItem_} is currently hovering over, or * null if it is not hovering over a list. * @type {Element} * @private */ goog.fx.DragListGroup.prototype.currHoverList_; /** * The original drag list that the current drag item came from. We need to * remember this in case the user drops the item outside of any lists, in which * case we return the item to its original location. * Note: This is only defined while a drag action is happening. * @type {Element} * @private */ goog.fx.DragListGroup.prototype.origList_; /** * The original next item in the original list that the current drag item came * from. We need to remember this in case the user drops the item outside of * any lists, in which case we return the item to its original location. * Note: This is only defined while a drag action is happening. * @type {Element} * @private */ goog.fx.DragListGroup.prototype.origNextItem_; /** * The current item in the list we are hovering over. We need to remember * this in case we do not update the position of the current drag item while * dragging (see {@code updateWhileDragging_}). In this case the current drag * item will be inserted into the list before this element when the drag ends. * @type {Element} * @private */ goog.fx.DragListGroup.prototype.currHoverItem_; /** * The clone of the current drag item that's actually being dragged around. * Note: This is only defined while a drag action is happening. * @type {Element} * @private */ goog.fx.DragListGroup.prototype.draggerEl_; /** * The dragger object. * Note: This is only defined while a drag action is happening. * @type {goog.fx.Dragger} * @private */ goog.fx.DragListGroup.prototype.dragger_; /** * The amount of distance, in pixels, after which a mousedown or touchstart is * considered a drag. * @type {number} * @private */ goog.fx.DragListGroup.prototype.hysteresisDistance_ = 0; /** * Sets the property of the currDragItem that it is always displayed in the * list. */ goog.fx.DragListGroup.prototype.setIsCurrDragItemAlwaysDisplayed = function() { this.isCurrDragItemAlwaysDisplayed_ = true; }; /** * Sets the private property updateWhileDragging_ to false. This disables the * update of the position of the currDragItem while dragging. It will only be * placed to its new location once the drag ends. */ goog.fx.DragListGroup.prototype.setNoUpdateWhileDragging = function() { this.updateWhileDragging_ = false; }; /** * Sets the distance the user has to drag the element before a drag operation * is started. * @param {number} distance The number of pixels after which a mousedown and * move is considered a drag. */ goog.fx.DragListGroup.prototype.setHysteresis = function(distance) { this.hysteresisDistance_ = distance; }; /** * @return {number} distance The number of pixels after which a mousedown and * move is considered a drag. */ goog.fx.DragListGroup.prototype.getHysteresis = function() { return this.hysteresisDistance_; }; /** * Adds a drag list to this DragListGroup. * All calls to this method must happen before the call to init(). * Remember that all child nodes (except text nodes) will be made draggable to * any other drag list in this group. * * @param {Element} dragListElement Must be a container for a list of items * that should all be made draggable. * @param {goog.fx.DragListDirection} growthDirection The direction that this * drag list grows in (i.e. if an item is appended to the DOM, the list's * bounding box expands in this direction). * @param {boolean=} opt_unused Unused argument. * @param {string=} opt_dragHoverClass CSS class to apply to this drag list when * the draggerEl hovers over it during a drag action. If present, must be a * single, valid classname (not a string of space-separated classnames). */ goog.fx.DragListGroup.prototype.addDragList = function( dragListElement, growthDirection, opt_unused, opt_dragHoverClass) { goog.asserts.assert(!this.isInitialized_); dragListElement.dlgGrowthDirection_ = growthDirection; dragListElement.dlgDragHoverClass_ = opt_dragHoverClass; this.dragLists_.push(dragListElement); }; /** * Sets a user-supplied function used to get the "handle" element for a drag * item. The function must accept exactly one argument. The argument may be * any drag item element. * * If not set, the default implementation uses the whole drag item as the * handle. * * @param {function(Element): Element} getHandleForDragItemFn A function that, * given any drag item, returns a reference to its "handle" element * (which may be the drag item element itself). */ goog.fx.DragListGroup.prototype.setFunctionToGetHandleForDragItem = function( getHandleForDragItemFn) { goog.asserts.assert(!this.isInitialized_); this.getHandleForDragItem_ = getHandleForDragItemFn; }; /** * Sets a user-supplied CSS class to add to a drag item on hover (not during a * drag action). * @param {...!string} var_args The CSS class or classes. */ goog.fx.DragListGroup.prototype.setDragItemHoverClass = function(var_args) { goog.asserts.assert(!this.isInitialized_); this.dragItemHoverClasses_ = goog.array.slice(arguments, 0); }; /** * Sets a user-supplied CSS class to add to a drag item handle on hover (not * during a drag action). * @param {...!string} var_args The CSS class or classes. */ goog.fx.DragListGroup.prototype.setDragItemHandleHoverClass = function( var_args) { goog.asserts.assert(!this.isInitialized_); this.dragItemHandleHoverClasses_ = goog.array.slice(arguments, 0); }; /** * Sets a user-supplied CSS class to add to the current drag item (during a * drag action). * * If not set, the default behavior adds visibility:hidden to the current drag * item so that it is a block of empty space in the hover drag list (if any). * If this class is set by the user, then the default behavior does not happen * (unless, of course, the class also contains visibility:hidden). * * @param {...!string} var_args The CSS class or classes. */ goog.fx.DragListGroup.prototype.setCurrDragItemClass = function(var_args) { goog.asserts.assert(!this.isInitialized_); this.currDragItemClasses_ = goog.array.slice(arguments, 0); }; /** * Sets a user-supplied CSS class to add to the clone of the current drag item * that's actually being dragged around (during a drag action). * @param {string} draggerElClass The CSS class. */ goog.fx.DragListGroup.prototype.setDraggerElClass = function(draggerElClass) { goog.asserts.assert(!this.isInitialized_); // Split space-separated classes up into an array. this.draggerElClasses_ = goog.string.trim(draggerElClass).split(' '); }; /** * Performs the initial setup to make all items in all lists draggable. */ goog.fx.DragListGroup.prototype.init = function() { if (this.isInitialized_) { return; } for (var i = 0, numLists = this.dragLists_.length; i < numLists; i++) { var dragList = this.dragLists_[i]; var dragItems = goog.dom.getChildren(dragList); for (var j = 0, numItems = dragItems.length; j < numItems; ++j) { this.listenForDragEvents(dragItems[j]); } } this.isInitialized_ = true; }; /** * Adds a single item to the given drag list and sets up the drag listeners for * it. * If opt_index is specified the item is inserted at this index, otherwise the * item is added as the last child of the list. * * @param {!Element} list The drag list where to add item to. * @param {!Element} item The new element to add. * @param {number=} opt_index Index where to insert the item in the list. If not * specified item is inserted as the last child of list. */ goog.fx.DragListGroup.prototype.addItemToDragList = function(list, item, opt_index) { if (goog.isDef(opt_index)) { goog.dom.insertChildAt(list, item, opt_index); } else { goog.dom.appendChild(list, item); } this.listenForDragEvents(item); }; /** @override */ goog.fx.DragListGroup.prototype.disposeInternal = function() { this.eventHandler_.dispose(); for (var i = 0, n = this.dragLists_.length; i < n; i++) { var dragList = this.dragLists_[i]; // Note: IE doesn't allow 'delete' for fields on HTML elements (because // they're not real JS objects in IE), so we just set them to undefined. dragList.dlgGrowthDirection_ = undefined; dragList.dlgDragHoverClass_ = undefined; } this.dragLists_.length = 0; this.dragItems_.length = 0; this.dragItemForHandle_ = null; // In the case where a drag event is currently in-progress and dispose is // called, this cleans up the extra state. this.cleanupDragDom_(); goog.fx.DragListGroup.superClass_.disposeInternal.call(this); }; /** * Caches the heights of each drag list and drag item, except for the current * drag item. * * @param {Element} currDragItem The item currently being dragged. * @private */ goog.fx.DragListGroup.prototype.recacheListAndItemBounds_ = function( currDragItem) { for (var i = 0, n = this.dragLists_.length; i < n; i++) { var dragList = this.dragLists_[i]; dragList.dlgBounds_ = goog.style.getBounds(dragList); } for (var i = 0, n = this.dragItems_.length; i < n; i++) { var dragItem = this.dragItems_[i]; if (dragItem != currDragItem) { dragItem.dlgBounds_ = goog.style.getBounds(dragItem); } } }; /** * Listens for drag events on the given drag item. This method is currently used * to initialize drag items. * * @param {Element} dragItem the element to initialize. This element has to be * in one of the drag lists. * @protected */ goog.fx.DragListGroup.prototype.listenForDragEvents = function(dragItem) { var dragItemHandle = this.getHandleForDragItem_(dragItem); var uid = goog.getUid(dragItemHandle); this.dragItemForHandle_[uid] = dragItem; if (this.dragItemHoverClasses_) { this.eventHandler_.listen( dragItem, goog.events.EventType.MOUSEOVER, this.handleDragItemMouseover_); this.eventHandler_.listen( dragItem, goog.events.EventType.MOUSEOUT, this.handleDragItemMouseout_); } if (this.dragItemHandleHoverClasses_) { this.eventHandler_.listen( dragItemHandle, goog.events.EventType.MOUSEOVER, this.handleDragItemHandleMouseover_); this.eventHandler_.listen( dragItemHandle, goog.events.EventType.MOUSEOUT, this.handleDragItemHandleMouseout_); } this.dragItems_.push(dragItem); this.eventHandler_.listen(dragItemHandle, [goog.events.EventType.MOUSEDOWN, goog.events.EventType.TOUCHSTART], this.handlePotentialDragStart_); }; /** * Handles mouse and touch events which may start a drag action. * @param {!goog.events.BrowserEvent} e MOUSEDOWN or TOUCHSTART event. * @private */ goog.fx.DragListGroup.prototype.handlePotentialDragStart_ = function(e) { var uid = goog.getUid(/** @type {Node} */ (e.currentTarget)); this.currDragItem_ = /** @type {Element} */ (this.dragItemForHandle_[uid]); this.draggerEl_ = this.createDragElementInternal(this.currDragItem_); if (this.draggerElClasses_) { // Add CSS class for the clone, if any. goog.dom.classlist.addAll( goog.asserts.assert(this.draggerEl_), this.draggerElClasses_ || []); } // Place the clone (i.e. draggerEl) at the same position as the actual // current drag item. This is a bit tricky since // goog.style.getPageOffset() gets the left-top pos of the border, but // goog.style.setPageOffset() sets the left-top pos of the margin. // It's difficult to adjust for the margins of the clone because it's // difficult to read it: goog.style.getComputedStyle() doesn't work for IE. // Instead, our workaround is simply to set the clone's margins to 0px. this.draggerEl_.style.margin = '0'; this.draggerEl_.style.position = 'absolute'; this.draggerEl_.style.visibility = 'hidden'; var doc = goog.dom.getOwnerDocument(this.currDragItem_); doc.body.appendChild(this.draggerEl_); // Important: goog.style.setPageOffset() only works correctly for IE when the // element is already in the document. var currDragItemPos = goog.style.getPageOffset(this.currDragItem_); goog.style.setPageOffset(this.draggerEl_, currDragItemPos); this.dragger_ = new goog.fx.Dragger(this.draggerEl_); this.dragger_.setHysteresis(this.hysteresisDistance_); // Listen to events on the dragger. These handlers will be unregistered at // DRAGEND, when the dragger is disposed of. We can't use eventHandler_, // because it creates new references to the handler functions at each // dragging action, and keeps them until DragListGroup is disposed of. goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.START, this.handleDragStart_, false, this); goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.END, this.handleDragEnd_, false, this); goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.EARLY_CANCEL, this.cleanup_, false, this); this.dragger_.startDrag(e); }; /** * Creates copy of node being dragged. * * @param {Element} sourceEl Element to copy. * @return {Element} The clone of {@code sourceEl}. * @deprecated Use goog.fx.Dragger.cloneNode(). * @private */ goog.fx.DragListGroup.prototype.cloneNode_ = function(sourceEl) { return goog.fx.Dragger.cloneNode(sourceEl); }; /** * Generates an element to follow the cursor during dragging, given a drag * source element. The default behavior is simply to clone the source element, * but this may be overridden in subclasses. This method is called by * {@code createDragElement()} before the drag class is added. * * @param {Element} sourceEl Drag source element. * @return {Element} The new drag element. * @protected * @suppress {deprecated} */ goog.fx.DragListGroup.prototype.createDragElementInternal = function(sourceEl) { return this.cloneNode_(sourceEl); }; /** * Handles the start of a drag action. * @param {!goog.fx.DragEvent} e goog.fx.Dragger.EventType.START event. * @private */ goog.fx.DragListGroup.prototype.handleDragStart_ = function(e) { if (!this.dispatchEvent(new goog.fx.DragListGroupEvent( goog.fx.DragListGroup.EventType.BEFOREDRAGSTART, this, e.browserEvent, this.currDragItem_, null, null))) { e.preventDefault(); this.cleanup_(); return; } // Record the original location of the current drag item. // Note: this.origNextItem_ may be null. this.origList_ = /** @type {Element} */ (this.currDragItem_.parentNode); this.origNextItem_ = goog.dom.getNextElementSibling(this.currDragItem_); this.currHoverItem_ = this.origNextItem_; this.currHoverList_ = this.origList_; // If there's a CSS class specified for the current drag item, add it. // Otherwise, make the actual current drag item hidden (takes up space). if (this.currDragItemClasses_) { goog.dom.classlist.addAll( goog.asserts.assert(this.currDragItem_), this.currDragItemClasses_ || []); } else { this.currDragItem_.style.visibility = 'hidden'; } // Precompute distances from top-left corner to center for efficiency. var draggerElSize = goog.style.getSize(this.draggerEl_); this.draggerEl_.halfWidth = draggerElSize.width / 2; this.draggerEl_.halfHeight = draggerElSize.height / 2; this.draggerEl_.style.visibility = ''; // Record the bounds of all the drag lists and all the other drag items. This // caching is for efficiency, so that we don't have to recompute the bounds on // each drag move. Do this in the state where the current drag item is not in // any of the lists, except when update while dragging is disabled, as in this // case the current drag item does not get removed until drag ends. if (this.updateWhileDragging_) { this.currDragItem_.style.display = 'none'; } this.recacheListAndItemBounds_(this.currDragItem_); this.currDragItem_.style.display = ''; // Listen to events on the dragger. goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.DRAG, this.handleDragMove_, false, this); this.dispatchEvent( new goog.fx.DragListGroupEvent( goog.fx.DragListGroup.EventType.DRAGSTART, this, e.browserEvent, this.currDragItem_, this.draggerEl_, this.dragger_)); }; /** * Handles a drag movement (i.e. DRAG event fired by the dragger). * * @param {goog.fx.DragEvent} dragEvent Event object fired by the dragger. * @return {boolean} The return value for the event. * @private */ goog.fx.DragListGroup.prototype.handleDragMove_ = function(dragEvent) { // Compute the center of the dragger element (i.e. the cloned drag item). var draggerElPos = goog.style.getPageOffset(this.draggerEl_); var draggerElCenter = new goog.math.Coordinate( draggerElPos.x + this.draggerEl_.halfWidth, draggerElPos.y + this.draggerEl_.halfHeight); // Check whether the center is hovering over one of the drag lists. var hoverList = this.getHoverDragList_(draggerElCenter); // If hovering over a list, find the next item (if drag were to end now). var hoverNextItem = hoverList ? this.getHoverNextItem_(hoverList, draggerElCenter) : null; var rv = this.dispatchEvent( new goog.fx.DragListGroupEvent( goog.fx.DragListGroup.EventType.BEFOREDRAGMOVE, this, dragEvent, this.currDragItem_, this.draggerEl_, this.dragger_, draggerElCenter, hoverList, hoverNextItem)); if (!rv) { return false; } if (hoverList) { if (this.updateWhileDragging_) { this.insertCurrDragItem_(hoverList, hoverNextItem); } else { // If update while dragging is disabled do not insert // the dragged item, but update the hovered item instead. this.updateCurrHoverItem(hoverNextItem, draggerElCenter); } this.currDragItem_.style.display = ''; // Add drag list's hover class (if any). if (hoverList.dlgDragHoverClass_) { goog.dom.classlist.add( goog.asserts.assert(hoverList), hoverList.dlgDragHoverClass_); } } else { // Not hovering over a drag list, so remove the item altogether unless // specified otherwise by the user. if (!this.isCurrDragItemAlwaysDisplayed_) { this.currDragItem_.style.display = 'none'; } // Remove hover classes (if any) from all drag lists. for (var i = 0, n = this.dragLists_.length; i < n; i++) { var dragList = this.dragLists_[i]; if (dragList.dlgDragHoverClass_) { goog.dom.classlist.remove( goog.asserts.assert(dragList), dragList.dlgDragHoverClass_); } } } // If the current hover list is different than the last, the lists may have // shrunk, so we should recache the bounds. if (hoverList != this.currHoverList_) { this.currHoverList_ = hoverList; this.recacheListAndItemBounds_(this.currDragItem_); } this.dispatchEvent( new goog.fx.DragListGroupEvent( goog.fx.DragListGroup.EventType.DRAGMOVE, this, dragEvent, /** @type {Element} */ (this.currDragItem_), this.draggerEl_, this.dragger_, draggerElCenter, hoverList, hoverNextItem)); // Return false to prevent selection due to mouse drag. return false; }; /** * Clear all our temporary fields that are only defined while dragging, and * all the bounds info stored on the drag lists and drag elements. * @param {!goog.events.Event=} opt_e EARLY_CANCEL event from the dragger if * cleanup_ was called as an event handler. * @private */ goog.fx.DragListGroup.prototype.cleanup_ = function(opt_e) { this.cleanupDragDom_(); this.currDragItem_ = null; this.currHoverList_ = null; this.origList_ = null; this.origNextItem_ = null; this.draggerEl_ = null; this.dragger_ = null; // Note: IE doesn't allow 'delete' for fields on HTML elements (because // they're not real JS objects in IE), so we just set them to null. for (var i = 0, n = this.dragLists_.length; i < n; i++) { this.dragLists_[i].dlgBounds_ = null; } for (var i = 0, n = this.dragItems_.length; i < n; i++) { this.dragItems_[i].dlgBounds_ = null; } }; /** * Handles the end or the cancellation of a drag action, i.e. END or CLEANUP * event fired by the dragger. * * @param {!goog.fx.DragEvent} dragEvent Event object fired by the dragger. * @return {boolean} Whether the event was handled. * @private */ goog.fx.DragListGroup.prototype.handleDragEnd_ = function(dragEvent) { var rv = this.dispatchEvent( new goog.fx.DragListGroupEvent( goog.fx.DragListGroup.EventType.BEFOREDRAGEND, this, dragEvent, /** @type {Element} */ (this.currDragItem_), this.draggerEl_, this.dragger_)); if (!rv) { return false; } // If update while dragging is disabled insert the current drag item into // its intended location. if (!this.updateWhileDragging_) { this.insertCurrHoverItem(); } // The DRAGEND handler may need the new order of the list items. Clean up the // garbage. // TODO(user): Regression test. this.cleanupDragDom_(); this.dispatchEvent( new goog.fx.DragListGroupEvent( goog.fx.DragListGroup.EventType.DRAGEND, this, dragEvent, this.currDragItem_, this.draggerEl_, this.dragger_)); this.cleanup_(); return true; }; /** * Cleans up DOM changes that are made by the {@code handleDrag*} methods. * @private */ goog.fx.DragListGroup.prototype.cleanupDragDom_ = function() { // Disposes of the dragger and remove the cloned drag item. goog.dispose(this.dragger_); if (this.draggerEl_) { goog.dom.removeNode(this.draggerEl_); } // If the current drag item is not in any list, put it back in its original // location. if (this.currDragItem_ && this.currDragItem_.style.display == 'none') { // Note: this.origNextItem_ may be null, but insertBefore() still works. this.origList_.insertBefore(this.currDragItem_, this.origNextItem_); this.currDragItem_.style.display = ''; } // If there's a CSS class specified for the current drag item, remove it. // Otherwise, make the current drag item visible (instead of empty space). if (this.currDragItemClasses_ && this.currDragItem_) { goog.dom.classlist.removeAll( goog.asserts.assert(this.currDragItem_), this.currDragItemClasses_ || []); } else if (this.currDragItem_) { this.currDragItem_.style.visibility = 'visible'; } // Remove hover classes (if any) from all drag lists. for (var i = 0, n = this.dragLists_.length; i < n; i++) { var dragList = this.dragLists_[i]; if (dragList.dlgDragHoverClass_) { goog.dom.classlist.remove( goog.asserts.assert(dragList), dragList.dlgDragHoverClass_); } } }; /** * Default implementation of the function to get the "handle" element for a * drag item. By default, we use the whole drag item as the handle. Users can * change this by calling setFunctionToGetHandleForDragItem(). * * @param {Element} dragItem The drag item to get the handle for. * @return {Element} The dragItem element itself. * @private */ goog.fx.DragListGroup.prototype.getHandleForDragItem_ = function(dragItem) { return dragItem; }; /** * Handles a MOUSEOVER event fired on a drag item. * @param {goog.events.BrowserEvent} e The event. * @private */ goog.fx.DragListGroup.prototype.handleDragItemMouseover_ = function(e) { var targetEl = goog.asserts.assertElement(e.currentTarget); goog.dom.classlist.addAll(targetEl, this.dragItemHoverClasses_ || []); }; /** * Handles a MOUSEOUT event fired on a drag item. * @param {goog.events.BrowserEvent} e The event. * @private */ goog.fx.DragListGroup.prototype.handleDragItemMouseout_ = function(e) { var targetEl = goog.asserts.assertElement(e.currentTarget); goog.dom.classlist.removeAll(targetEl, this.dragItemHoverClasses_ || []); }; /** * Handles a MOUSEOVER event fired on the handle element of a drag item. * @param {goog.events.BrowserEvent} e The event. * @private */ goog.fx.DragListGroup.prototype.handleDragItemHandleMouseover_ = function(e) { var targetEl = goog.asserts.assertElement(e.currentTarget); goog.dom.classlist.addAll(targetEl, this.dragItemHandleHoverClasses_ || []); }; /** * Handles a MOUSEOUT event fired on the handle element of a drag item. * @param {goog.events.BrowserEvent} e The event. * @private */ goog.fx.DragListGroup.prototype.handleDragItemHandleMouseout_ = function(e) { var targetEl = goog.asserts.assertElement(e.currentTarget); goog.dom.classlist.removeAll(targetEl, this.dragItemHandleHoverClasses_ || []); }; /** * Helper for handleDragMove_(). * Given the position of the center of the dragger element, figures out whether * it's currently hovering over any of the drag lists. * * @param {goog.math.Coordinate} draggerElCenter The center position of the * dragger element. * @return {Element} If currently hovering over a drag list, returns the drag * list element. Else returns null. * @private */ goog.fx.DragListGroup.prototype.getHoverDragList_ = function(draggerElCenter) { // If the current drag item was in a list last time we did this, then check // that same list first. var prevHoverList = null; if (this.currDragItem_.style.display != 'none') { prevHoverList = /** @type {Element} */ (this.currDragItem_.parentNode); // Important: We can't use the cached bounds for this list because the // cached bounds are based on the case where the current drag item is not // in the list. Since the current drag item is known to be in this list, we // must recompute the list's bounds. var prevHoverListBounds = goog.style.getBounds(prevHoverList); if (this.isInRect_(draggerElCenter, prevHoverListBounds)) { return prevHoverList; } } for (var i = 0, n = this.dragLists_.length; i < n; i++) { var dragList = this.dragLists_[i]; if (dragList == prevHoverList) { continue; } if (this.isInRect_(draggerElCenter, dragList.dlgBounds_)) { return dragList; } } return null; }; /** * Checks whether a coordinate position resides inside a rectangle. * @param {goog.math.Coordinate} pos The coordinate position. * @param {goog.math.Rect} rect The rectangle. * @return {boolean} True if 'pos' is within the bounds of 'rect'. * @private */ goog.fx.DragListGroup.prototype.isInRect_ = function(pos, rect) { return pos.x > rect.left && pos.x < rect.left + rect.width && pos.y > rect.top && pos.y < rect.top + rect.height; }; /** * Updates the value of currHoverItem_. * * This method is used for insertion only when updateWhileDragging_ is false. * The below implementation is the basic one. This method can be extended by * a subclass to support changes to hovered item (eg: highlighting). Parametr * opt_draggerElCenter can be used for more sophisticated effects. * * @param {Element} hoverNextItem element of the list that is hovered over. * @param {goog.math.Coordinate=} opt_draggerElCenter current position of * the dragged element. * @protected */ goog.fx.DragListGroup.prototype.updateCurrHoverItem = function( hoverNextItem, opt_draggerElCenter) { if (hoverNextItem) { this.currHoverItem_ = hoverNextItem; } }; /** * Inserts the currently dragged item in its new place. * * This method is used for insertion only when updateWhileDragging_ is false * (otherwise there is no need for that). In the basic implementation * the element is inserted before the currently hovered over item (this can * be changed by overriding the method in subclasses). * * @protected */ goog.fx.DragListGroup.prototype.insertCurrHoverItem = function() { this.origList_.insertBefore(this.currDragItem_, this.currHoverItem_); }; /** * Helper for handleDragMove_(). * Given the position of the center of the dragger element, plus the drag list * that it's currently hovering over, figures out the next drag item in the * list that follows the current position of the dragger element. (I.e. if * the drag action ends right now, it would become the item after the current * drag item.) * * @param {Element} hoverList The drag list that we're hovering over. * @param {goog.math.Coordinate} draggerElCenter The center position of the * dragger element. * @return {Element} Returns the earliest item in the hover list that belongs * after the current position of the dragger element. If all items in the * list should come before the current drag item, then returns null. * @private */ goog.fx.DragListGroup.prototype.getHoverNextItem_ = function( hoverList, draggerElCenter) { if (hoverList == null) { throw Error('getHoverNextItem_ called with null hoverList.'); } // The definition of what it means for the draggerEl to be "before" a given // item in the hover drag list is not always the same. It changes based on // the growth direction of the hover drag list in question. /** @type {number} */ var relevantCoord; var getRelevantBoundFn; var isBeforeFn; var pickClosestRow = false; var distanceToClosestRow = undefined; switch (hoverList.dlgGrowthDirection_) { case goog.fx.DragListDirection.DOWN: // "Before" means draggerElCenter.y is less than item's bottom y-value. relevantCoord = draggerElCenter.y; getRelevantBoundFn = goog.fx.DragListGroup.getBottomBound_; isBeforeFn = goog.fx.DragListGroup.isLessThan_; break; case goog.fx.DragListDirection.RIGHT_2D: pickClosestRow = true; case goog.fx.DragListDirection.RIGHT: // "Before" means draggerElCenter.x is less than item's right x-value. relevantCoord = draggerElCenter.x; getRelevantBoundFn = goog.fx.DragListGroup.getRightBound_; isBeforeFn = goog.fx.DragListGroup.isLessThan_; break; case goog.fx.DragListDirection.LEFT_2D: pickClosestRow = true; case goog.fx.DragListDirection.LEFT: // "Before" means draggerElCenter.x is greater than item's left x-value. relevantCoord = draggerElCenter.x; getRelevantBoundFn = goog.fx.DragListGroup.getLeftBound_; isBeforeFn = goog.fx.DragListGroup.isGreaterThan_; break; } // This holds the earliest drag item found so far that should come after // this.currDragItem_ in the hover drag list (based on draggerElCenter). var earliestAfterItem = null; // This is the position of the relevant bound for the earliestAfterItem, // where "relevant" is determined by the growth direction of hoverList. var earliestAfterItemRelevantBound; var hoverListItems = goog.dom.getChildren(hoverList); for (var i = 0, n = hoverListItems.length; i < n; i++) { var item = hoverListItems[i]; if (item == this.currDragItem_) { continue; } var relevantBound = getRelevantBoundFn(item.dlgBounds_); // When the hoverlist is broken into multiple rows (i.e., in the case of // LEFT_2D and RIGHT_2D) it is no longer enough to only look at the // x-coordinate alone in order to find the {@earliestAfterItem} in the // hoverlist. Make sure it is chosen from the row closest to the // {@code draggerElCenter}. if (pickClosestRow) { var distanceToRow = goog.fx.DragListGroup.verticalDistanceFromItem_(item, draggerElCenter); // Initialize the distance to the closest row to the current value if // undefined. if (!goog.isDef(distanceToClosestRow)) { distanceToClosestRow = distanceToRow; } if (isBeforeFn(relevantCoord, relevantBound) && (earliestAfterItemRelevantBound == undefined || (distanceToRow < distanceToClosestRow) || ((distanceToRow == distanceToClosestRow) && (isBeforeFn(relevantBound, earliestAfterItemRelevantBound) || relevantBound == earliestAfterItemRelevantBound)))) { earliestAfterItem = item; earliestAfterItemRelevantBound = relevantBound; } // Update distance to closest row. if (distanceToRow < distanceToClosestRow) { distanceToClosestRow = distanceToRow; } } else if (isBeforeFn(relevantCoord, relevantBound) && (earliestAfterItemRelevantBound == undefined || isBeforeFn(relevantBound, earliestAfterItemRelevantBound))) { earliestAfterItem = item; earliestAfterItemRelevantBound = relevantBound; } } // If we ended up picking an element that is not in the closest row it can // only happen if we should have picked the last one in which case there is // no consecutive element. if (!goog.isNull(earliestAfterItem) && goog.fx.DragListGroup.verticalDistanceFromItem_( earliestAfterItem, draggerElCenter) > distanceToClosestRow) { return null; } else { return earliestAfterItem; } }; /** * Private helper for getHoverNextItem(). * Given an item and a target determine the vertical distance from the item's * center to the target. * @param {Element} item The item to measure the distance from. * @param {goog.math.Coordinate} target The (x,y) coordinate of the target * to measure the distance to. * @return {number} The vertical distance between the center of the item and * the target. * @private */ goog.fx.DragListGroup.verticalDistanceFromItem_ = function(item, target) { var itemBounds = item.dlgBounds_; var itemCenterY = itemBounds.top + (itemBounds.height - 1) / 2; return Math.abs(target.y - itemCenterY); }; /** * Private helper for getHoverNextItem_(). * Given the bounds of an item, computes the item's bottom y-value. * @param {goog.math.Rect} itemBounds The bounds of the item. * @return {number} The item's bottom y-value. * @private */ goog.fx.DragListGroup.getBottomBound_ = function(itemBounds) { return itemBounds.top + itemBounds.height - 1; }; /** * Private helper for getHoverNextItem_(). * Given the bounds of an item, computes the item's right x-value. * @param {goog.math.Rect} itemBounds The bounds of the item. * @return {number} The item's right x-value. * @private */ goog.fx.DragListGroup.getRightBound_ = function(itemBounds) { return itemBounds.left + itemBounds.width - 1; }; /** * Private helper for getHoverNextItem_(). * Given the bounds of an item, computes the item's left x-value. * @param {goog.math.Rect} itemBounds The bounds of the item. * @return {number} The item's left x-value. * @private */ goog.fx.DragListGroup.getLeftBound_ = function(itemBounds) { return itemBounds.left || 0; }; /** * Private helper for getHoverNextItem_(). * @param {number} a Number to compare. * @param {number} b Number to compare. * @return {boolean} Whether a is less than b. * @private */ goog.fx.DragListGroup.isLessThan_ = function(a, b) { return a < b; }; /** * Private helper for getHoverNextItem_(). * @param {number} a Number to compare. * @param {number} b Number to compare. * @return {boolean} Whether a is greater than b. * @private */ goog.fx.DragListGroup.isGreaterThan_ = function(a, b) { return a > b; }; /** * Inserts the current drag item to the appropriate location in the drag list * that we're hovering over (if the current drag item is not already there). * * @param {Element} hoverList The drag list we're hovering over. * @param {Element} hoverNextItem The next item in the hover drag list. * @private */ goog.fx.DragListGroup.prototype.insertCurrDragItem_ = function( hoverList, hoverNextItem) { if (this.currDragItem_.parentNode != hoverList || goog.dom.getNextElementSibling(this.currDragItem_) != hoverNextItem) { // The current drag item is not in the correct location, so we move it. // Note: hoverNextItem may be null, but insertBefore() still works. hoverList.insertBefore(this.currDragItem_, hoverNextItem); } }; /** * The event object dispatched by DragListGroup. * The fields draggerElCenter, hoverList, and hoverNextItem are only available * for the BEFOREDRAGMOVE and DRAGMOVE events. * * @param {string} type The event type string. * @param {goog.fx.DragListGroup} dragListGroup A reference to the associated * DragListGroup object. * @param {goog.events.BrowserEvent|goog.fx.DragEvent} event The event fired * by the browser or fired by the dragger. * @param {Element} currDragItem The current drag item being moved. * @param {Element} draggerEl The clone of the current drag item that's actually * being dragged around. * @param {goog.fx.Dragger} dragger The dragger object. * @param {goog.math.Coordinate=} opt_draggerElCenter The current center * position of the draggerEl. * @param {Element=} opt_hoverList The current drag list that's being hovered * over, or null if the center of draggerEl is outside of any drag lists. * If not null and the drag action ends right now, then currDragItem will * end up in this list. * @param {Element=} opt_hoverNextItem The current next item in the hoverList * that the draggerEl is hovering over. (I.e. If the drag action ends * right now, then this item would become the next item after the new * location of currDragItem.) May be null if not applicable or if * currDragItem would be added to the end of hoverList. * @constructor * @extends {goog.events.Event} */ goog.fx.DragListGroupEvent = function( type, dragListGroup, event, currDragItem, draggerEl, dragger, opt_draggerElCenter, opt_hoverList, opt_hoverNextItem) { goog.events.Event.call(this, type); /** * A reference to the associated DragListGroup object. * @type {goog.fx.DragListGroup} */ this.dragListGroup = dragListGroup; /** * The event fired by the browser or fired by the dragger. * @type {goog.events.BrowserEvent|goog.fx.DragEvent} */ this.event = event; /** * The current drag item being move. * @type {Element} */ this.currDragItem = currDragItem; /** * The clone of the current drag item that's actually being dragged around. * @type {Element} */ this.draggerEl = draggerEl; /** * The dragger object. * @type {goog.fx.Dragger} */ this.dragger = dragger; /** * The current center position of the draggerEl. * @type {goog.math.Coordinate|undefined} */ this.draggerElCenter = opt_draggerElCenter; /** * The current drag list that's being hovered over, or null if the center of * draggerEl is outside of any drag lists. (I.e. If not null and the drag * action ends right now, then currDragItem will end up in this list.) * @type {Element|undefined} */ this.hoverList = opt_hoverList; /** * The current next item in the hoverList that the draggerEl is hovering over. * (I.e. If the drag action ends right now, then this item would become the * next item after the new location of currDragItem.) May be null if not * applicable or if currDragItem would be added to the end of hoverList. * @type {Element|undefined} */ this.hoverNextItem = opt_hoverNextItem; }; goog.inherits(goog.fx.DragListGroupEvent, goog.events.Event);
nanaze/closure-rhino-fork
closure/goog/fx/draglistgroup.js
JavaScript
apache-2.0
44,356
// Copyright 2017 The Kubernetes Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * Definition object for the component that displays namespace info. * * @return {!angular.Component} */ export const namespaceInfoComponent = { templateUrl: 'namespace/detail/info.html', bindings: { /** {!backendApi.NamespaceDetail} */ 'namespace': '=', }, };
kenan435/dashboard
src/app/frontend/namespace/detail/info_component.js
JavaScript
apache-2.0
883
var quantidade =0; var nomeArtigo; var artigoCategoria = "input:text[name='articleForm:articleCategory_input']"; $(document).ready(function (e) { $('.addArtigo').click(function (e) { e.preventDefault(); $(".modalFrame12 h3").html("Adicionar Novo Artigo"); $(".articleNA").val(""); $(artigoCategoria).val(""); $(".articleNA").attr("disabled", false); $(".articleChangeNameDisabled").val(""); $(".articleChangeNameDisabled").attr("disabled", false); $('.pageModal').fadeIn(); }); $('.addArticle').click(function (e) { e.preventDefault(); if($(".artigoQuantidade").is(':disabled')) { if($(".artigoNome").val() === '') $(".artigoNome").css('border','1px solid red'); if($(artigoCategoria).val() === '') $(artigoCategoria).css('border','1px solid red'); } else { $('.formArtigo [type=text], select, [type=textarea]').each(function () { if($(this).val()==='') $(this).css('border','1px solid red'); }); if($(".artigoObs").val()==='') $(".artigoObs").css("border","1px solid red"); } sendDataArticle(); }); $(".artigoObs").focus(function(e) { $(this).css("border",""); }); $("input, select").focus(function (e) { $(this).css("border", ""); }); }); function articleChangeQuantity(parametro,quantidadeStock) { if(quantidadeStock !=='null') { $(".articleChangeNameDisabled").attr("disabled", false); $(".modalFrame12 h3").html(parametro); $(".articleNA").attr("disabled", true); $('.pageModal').fadeIn(); $('.artigoQuantidade').val(quantidadeStock); quantidade = quantidadeStock; } else { nomeArtigo = $(".artigoNome").val(); $(".modalFrame12 h3").html(parametro); $(".articleChangeNameDisabled").attr("disabled", true); $('.pageModal').fadeIn(); } } function artigoRegistrado() { $('.modalProcess').hide(); $(".articleNA").val(""); $(".articleChangeNameDisabled").val(""); $('.pageModal').fadeOut("slow"); } function nomeArtigoExiste() { $(".artigoNome").focus(); } function changeArticleNameCategory() { var valido = true; if($(".artigoNome").val() === '') valido = false; if($(artigoCategoria).val() === '') valido = false; return valido; } function sendDataArticle() { var valido = true; if($(".artigoQuantidade").is(':disabled')) { if(changeArticleNameCategory() === true) { $('.modalProcess').show(); article([{name:'nome',value:$(".artigoNome").val()}, {name:'categoria',value:$(artigoCategoria).val()}, {name:'quantidade', value:$(".artigoQuantidade").val()}, {name:'funcionario', value:$(".artigoFuncionario").val()}, {name:'fornecedor', value:$(".artigoFornecedor").val()}, {name:'typeOperation', value:"alterar nome do artigo"}, {name:'stockQuantidade', value:quantidade}, {name:'adicionarRemover', value:$(".modalFrame12 h3").html()}, {name:'nomeArtigoAtualizar', value:nomeArtigo}, {name:'obs', value:$(".artigoObs").val()}]); } } else { if($(artigoCategoria).val() === '') valido = false; if($(".artigoObs").val()==='') valido = false; $('.formArtigo [type=text], select').each(function () { if($(this).val()==='') valido = false; }); var nomeD = $(".artigoNome").is(":disabled"); if(valido === true) { $('.modalProcess').show(); article([{name:'nome',value:$(".artigoNome").val()}, {name:'categoria',value:$(artigoCategoria).val()}, {name:'quantidade', value:$(".artigoQuantidade").val()}, {name:'funcionario', value:$(".artigoFuncionario").val()}, {name:'fornecedor', value:$(".artigoFornecedor").val()}, {name:'typeOperation', value:(nomeD===true)? "alterar quantidade" : "novo"}, {name:'stockQuantidade', value:quantidade}, {name:'adicionarRemover', value:$(".modalFrame12 h3").html()}, {name:'obs', value:$(".artigoObs").val()}]); } } } function artigoQuantidadeBorda() { $(".artigoQuantidade").focus(); } function quantidadeArtigoAtual(quantidade) { $(".artigoQuantidade").val(quantidade); }
JIGAsoftSTP/NICON
web/resources/js/Administracao.js
JavaScript
apache-2.0
4,812
/* @flow strict-local */ import format from 'date-fns/format'; import isToday from 'date-fns/is_today'; import isYesterday from 'date-fns/is_yesterday'; import isSameYear from 'date-fns/is_same_year'; import tz from 'timezone/loaded'; export { default as isSameDay } from 'date-fns/is_same_day'; export const shortTime = (date: Date, twentyFourHourTime: boolean = false): string => format(date, twentyFourHourTime ? 'H:mm' : 'h:mm A'); export const shortDate = (date: Date): string => format(date, 'MMM D'); export const longDate = (date: Date): string => format(date, 'MMM D, YYYY'); export const daysInDate = (date: Date): number => Math.trunc(date / 1000 / 60 / 60 / 24); export const humanDate = (date: Date): string => { if (isToday(date)) { return 'Today'; } if (isYesterday(date)) { return 'Yesterday'; } return isSameYear(new Date(date), new Date()) ? shortDate(date) : longDate(date); }; export const nowInTimeZone = (timezone: string): string => tz(tz(new Date()), '%I:%M %p', timezone);
vishwesh3/zulip-mobile
src/utils/date.js
JavaScript
apache-2.0
1,026
import path from 'path'; import fs from 'fs'; import readdirSyncRecursive from 'fs-readdir-recursive'; import outputFileSync from 'output-file-sync'; import child_process from 'child_process'; import test from 'ava'; import rimraf from 'rimraf'; const fixturesPath = path.join(__dirname, 'fixtures', 'commands'); fs.readdirSync(fixturesPath).forEach(testName => { if (testName[0] === '.') return; const [, command, testType] = testName.match(/([^-]+)-(.+)/); test(`${command} command: ${testType}`, async t => { const testPath = path.join(fixturesPath, testName); const tmpPath = path.join(testPath, 'tmp'); createAndChangeToTempDir(tmpPath); // Write files to temporary location Object.entries(readDir(path.join(testPath, 'in-files'))) .forEach(([filename, content]) => outputFileSync(filename, content) ); const { args, stdoutIncludes, stderrIncludes, } = JSON.parse(fs.readFileSync(path.join(testPath, 'options.json'))); const server = child_process.spawn( process.execPath, [ path.join(__dirname, '..', 'bin', 'react-server-cli'), ...args, ] ); let stdout = ''; let stderr = ''; server.stdout.on('data', chunk => stdout += chunk); server.stderr.on('data', chunk => stderr += chunk); const frequency = 100; let elapsed = 0; // Wait for the expected output or the timeout await new Promise(resolve => { const checkForExpectedOutput = setInterval(() => { // Increment the elapsed time if neither stdout nor stderr includes the expected content and the time limit hasn't been reached. if ( ( (stdoutIncludes && !stdout.includes(stdoutIncludes)) || (stderrIncludes && !stderr.includes(stderrIncludes)) ) && elapsed < 5000 ) { elapsed += frequency; return; } clearInterval(checkForExpectedOutput); resolve(); }, frequency); }); t.true(testStdOutput(stderr, stderrIncludes), 'stderr does not include expected output. Instead, it says: ' + stderr); t.true(testStdOutput(stdout, stdoutIncludes), 'stdout does not include expected output. Instead, it says: ' + stdout); server.kill(); // Remove temporary directory after the test rimraf.sync(tmpPath); }); }); //Test the output to stderr or stdout against an approved message. //Ignore messages that start with "Warning:" function testStdOutput(stdOutput, includes) { //Ignore warning messages if (stdOutput.startsWith("Warning:")) { return true; } if (includes && stdOutput.includes(includes)) { return true; } return !stdOutput; } function createAndChangeToTempDir(tmpPath){ if (fs.existsSync(tmpPath)) rimraf.sync(tmpPath); fs.mkdirSync(tmpPath); process.chdir(tmpPath); } function noDotDirectory(x){ return x !== '.'; } function readDir(dirPath){ const files = {}; if (fs.existsSync(dirPath)) { readdirSyncRecursive(dirPath, noDotDirectory).forEach(filename => { files[filename] = fs.readFileSync(path.join(dirPath, filename)); }); } return files; };
lidawang/react-server
packages/react-server-cli/test/commands.js
JavaScript
apache-2.0
2,998
/* global UTILS */ 'use strict'; angular.module('alienUiApp').factory('relationshipTopologyService', ['$q', 'componentService', 'toscaService', function($q, componentService, toscaService) { return { /** * Compute a list of node templates that can be valid targets for a given requirement. * * @param sourceElementName: Name of the node template that is source of the relationship. * @param requirement: The actual requirement for which to find targets. * @param requirementName: The name of the requirement for which to find targets. * @param nodeTemplates: A map of node templates in which to find valid targets for the requirement. * @param nodeTypes: A map of node types that should contains all types used by the previous node templates map. * @param relationshipTypes: A map of relationship types used in the topology. * @param capabilityTypes: A map of relationship types used by nodes in the topology. * @param dependencies: Array of CSAR dependencies in which types should exists. * @param preferedTargetName: Optional name of a prefered target node template that will be placed in prefered field of the result object. */ getTargets: function(sourceElementName, requirement, requirementName, nodeTemplates, nodeTypes, relationshipTypes, capabilityTypes, dependencies, preferedTargetName) { var instance = this; // create a promise as the result may be asynchronous... var deferred = $q.defer(); var requirementDefinition = this.getRequirementDefinition(nodeTypes[nodeTemplates[sourceElementName].type], requirementName); if(UTILS.isDefinedAndNotNull(requirementDefinition.relationshipType)) { var relationshipType = relationshipTypes[requirementDefinition.relationshipType]; if(UTILS.isDefinedAndNotNull(relationshipType)) { deferred.resolve(instance.doGetTargets(sourceElementName, requirement, nodeTemplates, nodeTypes, capabilityTypes, relationshipType, preferedTargetName)); } else { // valid target for the relationship type componentService.getInArchives(requirementDefinition.relationshipType, 'RELATIONSHIP_TYPE', dependencies).success(function(result) { deferred.resolve(instance.doGetTargets(sourceElementName, requirement, nodeTemplates, nodeTypes, capabilityTypes, result.data, preferedTargetName)); }); } } else { deferred.resolve(instance.doGetTargets(sourceElementName, requirement, nodeTemplates, nodeTypes, capabilityTypes, null, preferedTargetName)); } // return the promise. return deferred.promise; }, getRequirementDefinition: function(nodeType, requirementName) { for(var i=0; i<nodeType.requirements.length; i++) { if(nodeType.requirements[i].id === requirementName) { return nodeType.requirements[i]; } } return null; }, doGetTargets: function(sourceElementName, requirement, nodeTemplates, nodeTypes, capabilityTypes, relationshipType, preferedTargetName) { var matches = []; var preferedMatch = null; // valid targets is an array of array, first level elements are all required (AND) while only one of the elements of inner array is required. var validTargets = [[requirement.type]]; if(UTILS.isDefinedAndNotNull(relationshipType) && UTILS.isDefinedAndNotNull(relationshipType.validTargets) && relationshipType.validTargets.length > 0) { validTargets.push(relationshipType.validTargets); } for (var templateName in nodeTemplates) { if (templateName !== sourceElementName && nodeTemplates.hasOwnProperty(templateName)) { var candidate = nodeTemplates[templateName]; // try to match on node type first (if match this means that there is no capacity constraint, we won't be able to match cardinalities on theses relationships). // but that's allowed by TOSCA Simple profile. var match = this.getNodeTarget(validTargets, candidate, nodeTypes); if(match === null) { match = this.getCapabilityTarget(validTargets, candidate, nodeTypes, capabilityTypes); } if(match !== null) { matches.push(match); } if(templateName === preferedTargetName) { preferedMatch = match; } } } return { targets: matches, relationshipType: relationshipType, preferedMatch: preferedMatch }; }, /** * Check if the given node type is a valid candidate based on the validTargets requirements. * * @param validTargets An array of array. First level array contains conditions that must all be matched (AND). Inner array contains type names, one of them must be matched (OR). * @param candidateNodeTypeName Name of the type of the node that is candidate. * @param nodeTypes A map of all available node types (it must contains the candidate node type). */ getNodeTarget: function(validTargets, candidateTemplate, nodeTypes) { var isValid = true; for(var i=0; i<validTargets.length; i++) { isValid = isValid && toscaService.isOneOfType(validTargets[i], candidateTemplate.type, nodeTypes); } if(isValid) { return { template: candidateTemplate, capabilities: [] }; } return null; }, getCapabilityTarget: function(validTargets, candidateTemplate, nodeTypes, capabilityTypes) { var nodeCapabilities = nodeTypes[candidateTemplate.type].capabilities; if(UTILS.isUndefinedOrNull(nodeCapabilities)) { return null; } var match = null; for(var i=0; i<nodeCapabilities.length; i++) { var capabilityId = nodeCapabilities[i].id; if(candidateTemplate.capabilitiesMap[capabilityId].value.canAddRel.yes && this.isValidTarget(validTargets, candidateTemplate.type, i, nodeTypes, capabilityTypes)) { if(match === null) { match = { template: candidateTemplate, capabilities: [] }; } match.capabilities.push({id: capabilityId, type: candidateTemplate.capabilitiesMap[capabilityId].value.type}); } } return match; }, /** * Check if a capability is a valid target. * * @param validTargets An array of array. First level array contains conditions that must all be matched (AND). Inner array contains type names, one of them must be matched (OR). * @param candidateNodeTypeName Name of the type of the node that is candidate. * @param candidateCapabilityIndex Index of the capability of the candidate node that we should check as valid target. * @param nodeTypes A map of all available node types (it must contains the candidate node type). * @param capabilityTypes A map of all available capability types (it must contains the candidate capability type). * @return true if the capability type is one of the valid targets, false if not. */ isValidTarget: function(validTargets, candidateNodeTypeName, candidateCapabilityIndex, nodeTypes, capabilityTypes) { var isValid = true; // we should match all valid targets. for(var i=0; i<validTargets.length; i++) { // One of the validTargets[i] element should be either the capability type or the node type. isValid = isValid && (toscaService.isOneOfType(validTargets[i], candidateNodeTypeName, nodeTypes) || toscaService.isOneOfType(validTargets[i], nodeTypes[candidateNodeTypeName].capabilities[candidateCapabilityIndex].type, capabilityTypes)); } return isValid; } }; } ]);
ngouagna/alien4cloud
alien4cloud-ui/yo/app/scripts/topology/services/relationship_target_matcher_service.js
JavaScript
apache-2.0
7,871
/* global config, $, APP, Strophe, callstats */ var jsSHA = require('jssha'); var io = require('socket.io-client'); var callStats = null; function initCallback (err, msg) { console.log("Initializing Status: err="+err+" msg="+msg); } var CallStats = { init: function (jingleSession) { if(!config.callStatsID || !config.callStatsSecret || callStats !== null) return; callStats = new callstats($, io, jsSHA); this.session = jingleSession; this.peerconnection = jingleSession.peerconnection.peerconnection; this.userID = APP.xmpp.myResource(); var location = window.location; this.confID = location.hostname + location.pathname; //userID is generated or given by the origin server callStats.initialize(config.callStatsID, config.callStatsSecret, this.userID, initCallback); var usage = callStats.fabricUsage.multiplex; callStats.addNewFabric(this.peerconnection, Strophe.getResourceFromJid(jingleSession.peerjid), usage, this.confID, this.pcCallback.bind(this)); }, pcCallback: function (err, msg) { if (!callStats) return; console.log("Monitoring status: "+ err + " msg: " + msg); callStats.sendFabricEvent(this.peerconnection, callStats.fabricEvent.fabricSetup, this.confID); }, sendMuteEvent: function (mute, type) { if (!callStats) return; var event = null; if (type === "video") { event = (mute? callStats.fabricEvent.videoPause : callStats.fabricEvent.videoResume); } else { event = (mute? callStats.fabricEvent.audioMute : callStats.fabricEvent.audioUnmute); } callStats.sendFabricEvent(this.peerconnection, event, this.confID); }, sendTerminateEvent: function () { if(!callStats) { return; } callStats.sendFabricEvent(this.peerconnection, callStats.fabricEvent.fabricTerminated, this.confID); }, sendSetupFailedEvent: function () { if(!callStats) { return; } callStats.sendFabricEvent(this.peerconnection, callStats.fabricEvent.fabricSetupFailed, this.confID); } }; module.exports = CallStats;
gerges/jitsi-meet
modules/statistics/CallStats.js
JavaScript
apache-2.0
2,405
Ext.define('Pku.view.user.Edit',{ extend:'Ext.window.Window', alias:'widget.useredit', title:'编辑用户信息', layout:'fit', autoShow:'true', initComponent:function(){ this.items=[ { xtype:'form', items:[ { xtype:'textfield', name:'name', fieldLabel:'姓名' }, { xtype:'textfield', name:'email', fieldLabel:'邮箱/用户名' } ] } ]; this.buttons=[ { text:'保存', action:'save' }, { text:'取消', scope:this, handler:this.close } ]; this.callParent(arguments); } });
PKUSS/IDP
02.Codes/IPDDEV/src/main/webapp/app/view/user/Edit.js
JavaScript
apache-2.0
616
/*! * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015 * @version 4.1.8 * * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced * features including the FileReader API. * * The plugin drastically enhances the HTML file input to preview multiple files on the client before * upload. In addition it provides the ability to preview content of images, text, videos, audio, html, * flash and other objects. It also offers the ability to upload and delete files using AJAX, and add * files in batches (i.e. preview, append, or remove before upload). * * Author: Kartik Visweswaran * Copyright: 2015, Kartik Visweswaran, Krajee.com * For more JQuery plugins visit http://plugins.krajee.com * For more Yii related demos visit http://demos.krajee.com */ (function ($) { "use strict"; String.prototype.repl = function (from, to) { return this.split(from).join(to); }; var isIE = function (ver) { var div = document.createElement("div"), status; div.innerHTML = "<!--[if IE " + ver + "]><i></i><![endif]-->"; status = (div.getElementsByTagName("i").length === 1); document.body.appendChild(div); div.parentNode.removeChild(div); return status; }, getNum = function(num, def) { def = def || 0; if (typeof num === "number") { return num; } if (typeof num === "string") { num = parseFloat(num); } return isNaN(num) ? def : num; }, hasFileAPISupport = function () { return window.File && window.FileReader; }, hasDragDropSupport = function () { var $div = document.createElement('div'); return !isIE(9) && ($div.draggable !== undefined || ($div.ondragstart !== undefined && $div.ondrop !== undefined)); }, hasFileUploadSupport = function () { return hasFileAPISupport && window.FormData; }, addCss = function ($el, css) { $el.removeClass(css).addClass(css); }, STYLE_SETTING = 'style="width:{width};height:{height};"', OBJECT_PARAMS = ' <param name="controller" value="true" />\n' + ' <param name="allowFullScreen" value="true" />\n' + ' <param name="allowScriptAccess" value="always" />\n' + ' <param name="autoPlay" value="false" />\n' + ' <param name="autoStart" value="false" />\n' + ' <param name="quality" value="high" />\n', DEFAULT_PREVIEW = '<div class="file-preview-other">\n' + ' {previewFileIcon}\n' + ' </div>', defaultFileActionSettings = { removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>', removeClass: 'btn btn-xs btn-default', removeTitle: 'Remove file', uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>', uploadClass: 'btn btn-xs btn-default', uploadTitle: 'Upload file', indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>', indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>', indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>', indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>', indicatorNewTitle: 'Not uploaded yet', indicatorSuccessTitle: 'Uploaded', indicatorErrorTitle: 'Upload Error', indicatorLoadingTitle: 'Uploading ...' }, tMain1 = '{preview}\n' + '<div class="kv-upload-progress hide"></div>\n' + '<div class="input-group {class}">\n' + ' {caption}\n' + ' <div class="input-group-btn">\n' + ' {remove}\n' + ' {cancel}\n' + ' {upload}\n' + ' {browse}\n' + ' </div>\n' + '</div>', tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n', tPreview = '<div class="file-preview {class}">\n' + ' <div class="close fileinput-remove">&times;</div>\n' + ' <div class="{dropClass}">\n' + ' <div class="file-preview-thumbnails">\n' + ' </div>\n' + ' <div class="clearfix"></div>' + ' <div class="file-preview-status text-center text-success"></div>\n' + ' <div class="kv-fileinput-error"></div>\n' + ' </div>\n' + '</div>', tIcon = '<span class="glyphicon glyphicon-file kv-caption-icon"></span>', tCaption = '<div tabindex="-1" class="form-control file-caption {class}">\n' + ' <span class="file-caption-ellipsis">&hellip;</span>\n' + ' <div class="file-caption-name"></div>\n' + '</div>', tModal = '<div id="{id}" class="modal fade">\n' + ' <div class="modal-dialog modal-lg">\n' + ' <div class="modal-content">\n' + ' <div class="modal-header">\n' + ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' + ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' + ' </div>\n' + ' <div class="modal-body">\n' + ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' + ' </div>\n' + ' </div>\n' + ' </div>\n' + '</div>', tProgress = '<div class="progress">\n' + ' <div class="{class}" role="progressbar"' + ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' + ' {percent}%\n' + ' </div>\n' + '</div>', tFooter = '<div class="file-thumbnail-footer">\n' + ' <div class="file-caption-name">{caption}</div>\n' + ' {actions}\n' + '</div>', tActions = '<div class="file-actions">\n' + ' <div class="file-footer-buttons">\n' + ' {upload}{delete}{other}' + ' </div>\n' + ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' + ' <div class="clearfix"></div>\n' + '</div>', tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' + 'title="{removeTitle}"{dataUrl}{dataKey}{dataIndex}>{removeIcon}</button>\n', tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' + ' {uploadIcon}\n</button>\n', tGeneric = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' {content}\n' + ' {footer}\n' + '</div>\n', tHtml = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + ' {footer}\n' + '</div>', tImage = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' + ' {footer}\n' + '</div>\n', tText = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' + ' {data}\n' + ' </div>\n' + ' {footer}\n' + '</div>', tVideo = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' + ' title="{caption}" ' + STYLE_SETTING + '>\n' + ' <video width="{width}" height="{height}" controls>\n' + ' <source src="{data}" type="{type}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </video>\n' + ' {footer}\n' + '</div>\n', tAudio = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' + ' title="{caption}" ' + STYLE_SETTING + '>\n' + ' <audio controls>\n' + ' <source src="' + '{data}' + '" type="{type}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </audio>\n' + ' {footer}\n' + '</div>', tFlash = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' + ' title="{caption}" ' + STYLE_SETTING + '>\n' + ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + ' {footer}\n' + '</div>\n', tObject = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' + ' title="{caption}" ' + STYLE_SETTING + '>\n' + ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' + ' <param name="movie" value="{caption}" />\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + ' {footer}\n' + '</div>', tOther = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' + ' title="{caption}" ' + STYLE_SETTING + '>\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' {footer}\n' + '</div>', defaultLayoutTemplates = { main1: tMain1, main2: tMain2, preview: tPreview, icon: tIcon, caption: tCaption, modal: tModal, progress: tProgress, footer: tFooter, actions: tActions, actionDelete: tActionDelete, actionUpload: tActionUpload }, defaultPreviewTemplates = { generic: tGeneric, html: tHtml, image: tImage, text: tText, video: tVideo, audio: tAudio, flash: tFlash, object: tObject, other: tOther }, defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'], defaultPreviewSettings = { image: {width: "auto", height: "160px"}, html: {width: "213px", height: "160px"}, text: {width: "160px", height: "160px"}, video: {width: "213px", height: "160px"}, audio: {width: "213px", height: "80px"}, flash: {width: "213px", height: "160px"}, object: {width: "160px", height: "160px"}, other: {width: "160px", height: "160px"} }, defaultFileTypeSettings = { image: function (vType, vName) { return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i); }, html: function (vType, vName) { return (vType !== undefined) ? vType === 'text/html' : vName.match(/\.(htm|html)$/i); }, text: function (vType, vName) { return (vType !== undefined && vType.match('text.*')) || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i); }, video: function (vType, vName) { return (vType !== undefined && vType.match(/\.video\/(ogg|mp4|webm)$/i)) || vName.match(/\.(og?|mp4|webm)$/i); }, audio: function (vType, vName) { return (vType !== undefined && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i); }, flash: function (vType, vName) { return (vType !== undefined && vType === 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i); }, object: function () { return true; }, other: function () { return true; } }, isEmpty = function (value, trim) { return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === ''); }, isArray = function (a) { return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]'; }, isSet = function (needle, haystack) { return (typeof haystack === 'object' && needle in haystack); }, getElement = function (options, param, value) { return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]); }, uniqId = function () { return Math.round(new Date().getTime() + (Math.random() * 100)); }, htmlEncode = function (str) { return String(str).repl('&', '&amp;') .repl('"', '&quot;') .repl("'", '&#39;') .repl('<', '&lt;') .repl('>', '&gt;'); }, replaceTags = function (str, tags) { var out = str; $.each(tags, function (key, value) { if (typeof value === "function") { value = value(); } out = out.repl(key, value); }); return out; }, objUrl = window.URL || window.webkitURL, FileInput = function (element, options) { this.$element = $(element); if (hasFileAPISupport() || isIE(9)) { this.init(options); this.listen(); } else { this.$element.removeClass('file-loading'); } }; FileInput.prototype = { constructor: FileInput, init: function (options) { var self = this, $el = self.$element, content, t; $.each(options, function (key, value) { if (key === 'maxFileCount' || key === 'maxFileSize' || key === 'initialPreviewCount') { self[key] = getNum(value); } self[key] = value; }); if (isEmpty(self.allowedPreviewTypes)) { self.allowedPreviewTypes = defaultPreviewTypes; } self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data'; self.reader = null; self.formdata = {}; self.isIE9 = isIE(9); self.isIE10 = isIE(10); self.filestack = []; self.ajaxRequests = []; self.isError = false; self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled; self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly'); self.isUploadable = hasFileUploadSupport && !isEmpty(self.uploadUrl); self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault; self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2'); self.captionTemplate = self.getLayoutTemplate('caption'); self.previewGenericTemplate = self.getPreviewTemplate('generic'); if (isEmpty(self.$element.attr('id'))) { self.$element.attr('id', uniqId()); } if (self.$container === undefined) { self.$container = self.createContainer(); } else { self.refreshContainer(); } self.$progress = self.$container.find('.kv-upload-progress'); self.$btnUpload = self.$container.find('.kv-fileinput-upload'); self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption')); self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name')); self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview')); self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails')); self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status')); self.$errorContainer = getElement(options, 'elErrorContainer', self.$previewContainer.find('.kv-fileinput-error')); if (!isEmpty(self.msgErrorClass)) { addCss(self.$errorContainer, self.msgErrorClass); } self.$errorContainer.hide(); self.initialPreviewContent = ''; content = self.initialPreview; self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialPreviewDelimiter).length : 0); self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings); self.previewInitId = "preview-" + uniqId(); self.initPreview(); self.initPreviewDeletes(); self.original = { preview: self.$preview.html(), caption: self.$caption.html() }; self.options = options; self.setFileDropZoneTitle(); self.uploadCount = 0; self.uploadPercent = 0; self.$element.removeClass('file-loading'); t = self.getLayoutTemplate('progress'); self.progressTemplate = t.replace('{class}', self.progressClass); self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass); self.setEllipsis(); }, raise: function (event, params) { var self = this; if (params !== undefined) { self.$element.trigger(event, params); } else { self.$element.trigger(event); } }, getLayoutTemplate: function (t) { var self = this, template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t]; if (isEmpty(self.customLayoutTags)) { return template; } return replaceTags(template, self.customLayoutTags); }, getPreviewTemplate: function (t) { var self = this, template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t]; template = template.repl('{previewFileIcon}', self.previewFileIcon); if (isEmpty(self.customPreviewTags)) { return template; } return replaceTags(template, self.customPreviewTags); }, getOutData: function (jqXHR, responseData, filesData) { var self = this; jqXHR = jqXHR || {}; responseData = responseData || {}; filesData = filesData || self.filestack.slice(0) || {}; return { form: self.formdata, files: filesData, extra: self.getExtraData(), response: responseData, reader: self.reader, jqXHR: jqXHR }; }, setEllipsis: function () { var self = this, $capCont = self.$captionContainer, $cap = self.$caption, $div = $cap.clone().css('height', 'auto').hide(); $capCont.parent().before($div); $capCont.removeClass('kv-has-ellipsis'); if ($div.outerWidth() > $cap.outerWidth()) { $capCont.addClass('kv-has-ellipsis'); } $div.remove(); }, listen: function () { var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile; $el.on('change', $.proxy(self.change, self)); $(window).on('resize', function () { self.setEllipsis(); }); $btnFile.off('click').on('click', function () { self.raise('filebrowse'); if (self.isError && !self.isUploadable) { self.clear(true); } $cap.focus(); }); $el.closest('form').off('reset').on('reset', $.proxy(self.reset, self)); self.$container.off('click') .on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self)) .on('click', '.fileinput-cancel', $.proxy(self.cancel, self)); if (self.isUploadable && self.dropZoneEnabled && self.showPreview) { self.initDragDrop(); } if (!self.isUploadable) { return; } self.$container.find('.kv-fileinput-upload').off('click').on('click', function (e) { if (!self.isUploadable) { return; } e.preventDefault(); if (!$(this).hasClass('disabled') && isEmpty($(this).attr('disabled'))) { self.upload(); } }); }, setProgress: function (p) { var self = this, pct = Math.min(p, 100), template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate; self.$progress.html(template.repl('{percent}', pct)); }, upload: function () { var self = this, totLen = self.getFileStack().length, i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData()); if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) { return; } self.resetUpload(); self.$progress.removeClass('hide'); self.uploadCount = 0; self.uploadPercent = 0; self.lock(); self.setProgress(0); if (totLen === 0 && hasExtraData) { self.uploadExtraOnly(); return; } len = self.filestack.length; if ((self.uploadAsync || totLen === 1) && self.showPreview) { outData = self.getOutData(); self.raise('filebatchpreupload', [outData]); for (i = 0; i < len; i += 1) { if (self.filestack[i] !== undefined) { self.uploadSingle(i, self.filestack, true); } } return; } self.uploadBatch(); }, lock: function () { var self = this; self.resetErrors(); self.disable(); if (self.showRemove) { addCss(self.$container.find('.fileinput-remove'), 'hide'); } if (self.showCancel) { self.$container.find('.fileinput-cancel').removeClass('hide'); } self.raise('filelock', [self.filestack, self.getExtraData()]); }, unlock: function (reset) { var self = this; if (reset === undefined) { reset = true; } self.enable(); if (self.showCancel) { addCss(self.$container.find('.fileinput-cancel'), 'hide'); } if (self.showRemove) { self.$container.find('.fileinput-remove').removeClass('hide'); } if (reset) { self.resetFileStack(); } self.raise('fileunlock', [self.filestack, self.getExtraData()]); }, resetFileStack: function () { var self = this, i = 0, newstack = []; self.$preview.find('.file-preview-frame').each(function () { var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind]; if (ind === -1) { return; } if (file !== undefined) { newstack[i] = file; $thumb.attr({ 'id': self.previewInitId + '-' + i, 'data-fileindex': i }); i += 1; } else { $thumb.attr({ 'id': 'uploaded-' + uniqId(), 'data-fileindex': '-1' }); } }); self.filestack = newstack; }, refresh: function (options) { var self = this, $el = self.$element, $zone, params = (arguments.length) ? $.extend(self.options, options) : self.options; $el.off(); self.init(params); $zone = self.$container.find('.file-drop-zone'); $zone.off('dragenter dragover drop'); $(document).off('dragenter dragover drop'); self.listen(); self.setFileDropZoneTitle(); }, initDragDrop: function () { var self = this, $zone = self.$container.find('.file-drop-zone'); $zone.off('dragenter dragover drop'); $(document).off('dragenter dragover drop'); $zone.on('dragenter dragover', function (e) { e.stopPropagation(); e.preventDefault(); if (self.isDisabled) { return; } addCss($(this), 'highlighted'); }); $zone.on('dragleave', function (e) { e.stopPropagation(); e.preventDefault(); if (self.isDisabled) { return; } $(this).removeClass('highlighted'); }); $zone.on('drop', function (e) { e.preventDefault(); if (self.isDisabled) { return; } self.change(e, 'dragdrop'); $(this).removeClass('highlighted'); }); $(document).on('dragenter dragover drop', function (e) { e.stopPropagation(); e.preventDefault(); }); }, setFileDropZoneTitle: function () { var self = this, $zone = self.$container.find('.file-drop-zone'); $zone.find('.' + self.dropZoneTitleClass).remove(); if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) { return; } if ($zone.find('.file-preview-frame').length === 0) { $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>'); } self.$container.removeClass('file-input-new'); addCss(self.$container, 'file-input-ajax-new'); }, initFileActions: function () { var self = this; self.$preview.find('.kv-file-remove').each(function () { var $el = $(this), $frame = $el.closest('.file-preview-frame'), ind = $frame.attr('data-fileindex'), n, cap; $el.off('click').on('click', function () { $frame.fadeOut('slow', function () { self.filestack[ind] = undefined; self.clearObjects($frame); $frame.remove(); var filestack = self.getFileStack(), len = filestack.length, chk = self.$container.find('.file-preview-initial').length; if (len === 0 && chk === 0) { self.original.preview = ''; self.reset(); } else { n = self.initialPreviewCount + len; cap = n > 1 ? self.msgSelected.repl('{n}', n) : filestack[0].name; self.setCaption(cap); } }); }); }); self.$preview.find('.kv-file-upload').each(function () { var $el = $(this); $el.off('click').on('click', function () { var $frame = $el.closest('.file-preview-frame'), ind = $frame.attr('data-fileindex'); self.uploadSingle(ind, self.filestack, false); }); }); }, renderInitFileFooter: function (i) { if (this.initialPreviewConfig.length === 0 || isEmpty(this.initialPreviewConfig[i])) { return ''; } var self = this, template = self.getLayoutTemplate('footer'), config = self.initialPreviewConfig[i], caption = isSet('caption', config) ? config.caption : '', width = isSet('width', config) ? config.width : 'auto', url = isSet('url', config) ? config.url : false, key = isSet('key', config) ? config.key : null, disabled = (url === false), actions = self.initialPreviewShowDelete ? self.renderFileActions(false, true, disabled, url, key, i) : '', footer = template.repl('{actions}', actions); return footer.repl('{caption}', caption).repl('{width}', width) .repl('{indicator}', '').repl('{indicatorTitle}', ''); }, renderFileFooter: function (caption, width) { var self = this, config = self.fileActionSettings, footer, template = self.getLayoutTemplate('footer'); if (self.isUploadable) { footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false, false)); return footer.repl('{caption}', caption) .repl('{width}', width) .repl('{indicator}', config.indicatorNew) .repl('{indicatorTitle}', config.indicatorNewTitle); } return template.repl('{actions}', '') .repl('{caption}', caption) .repl('{width}', width) .repl('{indicator}', '') .repl('{indicatorTitle}', ''); }, renderFileActions: function (showUpload, showDelete, disabled, url, key, index) { if (!showUpload && !showDelete) { return ''; } var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"', vIndex = index === false ? '' : ' data-index="' + index + '"', vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = self.getLayoutTemplate('actionDelete'), btnUpload = '', template = self.getLayoutTemplate('actions'), otherActionButtons = self.otherActionButtons.repl('{dataKey}', vKey), config = self.fileActionSettings, removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass; btnDelete = btnDelete .repl('{removeClass}', removeClass) .repl('{removeIcon}', config.removeIcon) .repl('{removeTitle}', config.removeTitle) .repl('{dataUrl}', vUrl) .repl('{dataKey}', vKey) .repl('{dataIndex}', vIndex); if (showUpload) { btnUpload = self.getLayoutTemplate('actionUpload') .repl('{uploadClass}', config.uploadClass) .repl('{uploadIcon}', config.uploadIcon) .repl('{uploadTitle}', config.uploadTitle); } return template .repl('{delete}', btnDelete) .repl('{upload}', btnUpload) .repl('{other}', otherActionButtons); }, getInitialPreview: function (template, content, i) { var self = this, ind = 'init_' + i, previewId = self.previewInitId + '-' + ind, footer = self.renderInitFileFooter(i, false); return template .repl('{previewId}', previewId) .repl('{frameClass}', ' file-preview-initial') .repl('{fileindex}', ind) .repl('{content}', content) .repl('{footer}', footer); }, initPreview: function () { var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount, cap = self.initialCaption.length, i, fileList, caption = (cap > 0) ? self.initialCaption : self.msgSelected.repl('{n}', len); if (isArray(content) && len > 0) { for (i = 0; i < len; i += 1) { html += self.getInitialPreview(self.previewGenericTemplate, content[i], i); } if (len > 1 && cap === 0) { caption = self.msgSelected.repl('{n}', len); } } else { if (len > 0) { fileList = content.split(self.initialPreviewDelimiter); for (i = 0; i < len; i += 1) { html += self.getInitialPreview(self.previewGenericTemplate, fileList[i], i); } if (len > 1 && cap === 0) { caption = self.msgSelected.repl('{n}', len); } } else { if (cap > 0) { self.setCaption(caption); } return; } } self.initialPreviewContent = html; self.$preview.html(html); self.setCaption(caption); self.$container.removeClass('file-input-new'); }, initPreviewDeletes: function () { var self = this, deleteExtraData = self.deleteExtraData || {}, caption, $that, resetProgress = function () { if (self.$preview.find('.kv-file-remove').length === 0) { self.reset(); } }; self.$preview.find('.kv-file-remove').each(function () { var $el = $(this), $frame = $el.closest('.file-preview-frame'), index = $el.data('index'), config = isEmpty(self.initialPreviewConfig[index]) ? null : self.initialPreviewConfig[index], extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra, vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), $content; if (typeof extraData === "function") { extraData = extraData(); } if (vUrl === undefined || vKey === undefined) { return; } $el.off('click').on('click', function () { $.ajax({ url: vUrl, type: 'POST', dataType: 'json', data: $.extend({key: vKey}, extraData), beforeSend: function (jqXHR) { addCss($frame, 'file-uploading'); addCss($el, 'disabled'); self.raise('filepredelete', [vKey, jqXHR, extraData]); }, success: function (data, textStatus, jqXHR) { if (data.error === undefined) { self.raise('filedeleted', [vKey, jqXHR, extraData]); } else { self.showError(data.error, extraData, $el.attr('id'), vKey, 'filedeleteerror', jqXHR); $frame.removeClass('file-uploading'); $el.removeClass('disabled'); resetProgress(); return; } $frame.removeClass('file-uploading').addClass('file-deleted'); $frame.fadeOut('slow', function () { self.clearObjects($frame); $frame.remove(); $content = $(document.createElement('div')).html(self.original.preview); $content.find('.file-preview-frame').each(function () { $that = $(this); if ($that.find('.kv-file-remove').attr('data-key') == vKey) { $that.remove(); } }); self.initialPreviewContent = $content.html(); if (self.initialPreviewCount > 0) { self.initialPreviewCount -= 1; } caption = self.initialCaption; if (self.initialCaption.length === 0) { caption = self.msgSelected.repl('{n}', self.initialPreviewCount); } self.original.preview = $content.html(); self.setCaption(caption); self.original.caption = self.$caption.html(); $content.remove(); resetProgress(); }); }, error: function (jqXHR, textStatus, errorThrown) { self.showError(errorThrown, extraData, $el.attr('id'), vKey, 'filedeleteerror', jqXHR); $frame.removeClass('file-uploading'); resetProgress(); } }); }); }); }, clearObjects: function ($el) { $el.find('video audio').each(function () { this.pause(); $(this).remove(); }); $el.find('img object div').each(function () { $(this).remove(); }); }, clearFileInput: function () { var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl; if (isEmpty($el.val())) { return; } // Fix for IE ver < 11, that does not clear file inputs // Requires a sequence of steps to prevent IE crashing but // still allow clearing of the file input. if (self.isIE9 || self.isIE10) { $srcFrm = $el.closest('form'); $tmpFrm = $(document.createElement('form')); $tmpEl = $(document.createElement('div')); $el.before($tmpEl); if ($srcFrm.length) { $srcFrm.after($tmpFrm); } else { $tmpEl.after($tmpFrm); } $tmpFrm.append($el).trigger('reset'); $tmpEl.before($el).remove(); $tmpFrm.remove(); } else { // normal input clear behavior for other sane browsers $el.val(''); } }, resetUpload: function () { var self = this; self.uploadCount = 0; self.uploadPercent = 0; self.$btnUpload.removeAttr('disabled'); self.setProgress(0); addCss(self.$progress, 'hide'); self.resetErrors(false); self.ajaxRequests = []; }, cancel: function () { var self = this, xhr = self.ajaxRequests, len = xhr.length, i; if (len > 0) { for (i = 0; i < len; i += 1) { xhr[i].abort(); } } self.$preview.find('.file-preview-frame').each(function () { var $thumb = $(this), ind = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); if (self.filestack[ind] !== undefined) { $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled'); $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled'); } self.unlock(); }); }, clear: function (trig) { var self = this, cap; if (!self.isIE9 && self.reader instanceof FileReader) { self.reader.abort(); } self.$btnUpload.removeAttr('disabled'); self.resetUpload(); self.filestack = []; self.clearFileInput(); self.resetErrors(true); if (trig !== true) { self.raise('change'); self.raise('fileclear'); } if (self.overwriteInitial) { self.initialPreviewCount = 0; self.initialPreviewContent = ''; } if (!self.overwriteInitial && self.initialPreviewContent.length > 0) { self.showFileIcon(); self.$preview.html(self.original.preview); self.$caption.html(self.original.caption); self.setEllipsis(); self.initPreviewDeletes(); self.$container.removeClass('file-input-new'); } else { self.$preview.find('.file-preview-frame').each(function () { self.clearObjects($(this)); }); self.$preview.html(''); cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.original.caption : ''; self.$caption.html(cap); self.setEllipsis(); self.$caption.attr('title', ''); addCss(self.$container, 'file-input-new'); } if (self.$container.find('.file-preview-frame').length === 0) { self.initialCaption = ''; self.original.caption = ''; self.$caption.html(''); self.setEllipsis(); self.$captionContainer.find('.kv-caption-icon').hide(); } self.hideFileIcon(); self.raise('filecleared'); self.$captionContainer.focus(); self.setFileDropZoneTitle(); }, reset: function () { var self = this; self.clear(true); self.$preview.html(self.original.preview); self.$caption.html(self.original.caption); self.setEllipsis(); self.$container.find('.fileinput-filename').text(''); self.raise('filereset'); if (self.initialPreview.length > 0) { self.$container.removeClass('file-input-new'); } self.setFileDropZoneTitle(); if (self.isUploadable) { self.resetUpload(); } self.filestack = []; self.formdata = {}; }, disable: function () { var self = this; self.isDisabled = true; self.raise('filedisabled'); self.$element.attr('disabled', 'disabled'); self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled"); self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true); self.initDragDrop(); }, enable: function () { var self = this; self.isDisabled = false; self.raise('fileenabled'); self.$element.removeAttr('disabled'); self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled"); self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled"); self.initDragDrop(); }, getExtraData: function () { var self = this, data = self.uploadExtraData; if (typeof self.uploadExtraData === "function") { data = self.uploadExtraData(); } return data; }, uploadExtra: function () { var self = this, data = self.getExtraData(); if (data.length === 0) { return; } $.each(data, function (key, value) { self.formdata.append(key, value); }); }, initXhr: function (xhrobj, factor) { var self = this; if (xhrobj.upload) { xhrobj.upload.addEventListener('progress', function (event) { var pct = 0, position = event.loaded || event.position, total = event.total; if (event.lengthComputable) { pct = Math.ceil(position / total * factor); } self.uploadPercent = Math.max(pct, self.uploadPercent); self.setProgress(self.uploadPercent); }, false); } return xhrobj; }, ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) { var self = this, settings; self.uploadExtra(); settings = $.extend(self.ajaxSettings, { xhr: function () { var xhrobj = $.ajaxSettings.xhr(); return self.initXhr(xhrobj, 98); }, url: self.uploadUrl, type: 'POST', dataType: 'json', data: self.formdata, cache: false, processData: false, contentType: false, beforeSend: fnBefore, success: fnSuccess, complete: fnComplete, error: fnError }); self.ajaxRequests.push($.ajax(settings)); }, uploadSingle: function (i, files, allFiles) { var self = this, total = self.getFileStack().length, formdata = new FormData(), outData, previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId), cap, pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'), $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), setIndicator, updateProgress, resetActions, fnBefore, fnSuccess, fnComplete, fnError; self.formdata = formdata; if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled')) { return; } chkComplete = function () { var $thumbs = self.$preview.find('.file-preview-frame.file-uploading'), chk = $thumbs.length; if (chk > 0) { return; } self.setProgress(100); self.unlock(); self.clearFileInput(); self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]); }; setIndicator = function (icon, msg) { $indicator.html(config[icon]); $indicator.attr('title', config[msg]); }; updateProgress = function () { if (!allFiles || total === 0 || self.uploadPercent >= 100) { return; } self.uploadCount += 1; pct = 80 + Math.ceil(self.uploadCount * 20 / total); self.uploadPercent = Math.max(pct, self.uploadPercent); self.setProgress(self.uploadPercent); self.initPreviewDeletes(); }; resetActions = function () { $btnUpload.removeAttr('disabled'); $btnDelete.removeAttr('disabled'); $thumb.removeClass('file-uploading'); }; fnBefore = function (jqXHR) { outData = self.getOutData(jqXHR); setIndicator('indicatorLoading', 'indicatorLoadingTitle'); addCss($thumb, 'file-uploading'); $btnUpload.attr('disabled', true); $btnDelete.attr('disabled', true); if (!allFiles) { self.lock(); } self.raise('filepreupload', [outData, previewId, i]); }; fnSuccess = function (data, textStatus, jqXHR) { outData = self.getOutData(jqXHR, data); setTimeout(function () { if (data.error === undefined) { setIndicator('indicatorSuccess', 'indicatorSuccessTitle'); $btnUpload.hide(); $btnDelete.hide(); self.filestack[i] = undefined; if (!allFiles) { self.resetFileStack(); } self.raise('fileuploaded', [outData, previewId, i]); } else { setIndicator('indicatorError', 'indicatorErrorTitle'); self.showUploadError(data.error, outData, previewId, i); } }, 100); }; fnComplete = function () { setTimeout(function () { updateProgress(); resetActions(); if (!allFiles) { self.unlock(false); } else { chkComplete(); } }, 100); }; fnError = function (jqXHR, textStatus, errorThrown) { setIndicator('indicatorError', 'indicatorErrorTitle'); outData = self.getOutData(jqXHR); if (allFiles) { cap = files[i].name; self.showUploadError('<b>' + cap + '</b>: ' + errorThrown, outData, previewId, i); } else { self.showUploadError(errorThrown, outData, previewId, i); } }; formdata.append(self.uploadFileAttr, files[i]); formdata.append('file_id', i); self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError); }, uploadBatch: function () { var self = this, files = self.filestack, total = files.length, config, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), setIndicator, setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError; self.formdata = new FormData(); if (total === 0 || !hasPostData) { return; } config = self.fileActionSettings; setIndicator = function (i, icon, msg) { var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator'); $indicator.html(config[icon]); $indicator.attr('title', config[msg]); }; enableActions = function (i) { var $thumb = $('#' + self.previewInitId + "-" + i), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-delete'); $thumb.removeClass('file-uploading'); $btnUpload.removeAttr('disabled'); $btnDelete.removeAttr('disabled'); }; setAllUploaded = function () { $.each(files, function (key, data) { self.filestack[key] = undefined; }); self.clearFileInput(); }; fnBefore = function (jqXHR) { self.lock(); var outData = self.getOutData(jqXHR); if (self.showPreview) { self.$preview.find('.file-preview-frame').each(function () { var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'); addCss($thumb, 'file-uploading'); $btnUpload.attr('disabled', true); $btnDelete.attr('disabled', true); }); } self.raise('filebatchpreupload', [outData]); }; fnSuccess = function (data, textStatus, jqXHR) { var outData = self.getOutData(jqXHR, data), keys = isEmpty(data.errorkeys) ? [] : data.errorkeys; if (data.error === undefined || isEmpty(data.error)) { self.raise('filebatchuploadsuccess', [outData]); setAllUploaded(); if (self.showPreview) { self.$preview.find('.kv-file-upload').hide(); self.$preview.find('.kv-file-remove').hide(); self.$preview.find('.file-preview-frame').each(function () { var $thumb = $(this), key = $thumb.attr('data-fileindex'); setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle'); enableActions(key); }); } else { self.reset(); } } else { if (self.showPreview) { self.$preview.find('.file-preview-frame').each(function () { var $thumb = $(this), key = parseInt($thumb.attr('data-fileindex'), 10); enableActions(key); if (keys.length === 0) { setIndicator(key, 'indicatorError', 'indicatorErrorTitle'); return; } if ($.inArray(key, keys) !== -1) { setIndicator(key, 'indicatorError', 'indicatorErrorTitle'); } else { $thumb.find('.kv-file-upload').hide(); $thumb.find('.kv-file-remove').hide(); setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle'); self.filestack[key] = undefined; } }); } self.showUploadError(data.error, outData, null, null, 'filebatchuploaderror'); } }; fnComplete = function () { self.setProgress(100); self.unlock(); self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]); self.clearFileInput(); }; fnError = function (jqXHR, textStatus, errorThrown) { var outData = self.getOutData(jqXHR); self.showUploadError(errorThrown, outData, null, null, 'filebatchuploaderror'); self.uploadFileCount = total - 1; if (!self.showPreview) { return; } self.$preview.find('.file-preview-frame').each(function () { var $thumb = $(this), key = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); if (self.filestack[key] !== undefined) { setIndicator(key, 'indicatorError', 'indicatorErrorTitle'); } }); self.$preview.find('.file-preview-frame').removeClass('file-uploading'); self.$preview.find('.file-preview-frame kv-file-upload').removeAttr('disabled'); self.$preview.find('.file-preview-frame kv-file-delete').removeAttr('disabled'); }; $.each(files, function (key, data) { if (!isEmpty(files[key])) { self.formdata.append(self.uploadFileAttr, data); } }); self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError); }, uploadExtraOnly: function () { var self = this, fnBefore, fnSuccess, fnComplete, fnError; self.formdata = new FormData(); fnBefore = function (jqXHR) { self.lock(); var outData = self.getOutData(jqXHR); self.raise('filebatchpreupload', [outData]); self.setProgress(50); }; fnSuccess = function (data, textStatus, jqXHR) { var outData = self.getOutData(jqXHR, data), keys = isEmpty(data.errorkeys) ? [] : data.errorkeys; if (data.error === undefined || isEmpty(data.error)) { self.raise('filebatchuploadsuccess', [outData]); self.clearFileInput(); } else { self.showUploadError(data.error, outData, null, null, 'filebatchuploaderror'); } }; fnComplete = function () { self.setProgress(100); self.unlock(); self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]); self.clearFileInput(); }; fnError = function (jqXHR, textStatus, errorThrown) { var outData = self.getOutData(jqXHR); self.showUploadError(errorThrown, outData, null, null, 'filebatchuploaderror'); }; self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError); }, hideFileIcon: function () { if (this.overwriteInitial) { this.$captionContainer.find('.kv-caption-icon').hide(); } }, showFileIcon: function () { this.$captionContainer.find('.kv-caption-icon').show(); }, resetErrors: function (fade) { var self = this, $error = self.$errorContainer; self.isError = false; self.$container.removeClass('has-error'); $error.html(''); if (fade) { $error.fadeOut('slow'); } else { $error.hide(); } }, showUploadError: function (msg, data, previewId, index, ev) { var self = this, $error = self.$errorContainer; ev = ev || 'fileuploaderror'; if ($error.find('ul').length === 0) { $error.html('<ul class="text-left"><li>' + msg + '</li></ul>'); } else { $error.find('ul').append('<li>' + msg + '</li>'); } $error.fadeIn(800); self.raise(ev, [data, previewId, index, self.reader]); addCss(self.$container, 'has-error'); return true; }, showError: function (msg, file, previewId, index, ev, jqXHR) { var self = this, $error = self.$errorContainer; ev = ev || 'fileerror'; jqXHR = jqXHR || {}; $error.html(msg); $error.fadeIn(800); self.raise(ev, [file, previewId, index, self.reader, jqXHR]); if (!self.isUploadable) { self.clearFileInput(); } addCss(self.$container, 'has-error'); self.$btnUpload.attr('disabled', true); return true; }, errorHandler: function (evt, caption) { var self = this, err = evt.target.error; switch (err.code) { case err.NOT_FOUND_ERR: self.addError(self.msgFileNotFound.repl('{name}', caption)); break; case err.SECURITY_ERR: self.addError(self.msgFileSecured.repl('{name}', caption)); break; case err.NOT_READABLE_ERR: self.addError(self.msgFileNotReadable.repl('{name}', caption)); break; case err.ABORT_ERR: self.addError(self.msgFilePreviewAborted.repl('{name}', caption)); break; default: self.addError(self.msgFilePreviewError.repl('{name}', caption)); } }, parseFileType: function (file) { var self = this, isValid, vType, cat, i; for (i = 0; i < defaultPreviewTypes.length; i += 1) { cat = defaultPreviewTypes[i]; isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat]; vType = isValid(file.type, file.name) ? cat : ''; if (!isEmpty(vType)) { return vType; } } return 'other'; }, previewDefault: function (file, previewId, isDisabled) { if (!this.showPreview) { return; } var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId), config = self.previewSettings.other, footer = self.renderFileFooter(file.name, config.width), previewOtherTemplate = self.getPreviewTemplate('other'), ind = previewId.slice(previewId.lastIndexOf('-') + 1), frameClass = ''; if (isDisabled === true) { frameClass = ' btn disabled'; footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>'; } self.$preview.append("\n" + previewOtherTemplate .repl('{previewId}', previewId) .repl('{frameClass}', frameClass) .repl('{fileindex}', ind) .repl('{caption}', self.slug(file.name)) .repl('{width}', config.width) .repl('{height}', config.height) .repl('{type}', file.type) .repl('{data}', data) .repl('{footer}', footer)); $obj.on('load', function () { objUrl.revokeObjectURL($obj.attr('data')); }); }, previewFile: function (file, theFile, previewId, data) { if (!this.showPreview) { return; } var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, tmplt = self.getPreviewTemplate(cat), config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat], wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator, chkTypes = types.indexOf(cat) >= 0, id, height, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)), footer = self.renderFileFooter(caption, config.width), modal = '', ind = previewId.slice(previewId.lastIndexOf('-') + 1); if (chkTypes && chkMimes) { if (cat === 'text') { strText = htmlEncode(theFile.target.result); objUrl.revokeObjectURL(data); if (strText.length > wrapLen) { id = 'text-' + uniqId(); height = window.innerHeight * 0.75; modal = self.getLayoutTemplate('modal').repl('{id}', id) .repl('{title}', caption) .repl('{height}', height) .repl('{body}', strText); wrapInd = wrapInd .repl('{title}', caption) .repl('{dialog}', "$('#" + id + "').modal('show')"); strText = strText.substring(0, (wrapLen - 1)) + wrapInd; } content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption) .repl('{frameClass}', '') .repl('{type}', file.type).repl('{width}', config.width) .repl('{height}', config.height).repl('{data}', strText) .repl('{footer}', footer).repl('{fileindex}', ind) + modal; } else { content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption) .repl('{frameClass}', '') .repl('{type}', file.type).repl('{data}', data) .repl('{width}', config.width).repl('{height}', config.height) .repl('{footer}', footer).repl('{fileindex}', ind); } self.$preview.append("\n" + content); self.autoSizeImage(previewId); } else { self.previewDefault(file, previewId); } }, slugDefault: function (text) { return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\-.\\\/ ]+/g, ''); }, getFileStack: function () { var self = this; return self.filestack.filter(function (n) { return n !== undefined; }); }, readFiles: function (files) { this.reader = new FileReader(); var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader, $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings, ctr = self.filestack.length, throwError = function (msg, file, previewId, index) { self.previewDefault(file, previewId, true); var outData = self.getOutData({}, {}, files); return self.isUploadable ? self.showUploadError(msg, outData, previewId, index) : self.showError(msg, file, previewId, index); }; function readFile(i) { if (isEmpty($el.attr('multiple'))) { numFiles = 1; } if (i >= numFiles) { $container.removeClass('loading'); $status.html(''); return; } var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i], caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '', previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk, fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '), fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', '); if (!isEmpty(fileExt)) { fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i'); } fileSize = fileSize.toFixed(2); if (self.maxFileSize > 0 && fileSize > self.maxFileSize) { msg = self.msgSizeTooLarge.repl('{name}', caption) .repl('{size}', fileSize) .repl('{maxSize}', self.maxFileSize); self.isError = throwError(msg, file, previewId, i); return; } if (!isEmpty(fileTypes) && isArray(fileTypes)) { for (j = 0; j < fileTypes.length; j += 1) { typ = fileTypes[j]; checkFile = settings[typ]; chk = (checkFile !== undefined && checkFile(file.type, caption)); fileCount += isEmpty(chk) ? 0 : chk.length; } if (fileCount === 0) { msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes); self.isError = throwError(msg, file, previewId, i); return; } } if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) { chk = caption.match(fileExtExpr); fileCount += isEmpty(chk) ? 0 : chk.length; if (fileCount === 0) { msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}', strExt); self.isError = throwError(msg, file, previewId, i); return; } } if (!self.showPreview) { self.filestack.push(file); setTimeout(readFile(i + 1), 100); self.raise('fileloaded', [file, previewId, i, reader]); return; } if ($preview.length > 0 && FileReader !== undefined) { $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles)); $container.addClass('loading'); reader.onerror = function (evt) { self.errorHandler(evt, caption); }; reader.onload = function (theFile) { self.previewFile(file, theFile, previewId, previewData); self.initFileActions(); }; reader.onloadend = function () { msg = msgProgress .repl('{index}', i + 1).repl('{files}', numFiles) .repl('{percent}', 50).repl('{name}', caption); setTimeout(function () { $status.html(msg); objUrl.revokeObjectURL(previewData); }, 100); setTimeout(function () { readFile(i + 1); self.updateFileDetails(numFiles); }, 100); self.raise('fileloaded', [file, previewId, i, reader]); }; reader.onprogress = function (data) { if (data.lengthComputable) { var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact); msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles) .repl('{percent}', progress).repl('{name}', caption); setTimeout(function () { $status.html(msg); }, 100); } }; isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text; if (isText(file.type, caption)) { reader.readAsText(file, self.textEncoding); } else { reader.readAsArrayBuffer(file); } } else { self.previewDefault(file, previewId); setTimeout(function () { readFile(i + 1); self.updateFileDetails(numFiles); }, 100); self.raise('fileloaded', [file, previewId, i, reader]); } self.filestack.push(file); } readFile(0); self.updateFileDetails(numFiles, false); }, updateFileDetails: function (numFiles) { var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(), name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles, nFiles = self.initialPreviewCount + n, log = n > 1 ? msgSelected.repl('{n}', nFiles) : label; if (self.isError) { self.$previewContainer.removeClass('loading'); self.$previewStatus.html(''); self.$captionContainer.find('.kv-caption-icon').hide(); log = self.msgValidationError; } else { self.showFileIcon(); } self.setCaption(log); self.$container.removeClass('file-input-new file-input-ajax-new'); if (arguments.length === 1) { self.raise('fileselect', [numFiles, label]); } }, change: function (e) { var self = this, $el = self.$element; if (!self.isUploadable && isEmpty($el.val())) { // IE 11 fix return; } var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1, files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, isSingleUpload = isEmpty($el.attr('multiple')), ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr !== 0), throwError = function (mesg, file, previewId, index) { var outData = self.getOutData({}, {}, files); return self.isUploadable ? self.showUploadError(mesg, outData, previewId, index) : self.showError(mesg, file, previewId, index); }; self.resetUpload(); self.hideFileIcon(); self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove(); if (isDragDrop) { tfiles = files; } else { if (e.target.files === undefined) { tfiles = e.target && e.target.value ? [ {name: e.target.value.replace(/^.+\\/, '')} ] : []; } else { tfiles = e.target.files; } } if (isEmpty(tfiles) || tfiles.length === 0) { if (!isAjaxUpload) { self.clear(true); } self.raise('fileselectnone'); return; } self.resetErrors(); if (!isAjaxUpload || (isSingleUpload && ctr > 0)) { if (!self.overwriteInitial) { $preview.html(self.initialPreviewContent); } else { $preview.html(''); } if (isSingleUpload && ctr > 0) { self.filestack = []; } } total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length; if (self.maxFileCount > 0 && total > self.maxFileCount) { msg = self.msgFilesTooMany.repl('{m}', self.maxFileCount).repl('{n}', total); self.isError = throwError(msg, null, null, null); self.$captionContainer.find('.kv-caption-icon').hide(); self.$caption.html(self.msgValidationError); self.setEllipsis(); self.$container.removeClass('file-input-new file-input-ajax-new'); return; } if (!self.isIE9) { self.readFiles(tfiles); } else { self.updateFileDetails(1); } if (isAjaxUpload) { self.raise('filebatchselected', [self.getFileStack()]); } else { self.raise('filebatchselected', [tfiles]); } self.reader = null; }, autoSizeImage: function (previewId) { var self = this, $preview = self.$preview, $thumb = $preview.find("#" + previewId), $img = $thumb.find('img'), w1, w2, $cap; if (!$img.length) { return; } $img.on('load', function () { w1 = $thumb.width(); w2 = $preview.width(); if (w1 > w2) { $img.css('width', '100%'); $thumb.css('width', '97%'); } $cap = $img.closest('.file-preview-frame').find('.file-caption-name'); if ($cap.length) { $cap.width($img.width()); $cap.attr('title', $cap.text()); } self.raise('fileimageloaded', previewId); }); }, setCaption: function (content) { var self = this, title = $('<div>' + content + '</div>').text(), icon = self.getLayoutTemplate('icon'), out = icon + title; if (self.$caption.length === 0) { return; } self.$caption.html(out); self.$caption.attr('title', title); self.$captionContainer.find('.file-caption-ellipsis').attr('title', title); self.setEllipsis(); }, initBrowse: function ($container) { var self = this; self.$btnFile = $container.find('.btn-file'); self.$btnFile.append(self.$element); }, createContainer: function () { var self = this, $container = $(document.createElement("span")) .attr({"class": 'file-input file-input-new'}) .html(self.renderMain()); self.$element.before($container); self.initBrowse($container); return $container; }, refreshContainer: function () { var self = this, $container = self.$container; $container.before(self.$element); $container.html(self.renderMain()); self.initBrowse($container); }, renderMain: function () { var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '', preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass) .repl('{dropClass}', dropCss) : '', css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass, caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption'); return self.mainTemplate.repl('{class}', self.mainClass) .repl('{preview}', preview) .repl('{caption}', caption) .repl('{upload}', self.renderUpload()) .repl('{remove}', self.renderRemove()) .repl('{cancel}', self.renderCancel()) .repl('{browse}', self.renderBrowse()); }, renderBrowse: function () { var self = this, css = self.browseClass + ' btn-file', status = ''; if (self.isDisabled) { status = ' disabled '; } return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>'; }, renderRemove: function () { var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = ''; if (!self.showRemove) { return ''; } if (self.isDisabled) { status = ' disabled '; } return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>'; }, renderCancel: function () { var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button'; if (!self.showCancel) { return ''; } return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>'; }, renderUpload: function () { var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = ''; if (!self.showUpload) { return ''; } if (self.isDisabled) { status = ' disabled '; } if (!self.isUploadable || self.isDisabled) { content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>'; } else { content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>'; } return content; } }; //FileInput plugin definition $.fn.fileinput = function (option) { if (!hasFileAPISupport() && !isIE(9)) { return; } var args = Array.apply(null, arguments); args.shift(); return this.each(function () { var $this = $(this), data = $this.data('fileinput'), options = typeof option === 'object' && option; if (!data) { data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data())); $this.data('fileinput', data); } if (typeof option === 'string') { data[option].apply(data, args); } }); }; $.fn.fileinput.defaults = { showCaption: true, showPreview: true, showRemove: true, showUpload: true, showCancel: true, mainClass: '', previewClass: '', captionClass: '', mainTemplate: null, initialCaption: '', initialPreview: '', initialPreviewCount: 0, initialPreviewDelimiter: '*$$*', initialPreviewConfig: [], initialPreviewShowDelete: true, deleteUrl: '', deleteExtraData: {}, overwriteInitial: true, layoutTemplates: defaultLayoutTemplates, previewTemplates: defaultPreviewTemplates, allowedPreviewTypes: defaultPreviewTypes, allowedPreviewMimeTypes: null, allowedFileTypes: null, allowedFileExtensions: null, customLayoutTags: {}, customPreviewTags: {}, previewSettings: defaultPreviewSettings, fileTypeSettings: defaultFileTypeSettings, previewFileIcon: '<i class="glyphicon glyphicon-file"></i>', browseLabel: 'Browse &hellip;', browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;', browseClass: 'btn btn-primary', removeLabel: 'Remove', removeTitle: 'Clear selected files', removeIcon: '<i class="glyphicon glyphicon-trash"></i> ', removeClass: 'btn btn-default', cancelLabel: 'Cancel', cancelTitle: 'Abort ongoing upload', cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ', cancelClass: 'btn btn-default', uploadLabel: 'Upload', uploadTitle: 'Upload selected files', uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ', uploadClass: 'btn btn-default', uploadUrl: null, uploadAsync: true, uploadExtraData: {}, maxFileSize: 0, maxFileCount: 0, msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!', msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!', msgFileNotFound: 'File "{name}" not found!', msgFileSecured: 'Security restrictions prevent reading the file "{name}".', msgFileNotReadable: 'File "{name}" is not readable.', msgFilePreviewAborted: 'File preview aborted for "{name}".', msgFilePreviewError: 'An error occurred while reading the file "{name}".', msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.', msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>', msgErrorClass: 'file-error-message', msgLoading: 'Loading file {index} of {files} &hellip;', msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', msgSelected: '{n} files selected', progressClass: "progress-bar progress-bar-success progress-bar-striped active", progressCompleteClass: "progress-bar progress-bar-success", previewFileType: 'image', wrapTextLength: 250, wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>', elCaptionContainer: null, elCaptionText: null, elPreviewContainer: null, elPreviewImage: null, elPreviewStatus: null, elErrorContainer: null, slugCallback: null, dropZoneEnabled: true, dropZoneTitle: 'Drag & drop files here &hellip;', dropZoneTitleClass: 'file-drop-zone-title', fileActionSettings: {}, otherActionButtons: '', textEncoding: 'UTF-8', ajaxSettings: {} }; $.fn.fileinput.Constructor = FileInput; /** * Convert automatically file inputs with class 'file' * into a bootstrap fileinput control. */ $(document).ready(function () { var $input = $('input.file[type=file]'), count = $input.attr('type') ? $input.length : 0; if (count > 0) { $input.fileinput(); } }); })(window.jQuery);
le-tri-mulodo/trile.miniblog
htmlApp/js/fileinput.min.js
JavaScript
apache-2.0
87,334
/* * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ require(["jquery", "sakai/sakai.api.core"], function($, sakai){ /** * @name sakai_global.carousel * * @class carousel * * @description * * @version 0.0.1 * @param {String} tuid Unique id of the widget * @param {Boolean} showSettings Show the settings of the widget or not */ sakai_global.carousel = function(tuid, showSettings){ ///////////////////////////// // Configuration variables // ///////////////////////////// // Containers var carouselContainer = "#carousel_container"; // Templates var carouselSingleColumnTemplate = "carousel_single_column_template"; ///////////////////// // RENDER CAROUSEL // ///////////////////// var updateViewAfterAnimation = function(carousel, li, index, state){ if (index > carousel.options.size || index < 1) { index = index % carousel.options.size; if (!index) { index = carousel.options.size; } if (index < 1) { index = carousel.options.size + index; } } $("#carousel_container .carousel_view_toggle li").removeClass("carousel_view_toggle_selected"); $("#carousel_view_toggle_" + carousel.last).removeClass("carousel_view_toggle_selected"); $("#carousel_view_toggle_" + index).addClass("carousel_view_toggle_selected"); $(window).bind("sakai.addToContacts.requested", function(evObj, user){ var addbutton = $.grep($("#carousel_container .sakai_addtocontacts_overlay"), function(value, index) { return $(value).attr("sakai-entityid") === user.userid; }); $(addbutton).remove(); }); }; var stopAutoScrolling = function(carousel){ carousel.startAuto(0); }; var carouselBinding = function(carousel){ // Pause autoscrolling if the user moves with the cursor over the clip. carousel.clip.hover(function(){ carousel.stopAuto(); }, function(){ carousel.startAuto(); }); // Disable autoscrolling if the user clicks the prev or next button. carousel.buttonNext.bind('click', function(){ stopAutoScrolling(carousel); }); carousel.buttonPrev.bind('click', function(){ stopAutoScrolling(carousel); }); $('.carousel_view_toggle li').bind('click', function(){ stopAutoScrolling(carousel); carousel.scroll($.jcarousel.intval($(this)[0].id.split("carousel_view_toggle_")[1])); $("#carousel_container .carousel_view_toggle li").removeClass("carousel_view_toggle_selected"); $(this).addClass("carousel_view_toggle_selected"); return false; }); $(window).bind(tuid + ".shown.sakai", {"carousel": carousel}, toggleCarousel); }; var toggleCarousel = function(e, showing){ if (showing) { e.data.carousel.startAuto(); } else { e.data.carousel.stopAuto(); } }; var renderCarousel = function(dataArr){ sakai.api.Util.TemplateRenderer(carouselSingleColumnTemplate, { "data": dataArr, "sakai": sakai }, $(carouselContainer), false); applyThreeDots(); $(carouselContainer).jcarousel({ auto: 8, animation: "slow", scroll: 1, easing: "swing", size: dataArr.length, initCallback: carouselBinding, wrap: "circular", itemFirstInCallback: { onAfterAnimation: updateViewAfterAnimation } }); }; var applyThreeDots = function(){ $.each($(".carousel_apply_threedots"), function(index, item){ var maxrows = 1; if (item && item.className) { var classes = item.className.split(" "); $.each(classes, function(i, cl){ if (cl && cl.indexOf("threedots_allow_") === 0) { maxrows = parseInt(cl.split("threedots_allow_")[1], 10); return false; } }); } $(item).text(sakai.api.Util.applyThreeDots($(item).text(), $(item).width(), {max_rows:maxrows}, "carousel_content_tags s3d_action", true)); }); }; var parseContent = function(data, dataArr, callback){ var noPreviewArr = []; var previewArr = []; if (data && data.content && data.content.results) { sakai.api.Content.prepareContentForRender(data.content.results, sakai.data.me, function(results){ $.each(results, function(index, item) { if (item.thumbnail){ previewArr.push(item); } else { noPreviewArr.push(item); } }); // Prefer items with previews var suggested = { contentType: "suggestedContent", suggestions: previewArr.concat(noPreviewArr) }; dataArr.push(suggested); callback(data, dataArr); }); } }; var parseGroups = function(data, dataArr){ var picDescTags = []; var picDesc = []; var picTags = []; var descTags = []; var desc = []; var tags = []; var noPic = []; $.each(data.groups.results, function (index, group){ var obj = {}; if (group["sakai:group-description"] && group["sakai:group-description"].length) { obj.description = group["sakai:group-description"]; } if (group["sakai:tags"] && group["sakai:tags"].length) { obj.tags = sakai.api.Util.formatTags(group["sakai:tags"]); } if (group.picture){ obj.picture = sakai.api.Groups.getProfilePicture(group); } obj.counts = group.counts; obj.contentType = "group"; obj.groupid = group["sakai:group-id"]; obj.title = group["sakai:group-title"]; if (obj.picture && obj.description && obj.tags) { picDescTags.push(obj); } else if (obj.picture && obj.description) { picDesc.push(obj); } else if (obj.picture && obj.tags) { picTags.push(obj); } else if (obj.description && obj.tags) { descTags.push(obj); } else if (obj.description) { desc.push(obj); } else if (obj.tags) { tags.push(obj); } else { noPic.push(obj); } }); var suggested = { contentType: "suggestedGroups", suggestions: picDescTags.concat(picDesc, picTags, descTags, desc, tags, noPic).splice(0,6) }; dataArr.push(suggested); }; var parseUsers = function(data, dataArr){ var hasPicAndTag = []; var hasPic = []; var hasTag = []; var noPicAndTag = []; sakai.api.User.getContacts(function() { $.each(data.users.results, function (index, user){ var obj = {}; obj.userid = user.profile.userid; obj.contentType = "user"; obj.displayName = sakai.api.User.getDisplayName(user.profile); obj.counts = user.profile.counts; user = user.profile.basic.elements; if (user["sakai:tags"] && user["sakai:tags"].value && user["sakai:tags"].value.length){ obj.tags = sakai.api.Util.formatTags(user["sakai:tags"].value); } if (user.aboutme){ obj.aboutme = user.aboutme.elements.aboutme.value; } if (user.picture && user.picture.value && user.picture.value.length){ obj.picture = $.parseJSON(user.picture.value); } // is the user a contact or pending contact if ($.grep(sakai.data.me.mycontacts, function(value, index){return value.target === obj.userid;}).length !== 0){ obj.connected = true; } if (obj.picture && obj.tags){ hasPicAndTag.push(obj); } else if (obj.picture) { hasPic.push(obj); } else if (obj.tags) { hasTag.push(obj); } else { noPicAndTag.push(obj); } }); var suggested = { contentType: "suggestedUsers", suggestions: hasPicAndTag.concat(hasPic, hasTag, noPicAndTag).splice(0, 8) }; dataArr.push(suggested); }); }; var parseData = function(data){ var dataArr = []; parseContent(data, dataArr, function(data, dataArr){ parseGroups(data, dataArr); parseUsers(data, dataArr); if (dataArr.length) { renderCarousel(dataArr); } }); }; var loadFeatured = function(){ var dataArr = { "content": false, "groups": false, "users": false }; var reqs = [ { url: "/var/search/pool/me/related-content.json", method: "GET", parameters: { "items": 11 } }, { url: "/var/contacts/related-contacts.json", method: "GET", parameters: { "items": 11 } }, { url: "/var/search/myrelatedgroups.json", method: "GET", parameters: { "items": 11 } } ]; sakai.api.Server.batch(reqs, function(success, data) { if (success) { //content dataArr.content = $.parseJSON(data.results[0].body); //users dataArr.users = $.parseJSON(data.results[1].body); //groups dataArr.groups = $.parseJSON(data.results[2].body); } parseData(dataArr); }); }; var doInit = function(){ // Begin CalCentral customization if (sakai.config.enabledCarousel) { loadFeatured(); } // End CalCentral customization }; doInit(); }; sakai.api.Widgets.widgetLoader.informOnLoad("carousel"); });
jonmhays/3akai-ux
devwidgets/carousel/javascript/carousel.js
JavaScript
apache-2.0
12,650
import getProp from 'lodash.get' import isEmpty from 'lodash.isempty' import moment from 'moment' import PouchDB from './PouchDB-client' import { getSkipass } from './bukovelAPI' const DB_NAME = 'skipasses' const db = new PouchDB(DB_NAME) const prepareToSave = obj => { const objToSave = { _id: getProp(obj, '_id', Date.now().toString()), updateDate: moment.utc().toJSON() } return Object.assign({}, obj, objToSave) } const get = id => { return db.find({ selector: { cardNumber: id } }) .then(result => { if (isEmpty(result.docs)) { return getAndUpdateToLatest(id) } return result.docs[0] }) .catch(getAndUpdateToLatest) } const getAll = () => { return db.allDocs({ include_docs: true }) .then(result => { return result.rows.map(row => row.doc) }) } const getAndUpdateToLatest = async (id) => { const skipass = await getSkipass(id) await save(skipass) return skipass } const hasSkipass = cardNumber => { return db.find({ selector: { cardNumber } }) .then(result => !isEmpty(result.docs)) } const save = skipass => { const skipassToSave = prepareToSave(skipass) return db.put(skipassToSave) .then(response => { return db.get(response.id) }) } export const remove = (skipass) => { return db.remove(skipass) } export { get, save, getAll, hasSkipass, getSkipass as getLatest }
blobor/skipass.site
src/app/data-access/skipassRepository.js
JavaScript
apache-2.0
1,413
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import '../../src/polyfills'; import {dev, initLogConstructor, setReportError} from '../../src/log'; import {reportError} from '../../src/error'; import {getCookie, setCookie} from '../../src/cookies'; import {getMode} from '../../src/mode'; import {isExperimentOn, toggleExperiment} from '../../src/experiments'; import {listenOnce} from '../../src/event-helper'; import {onDocumentReady} from '../../src/document-ready'; //TODO(@cramforce): For type. Replace with forward declaration. import '../../src/service/timer-impl'; initLogConstructor(); setReportError(reportError); const COOKIE_MAX_AGE_DAYS = 180; // 6 month /** * @typedef {{ * id: string, * name: string, * spec: string * }} */ let ExperimentDef; /** * This experiment is special because it uses a different mechanism that is * interpreted by the server to deliver a different version of the AMP * JS libraries. */ const CANARY_EXPERIMENT_ID = 'dev-channel'; /** @const {!Array<!ExperimentDef>} */ const EXPERIMENTS = [ // Canary (Dev Channel) { id: CANARY_EXPERIMENT_ID, name: 'AMP Dev Channel (more info)', spec: 'https://github.com/ampproject/amphtml/blob/master/' + 'README.md#amp-dev-channel', }, { id: 'ad-type-custom', name: 'Activates support for custom (self-serve) advertisements', spec: 'https://github.com/ampproject/amphtml/blob/master/ads/custom.md', }, { id: 'alp', name: 'Activates support for measuring incoming clicks.', spec: 'https://github.com/ampproject/amphtml/issues/2934', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/4005', }, { id: 'amp-access-server', name: 'AMP Access server side prototype', spec: '', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/4000', }, { id: 'amp-access-jwt', name: 'AMP Access JWT prototype', spec: '', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/4000', }, { id: 'amp-access-signin', name: 'AMP Access sign-in', spec: 'https://github.com/ampproject/amphtml/issues/4227', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/4226', }, { id: 'amp-auto-ads', name: 'AMP Auto Ads', spec: 'https://github.com/ampproject/amphtml/issues/6196', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/6217', }, { id: 'amp-auto-ads-adsense-holdout', name: 'AMP Auto Ads AdSense Holdout', spec: 'https://github.com/ampproject/amphtml/issues/6196', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/9247', }, { id: 'amp-google-vrview-image', name: 'AMP VR Viewer for images via Google VRView', spec: 'https://github.com/ampproject/amphtml/blob/master/extensions/' + 'amp-google-vrview-image/amp-google-vrview-image.md', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/3996', }, { id: 'amp-gwd-animation', name: 'AMP GWD Animation', spec: 'https://github.com/ampproject/amphtml/issues/9949', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/11238', }, { id: 'no-auth-in-prerender', name: 'Delay amp-access auth request until doc becomes visible.', spec: '', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/3824', }, { id: 'amp-share-tracking', name: 'AMP Share Tracking', spec: 'https://github.com/ampproject/amphtml/issues/3135', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/5167', }, { id: 'amp-viz-vega', name: 'AMP Visualization using Vega grammar', spec: 'https://github.com/ampproject/amphtml/issues/3991', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/4171', }, { id: 'amp-apester-media', name: 'AMP extension for Apester media (launched)', spec: 'https://github.com/ampproject/amphtml/issues/3233', cleanupIssue: 'https://github.com/ampproject/amphtml/pull/4291', }, { id: 'cache-service-worker', name: 'AMP Cache Service Worker', spec: 'https://github.com/ampproject/amphtml/issues/1199', }, { id: 'amp-lightbox-viewer', name: 'Enables a new lightbox experience via the `lightbox` attribute', spec: 'https://github.com/ampproject/amphtml/issues/4152', }, { id: 'amp-lightbox-a4a-proto', name: 'Allows the new lightbox experience to be used in A4A (prototype).', spec: 'https://github.com/ampproject/amphtml/issues/7743', }, { id: 'amp-lightbox-viewer-auto', name: 'Allows the new lightbox experience to automatically include some ' + 'elements without the need to manually add the `lightbox` attribute', spec: 'https://github.com/ampproject/amphtml/issues/4152', }, { id: 'amp-playbuzz', name: 'AMP extension for playbuzz items (launched)', spec: 'https://github.com/ampproject/amphtml/issues/6106', cleanupIssue: 'https://github.com/ampproject/amphtml/pull/6351', }, { id: 'alp-for-a4a', name: 'Enable redirect to landing page directly for A4A', spec: 'https://github.com/ampproject/amphtml/issues/5212', }, { id: 'ios-embed-wrapper', name: 'A new iOS embedded viewport model that wraps the body into' + ' a synthetic root (launched)', spec: '', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/5639', }, { id: 'chunked-amp', name: 'Split AMP\'s loading phase into chunks', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/5535', }, { id: 'font-display-swap', name: 'Use font-display: swap as the default for fonts.', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/11165', }, { id: 'amp-animation', name: 'High-performing keyframe animations in AMP.', spec: 'https://github.com/ampproject/amphtml/blob/master/extensions/' + 'amp-animation/amp-animation.md', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/5888', }, { id: 'variable-filters', name: 'Format to apply filters to analytics variables', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/2198', }, { id: 'pump-early-frame', name: 'Force all extensions to have the same release ' + 'as the main JS binary', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/8237', }, { id: 'version-locking', name: 'Force all extensions to have the same release ' + 'as the main JS binary', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/8236', }, { id: 'web-worker', name: 'Web worker for background processing', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/7156', }, { id: 'jank-meter', name: 'Display jank meter', }, { id: 'amp-fx-parallax', name: 'Amp extension for a parallax effect', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/7801', spec: 'https://github.com/ampproject/amphtml/issues/1443', }, { id: 'slidescroll-disable-css-snap', name: 'Slidescroll disable css snap', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/8195', spec: 'https://github.com/ampproject/amphtml/issues/7670', }, { id: '3p-use-ampcontext', name: 'Use AmpContext for window.context messaging', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/8239', spec: 'https://github.com/ampproject/amphtml/issues/6829', }, { id: 'as-use-attr-for-format', name: 'Use slot width/height attribute for AdSense size format', }, { id: 'input-debounced', name: 'A debounced input event for AMP actions', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/9413', spec: 'https://github.com/ampproject/amphtml/issues/9277', }, { id: 'amp-ima-video', name: 'IMA-integrated Video Player', }, { id: 'amp-sidebar 1.0', name: 'Amp sidebar 1.0 extension', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/9803', spec: 'https://github.com/ampproject/amphtml/blob/master/extensions/' + 'amp-sidebar/1.0/amp-sidebar-1.0.md', }, { id: 'user-error-reporting', name: 'Report error to publishers', spec: 'https://github.com/ampproject/amphtml/issues/6415', }, { id: 'disable-rtc', name: 'Disable AMP RTC', spec: 'https://github.com/ampproject/amphtml/issues/8551', }, { id: 'amp-position-observer', name: 'Amp extension for monitoring position of an element within viewport', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/10875', spec: 'https://github.com/ampproject/amphtml/blob/master/extensions/' + 'amp-position-observer/amp-position-observer.md', }, { id: 'inabox-position-api', name: 'Position API for foreign iframe', spec: 'https://github.com/ampproject/amphtml/issues/10995', }, { id: 'amp-story', name: 'Visual storytelling in AMP', spec: 'https://github.com/ampproject/amphtml/issues/11329', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/11475', }, { id: 'amp-story-desktop', name: 'A responsive desktop experience for the amp-story component', spec: 'https://github.com/ampproject/amphtml/issues/11714', cleanupIssue: 'https://github.com/ampproject/amphtml/issues/11715', }, ]; if (getMode().localDev) { EXPERIMENTS.forEach(experiment => { dev().assert(experiment.cleanupIssue, `experiment ${experiment.name} must` + ' have a `cleanupIssue` field.'); }); } /** * Builds the expriments tbale. */ function build() { const table = document.getElementById('experiments-table'); EXPERIMENTS.forEach(function(experiment) { table.appendChild(buildExperimentRow(experiment)); }); } /** * Builds one row of the experiments table. * @param {!ExperimentDef} experiment */ function buildExperimentRow(experiment) { const tr = document.createElement('tr'); tr.id = 'exp-tr-' + experiment.id; const tdId = document.createElement('td'); tdId.appendChild(buildLinkMaybe(experiment.id, experiment.spec)); tr.appendChild(tdId); const tdName = document.createElement('td'); tdName.appendChild(buildLinkMaybe(experiment.name, experiment.spec)); tr.appendChild(tdName); const tdOn = document.createElement('td'); tdOn.classList.add('button-cell'); tr.appendChild(tdOn); const button = document.createElement('button'); tdOn.appendChild(button); const buttonOn = document.createElement('div'); buttonOn.classList.add('on'); buttonOn.textContent = 'On'; button.appendChild(buttonOn); const buttonDefault = document.createElement('div'); buttonDefault.classList.add('default'); buttonDefault.textContent = 'Default on'; button.appendChild(buttonDefault); const buttonOff = document.createElement('div'); buttonOff.classList.add('off'); buttonOff.textContent = 'Off'; button.appendChild(buttonOff); button.addEventListener('click', toggleExperiment_.bind(null, experiment.id, experiment.name, undefined)); return tr; } /** * If link is available, builds the anchor. Otherwise, it'd return a basic span. * @param {string} text * @param {?string} link * @return {!Element} */ function buildLinkMaybe(text, link) { let element; if (link) { element = document.createElement('a'); element.setAttribute('href', link); element.setAttribute('target', '_blank'); } else { element = document.createElement('span'); } element.textContent = text; return element; } /** * Updates states of all experiments in the table. */ function update() { EXPERIMENTS.forEach(function(experiment) { updateExperimentRow(experiment); }); } /** * Updates the state of a single experiment. * @param {!ExperimentDef} experiment */ function updateExperimentRow(experiment) { const tr = document.getElementById('exp-tr-' + experiment.id); if (!tr) { return; } let state = isExperimentOn_(experiment.id) ? 1 : 0; if (self.AMP_CONFIG[experiment.id]) { state = 'default'; } tr.setAttribute('data-on', state); } /** * Returns whether the experiment is on or off. * @param {string} id * @return {boolean} */ function isExperimentOn_(id) { if (id == CANARY_EXPERIMENT_ID) { return getCookie(window, 'AMP_CANARY') == '1'; } return isExperimentOn(window, id); } /** * Toggles the experiment. * @param {string} id * @param {boolean=} opt_on */ function toggleExperiment_(id, name, opt_on) { const currentlyOn = isExperimentOn_(id); const on = opt_on === undefined ? !currentlyOn : opt_on; // Protect against click jacking. const confirmMessage = on ? 'Do you really want to activate the AMP experiment' : 'Do you really want to deactivate the AMP experiment'; showConfirmation_(`${confirmMessage}: "${name}"`, () => { if (id == CANARY_EXPERIMENT_ID) { const validUntil = Date.now() + COOKIE_MAX_AGE_DAYS * 24 * 60 * 60 * 1000; setCookie(window, 'AMP_CANARY', (on ? '1' : '0'), (on ? validUntil : 0), { // Set explicit domain, so the cookie gets send to sub domains. domain: location.hostname, allowOnProxyOrigin: true, }); // Reflect default experiment state. self.location.reload(); } else { toggleExperiment(window, id, on); } update(); }); } /** * Shows confirmation and calls callback if it's approved. * @param {string} message * @param {function()} callback */ function showConfirmation_(message, callback) { const container = dev().assert(document.getElementById('popup-container')); const messageElement = dev().assert(document.getElementById('popup-message')); const confirmButton = dev().assert( document.getElementById('popup-button-ok')); const cancelButton = dev().assert( document.getElementById('popup-button-cancel')); const unlistenSet = []; const closePopup = affirmative => { container.classList.remove('show'); unlistenSet.forEach(unlisten => unlisten()); if (affirmative) { callback(); } }; messageElement.textContent = message; unlistenSet.push(listenOnce(confirmButton, 'click', () => closePopup(true))); unlistenSet.push(listenOnce(cancelButton, 'click', () => closePopup(false))); container.classList.add('show'); } /** * Loads the AMP_CONFIG objects from whatever the v0.js is that the * user has (depends on whether they opted into canary), so that * experiment state can reflect the default activated experiments. */ function getAmpConfig() { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.addEventListener('load', () => { resolve(xhr.responseText); }); xhr.addEventListener('error', () => { reject(new Error(xhr.statusText)); }); // Cache bust, so we immediately reflect AMP_CANARY cookie changes. xhr.open('GET', '/v0.js?' + Math.random(), true); xhr.send(null); }).then(text => { const match = text.match(/self\.AMP_CONFIG=([^;]+)/); if (!match) { throw new Error('Can\'t find AMP_CONFIG in: ' + text); } // Setting global var to make standard experiment code just work. return self.AMP_CONFIG = JSON.parse(match[1]); }).catch(error => { console./*OK*/error('Error fetching AMP_CONFIG', error); return {}; }); } // Start up. getAmpConfig().then(() => { onDocumentReady(document, () => { build(); update(); }); });
vmarteev/amphtml
tools/experiments/experiments.js
JavaScript
apache-2.0
16,033
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {FixedLayer} from '../../src/service/fixed-layer'; import * as sinon from 'sinon'; describe('FixedLayer', () => { let sandbox; let documentApi; let vsyncApi; let vsyncTasks; let docBody, docElem; let element1; let element2; let element3; let allRules; beforeEach(() => { sandbox = sinon.sandbox.create(); allRules = {}; docBody = createElement('docBody'); docElem = createElement('docElem'); element1 = createElement('element1'); element2 = createElement('element2'); element3 = createElement('element3'); docBody.appendChild(element1); docBody.appendChild(element2); docBody.appendChild(element3); const invalidRule = createValidRule('#invalid', [element1, element3]); documentApi = { styleSheets: [ // Will be ignored due to being a link. { ownerNode: document.createElement('link'), cssRules: [invalidRule], }, // Will be ignored because it's disabled { ownerNode: createStyleNode(), disabled: true, cssRules: [invalidRule], }, // Will be ignored because it's a boilerplate { ownerNode: createStyleNode('amp-boilerplate'), cssRules: [invalidRule], }, // Will be ignored because it's a runtime { ownerNode: createStyleNode('amp-runtime'), cssRules: [invalidRule], }, // Will be ignored because it's an extension { ownerNode: createStyleNode('amp-extension', 'amp-fit-text'), cssRules: [invalidRule], }, // Valid stylesheet with amp-custom { ownerNode: createStyleNode('amp-custom'), cssRules: [ createValidRule('#amp-custom-rule1', [element1]), createValidRule('#amp-custom-rule2', [element1, element2]), createUnrelatedRule('#amp-custom-rule3', [element3]), { type: 4, cssRules: [ createValidRule('#amp-custom-media-rule1', [element1]), ], }, { type: 12, cssRules: [ createValidRule('#amp-custom-supports-rule1', [element2]), ], }, // Uknown rule. { type: 3, }, ], }, // Valid stylesheet without amp-custom { ownerNode: createStyleNode(), cssRules: [ createValidRule('#other-rule1', [element1]), createValidRule('#other-rule2', [element2]), createUnrelatedRule('#other-rule3', [element1, element3]), ], }, ], querySelectorAll: selector => { if (!allRules[selector]) { return null; } return allRules[selector].elements; }, contains: elem => { return (!!elem.parentElement); }, defaultView: { getComputedStyle: elem => { return { getPropertyValue: prop => { return elem.computedStyle[prop] || ''; }, }; }, }, createElement: name => { return createElement(name); }, documentElement: docElem, body: docBody, }; vsyncTasks = []; vsyncApi = { runPromise: task => { vsyncTasks.push(task); return Promise.resolve(); }, mutate: mutator => { vsyncTasks.push({mutate: mutator}); }, }; }); afterEach(() => { sandbox.restore(); }); function createElement(id) { const attrs = {}; const children = []; const elem = { id: id, toString: () => { return id; }, style: { top: '', bottom: '', position: '', opacity: '0.9', visibility: 'visible', }, computedStyle: { opacity: '0.9', visibility: 'visible', }, matches: () => true, compareDocumentPosition: other => { if (id < other.id) { return 0x0A; } return 0; }, getAttribute: name => { return attrs[name]; }, setAttribute: (name, value) => { attrs[name] = value; }, appendChild: child => { child.parentElement = elem; children.push(child); }, removeChild: child => { const index = children.indexOf(child); if (index != -1) { children.splice(index, 1); } child.parentElement = null; }, replaceChild: (newChild, oldChild) => { oldChild.parentElement = null; if (children.indexOf(oldChild) != -1) { children.splice(children.indexOf(oldChild), 1); } newChild.parentElement = elem; children.push(newChild); }, }; return elem; } function createStyleNode(attr, value) { const node = document.createElement('style'); if (attr) { node.setAttribute(attr, value || ''); } return node; } function createValidRule(selector, elements) { const rule = { type: 1, selectorText: selector, style: {position: 'fixed'}, elements: elements, }; if (allRules[selector]) { throw new Error('dup selector'); } allRules[selector] = rule; return rule; } function createUnrelatedRule(selector, elements) { const rule = { type: 1, selectorText: selector, style: {}, elements: elements, }; if (allRules[selector]) { throw new Error('dup selector'); } allRules[selector] = rule; return rule; } describe('no-transfer', () => { let fixedLayer; beforeEach(() => { fixedLayer = new FixedLayer(documentApi, vsyncApi, /* paddingTop */ 11, /* transfer */ false); fixedLayer.setup(); }); it('should initiale fixed layer to null', () => { expect(fixedLayer.fixedLayer_).to.be.null; }); it('should discover all potentials', () => { function expectFe(actual, expected) { expect(actual.id).to.equal(expected.id, `${expected.id} wrong`); expect(actual.element).to.equal(expected.element, `${expected.id}: wrong element`); expect(JSON.stringify(actual.selectors)) .to.equal(JSON.stringify(expected.selectors), `${expected.id}: wrong selectors`); } expect(fixedLayer.fixedElements_).to.have.length(2); expectFe(fixedLayer.fixedElements_[0], { id: 'F0', element: element1, selectors: [ '#amp-custom-rule1', '#amp-custom-rule2', '#amp-custom-media-rule1', '#other-rule1', ], }); expectFe(fixedLayer.fixedElements_[1], { id: 'F1', element: element2, selectors: [ '#amp-custom-rule2', '#amp-custom-supports-rule1', '#other-rule2', ], }); }); it('should add and remove element directly', () => { const updateStub = sandbox.stub(fixedLayer, 'update'); expect(fixedLayer.fixedElements_).to.have.length(2); // Add. fixedLayer.addElement(element3, '*'); expect(updateStub.callCount).to.equal(1); expect(fixedLayer.fixedElements_).to.have.length(3); const fe = fixedLayer.fixedElements_[2]; expect(fe.id).to.equal('F2'); expect(fe.element).to.equal(element3); expect(fe.selectors).to.deep.equal(['*']); // Remove. fixedLayer.removeElement(element3); expect(fixedLayer.fixedElements_).to.have.length(2); }); it('should remove node when disappeared from DOM', () => { docBody.removeChild(element1); expect(fixedLayer.fixedElements_).to.have.length(2); fixedLayer.update(); expect(fixedLayer.fixedElements_).to.have.length(1); }); it('should collect updates', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.equal(true); expect(state['F0'].top).to.equal(''); expect(state['F0'].zIndex).to.equal(''); expect(state['F1'].fixed).to.equal(false); }); it('should disregard non-fixed position', () => { element1.computedStyle['position'] = 'static'; element1.offsetWidth = 10; element1.offsetHeight = 10; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.equal(false); expect(state['F1'].fixed).to.equal(false); }); it('should disregard invisible element', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 0; element1.offsetHeight = 0; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.equal(false); expect(state['F1'].fixed).to.equal(false); }); it('should tolerate getComputedStyle = null', () => { // See #3096 and https://bugzilla.mozilla.org/show_bug.cgi?id=548397 documentApi.defaultView.getComputedStyle = () => null; element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.equal(false); expect(state['F0'].transferrable).to.equal(false); expect(state['F0'].top).to.equal(''); expect(state['F0'].zIndex).to.equal(''); expect(state['F1'].fixed).to.equal(false); }); it('should mutate element to fixed without top', () => { const fe = fixedLayer.fixedElements_[0]; fixedLayer.mutateFixedElement_(fe, 1, { fixed: true, top: '', }); expect(fe.fixedNow).to.be.true; expect(fe.element.style.top).to.equal(''); expect(fixedLayer.fixedLayer_).to.be.null; }); it('should mutate element to fixed with top', () => { const fe = fixedLayer.fixedElements_[0]; fixedLayer.mutateFixedElement_(fe, 1, { fixed: true, top: '17px', }); expect(fe.fixedNow).to.be.true; expect(fe.element.style.top).to.equal('calc(17px + 11px)'); }); it('should reset top upon being removed from fixedlayer', () => { expect(fixedLayer.fixedElements_).to.have.length(2); // Add. fixedLayer.addElement(element3, '*'); expect(fixedLayer.fixedElements_).to.have.length(3); const fe = fixedLayer.fixedElements_[2]; expect(fe.id).to.equal('F2'); expect(fe.element).to.equal(element3); expect(fe.selectors).to.deep.equal(['*']); fixedLayer.mutateFixedElement_(fe, 1, { fixed: true, top: '17px', }); expect(fe.fixedNow).to.be.true; expect(fe.element.style.top).to.equal('calc(17px + 11px)'); // Remove. fixedLayer.vsync_ = { mutate: function(callback) { callback(); }, }; fixedLayer.removeElement(element3); expect(fixedLayer.fixedElements_).to.have.length(2); expect(element3.style.top).to.equal(''); }); it('should mutate element to non-fixed', () => { const fe = fixedLayer.fixedElements_[0]; fe.fixedNow = true; fe.element.style.top = '27px'; fixedLayer.mutateFixedElement_(fe, 1, { fixed: false, top: '17px', }); expect(fe.fixedNow).to.be.false; expect(fe.element.style.top).to.equal(''); }); }); describe('with-transfer', () => { let fixedLayer; beforeEach(() => { fixedLayer = new FixedLayer(documentApi, vsyncApi, /* paddingTop */ 11, /* transfer */ true); fixedLayer.setup(); }); it('should initiale fixed layer to null', () => { expect(fixedLayer.transfer_).to.be.true; expect(fixedLayer.fixedLayer_).to.be.null; }); it('should collect turn off transferrable', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.be.true; expect(state['F0'].transferrable).to.equal(false); expect(state['F1'].fixed).to.equal(false); }); it('should collect turn on transferrable with top = 0', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; element1.computedStyle['top'] = '0px'; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.be.true; expect(state['F0'].transferrable).to.equal(true); expect(state['F0'].top).to.equal('0px'); }); it('should collect turn off transferrable with top != 0', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; element1.computedStyle['top'] = '2px'; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.be.true; expect(state['F0'].transferrable).to.equal(false); expect(state['F0'].top).to.equal('2px'); }); it('should collect turn on transferrable with bottom = 0', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; element1.computedStyle['bottom'] = '0px'; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.be.true; expect(state['F0'].transferrable).to.equal(true); }); it('should collect turn off transferrable with bottom != 0', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; element1.computedStyle['bottom'] = '2px'; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.be.true; expect(state['F0'].transferrable).to.equal(false); }); it('should collect z-index', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; element1.computedStyle['z-index'] = '101'; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.be.true; expect(state['F0'].zIndex).to.equal('101'); }); it('should transfer element', () => { const fe = fixedLayer.fixedElements_[0]; fixedLayer.mutateFixedElement_(fe, 1, { fixed: true, transferrable: true, zIndex: '11', }); expect(fe.fixedNow).to.be.true; expect(fe.placeholder).to.exist; expect(fe.placeholder.style['display']).to.equal('none'); expect(fe.element.parentElement).to.equal(fixedLayer.fixedLayer_); expect(fe.element.style['pointer-events']).to.equal('initial'); expect(fe.element.style['zIndex']).to.equal('calc(10001 + 11)'); expect(fixedLayer.fixedLayer_).to.exist; expect(fixedLayer.fixedLayer_.style['pointerEvents']).to.equal('none'); }); it('should ignore transfer when non-transferrable', () => { const fe = fixedLayer.fixedElements_[0]; fixedLayer.mutateFixedElement_(fe, 1, { fixed: true, transferrable: false, }); expect(fe.fixedNow).to.be.true; expect(fe.placeholder).to.not.exist; expect(fixedLayer.fixedLayer_).to.not.exist; expect(fe.element.parentElement).to.not.equal(fixedLayer.fixedLayer_); }); it('should return transfered element if it no longer matches', () => { const fe = fixedLayer.fixedElements_[0]; fe.element.matches = () => false; fixedLayer.mutateFixedElement_(fe, 1, { fixed: true, transferrable: true, zIndex: '11', }); expect(fe.fixedNow).to.be.true; expect(fe.placeholder).to.exist; expect(fixedLayer.fixedLayer_).to.exist; expect(fe.element.parentElement).to.not.equal(fixedLayer.fixedLayer_); expect(fe.placeholder.parentElement).to.be.null; expect(fe.element.style.zIndex).to.equal(''); }); it('should remove transfered element if it no longer exists', () => { const fe = fixedLayer.fixedElements_[0]; // Add. fixedLayer.mutateFixedElement_(fe, 1, { fixed: true, transferrable: true, zIndex: '11', }); expect(fe.fixedNow).to.be.true; expect(fe.placeholder).to.exist; expect(fe.element.parentElement).to.equal(fixedLayer.fixedLayer_); expect(fixedLayer.fixedLayer_).to.exist; // Remove from DOM. fe.element.parentElement.removeChild(fe.element); fixedLayer.mutateFixedElement_(fe, 1, { fixed: false, transferrable: false, }); expect(fe.fixedNow).to.be.false; expect(fe.placeholder.parentElement).to.not.exist; }); it('should disregard transparent element', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; element1.computedStyle['top'] = '0px'; element1.computedStyle['opacity'] = '0'; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.equal(true); expect(state['F0'].transferrable).to.equal(false); }); it('should force transfer for visibility=hidden element', () => { element1.computedStyle['position'] = 'fixed'; element1.offsetWidth = 10; element1.offsetHeight = 10; element1.computedStyle['top'] = '0px'; element1.computedStyle['visibility'] = 'hidden'; expect(vsyncTasks).to.have.length(1); const state = {}; vsyncTasks[0].measure(state); expect(state['F0'].fixed).to.equal(true); expect(state['F0'].transferrable).to.equal(true); }); }); });
mkhatib/amphtml
test/functional/test-fixed-layer.js
JavaScript
apache-2.0
19,056
/* @flow */ export { BUTTON_RENDER as default } from './webpack.config';
mstuart/paypal-checkout
webpack.button.render.config.js
JavaScript
apache-2.0
74
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import iconMessages from './icons/en-US'; export default { IndexFilters: { // Did I understand the interpolation syntax? filters: `{quantity, plural, =0 {нет фильтров} =1 {один фильтр} other {# фильтры} }`, }, ...iconMessages, Active: 'Активный', Activate: 'Активировать', Activated: 'Активирован', Add: 'Добавить', add: 'добавить', Alerts: 'Уведомления', All: 'Все', ampm: 'ампм', // context? Arc: 'Дуга', AxisLabel: '{orientation} Ось', area: 'зона', Bar: 'Бар', // context? bar: 'бар', // context? Blank: 'Пустой', Box: 'Ящик', // context? Carousel: 'Карусель', Category: 'Категория', Circle: 'Круг', Chart: 'Диаграмма', Children: 'Дети', Clear: 'Очистить', Cleared: 'Очищенный', Close: 'Закрыть', 'Close Menu': 'Закрыть меню', Completed: 'Завершенный', 'Connects With': 'Соединяется с', created: 'созданный', Critical: 'Критический', 'Currently Active': 'Активный', 'Date Selector': 'Выбор даты', 'Date Time Icon': 'Выбор даты и времени', day: 'день', Disabled: 'Отключен', Distribution: 'Распределение', Email: 'Эл. адрес', 'Enter Select': 'Нажмите enter чтобы выбрать его', Error: 'Ошибка', Filter: 'Фильтр', Footer: 'Нижний колонтитул', // Not 100% sure on this one Grommet: 'Громмет', HotSpotsLabel: 'HotSpots: нажмите клавиши со стрелками, чтобы взаимодействовать с ним.', 'GraphValues': 'График имеет {count} элементы. Наивысшее - {highest}, а наименьшее - {smallest}', hour: 'час', 'Grommet Logo': 'Громмет Лого', Layer: 'Слой', List: 'Список', line: 'линия', Loading: 'Загружается', loginInvalidPassword: 'Пожалуйста, укажите имя и пароль пользователя.', 'Log In': 'Авторизоваться', Logout: 'Выйти', 'Main Content': 'Основное содержание', Max: 'Максимум', Menu: 'Меню', Meter: 'метр', Min: 'Минимум', // assming 'minimum' minute: 'минута', model: 'модель', modified: 'модифицирован', monitor: 'монитор', month: 'месяц', 'Multi Select': 'Выбор из нескольких вариантов', Name: 'Имя', 'Navigation Help': 'Используйте клавиши со стрелками для навигации', 'Next Month': 'Следующий месяц', 'Next Slide': 'Следующий слайд', 'No Relationship': 'Нет отношений', 'Notification': 'Уведомление', OK: 'ОК', Open: 'Открыть', Parent: 'Родитель', Parents: 'Родители', Parts: 'Части', Part: 'Часть', Password: 'Пароль', 'Previous Month': 'Предыдущий Месяц', 'Previous Slide': 'Предыдущая Слайд', 'Previous Tiles': 'Предыдущие Плитки', 'Remember me': 'Запомни меня', 'Range Start': 'Начало Диапазона', 'Range End': 'Конец Диапазона', Resource: 'Ресурс', Running: 'Работает', // "working" -- fitting in context? Search: 'Поиск', 'Match Results': `{count, plural, =0 {Нет совпадения} one {Есть одно совпадения} other {Есть # совпадений} }`, second: 'второй', // as in sequence (number #2), not as in time (hour/minute/second) (might need conjugation based on context) 'Select Icon': 'Открыть селектор', // "open selector" Selected: 'Selected', 'Selected Multiple': `{count, plural, =0 {none} one {# значение} other {# значения} }`, 'Skip to': 'Перейти к', 'Slide Number': ' Слайд {slideNumber}', Sort: 'Сортировать', Spinning: 'Прядильный', // not 100% sure on this Spiral: 'Спираль', State: 'Состояние', Status: 'Статус', Subtract: 'Вычитать', SunBurst: 'SunBurst', // context? 'Tab Contents': 'Содержимое вкладки {activeTitle}', Table: 'Таблица', Tasks: 'Задания', Tiles: 'Плитки', Time: 'Время', Title: 'Заглавие', Today: 'Cегодня', Topology: 'Топология', Total: 'Всего', Threshold: 'Порог', Unknown: 'Неизвестный', Username: 'Имя пользователя', uri: 'унифицированный идентификатор ресурса', // no common abbreviation Value: 'Стоимость', Warning: 'Предупреждение', year: 'год' };
odedre/grommet-final
src/js/messages/ru-RU.js
JavaScript
apache-2.0
5,144
/* * Web Experience Toolkit (WET) / Boîte à outils de l"expérience Web (BOEW) * wet-boew.github.io/wet-boew/License-en.html / wet-boew.github.io/wet-boew/Licence-fr.html */ /* ----- Polish dictionary (il8n) --- */ ( function( wb ) { "use strict"; /* main index */ wb.i18nDict = { "lang-code": "pl", "lang-native": "Język polski", add: "Ddać", all: "Wszystko", tphp: "Góra strony", load: "ładowanie ...", process: "przetwarzanie ...", srch: "Szukaj", "no-match": "Nie znaleziono odpowiedników", matches: { mixin: "Znaleziono [MIXIN] odpowiedników" }, current: "(bieżący)", hide: "Ukryj", err: "Błąd", colon: ":", hyphen: " - ", "full-stop": ".", "comma-space": ", ", space: "&#32;", start: "Rozpocznij", stop: "Zatrzymaj", back: "Wstecz", cancel: "Anuluj", "min-ago": "minutę temu", "coup-mins": "kilka minut temu", "mins-ago": { mixin: "[MIXIN] minut temu" }, "hour-ago": "godzinę temu", "hours-ago": { mixin: "[MIXIN] godzin temu" }, "days-ago": { mixin: "[MIXIN} dni temu" }, yesterday: "wczoraj", nxt: "Następny", "nxt-r": "Następny (klawisz strzałki w prawo)", prv: "Poprzedni", "prv-l": "Poprzedni (klawisz strzałka w lewo)", first: "Pierwszy", last: "Ostatni", page: "Page", "srch-menus": "Wyszukaj i menu", email: "Email", "menu-close": "Zamknij menu", "overlay-close": "Zamknij nakładkę", "esc-key": "(klawisz Esc)", show: "Pokaż", /* Tabbed interface */ "tab-rot": { off: "Zatrzymaj przewijanie zakładek", on: "Rozpocznij przewijanie zakładek" }, "tab-list": "Lista zakładek", "tab-pnl-end1": "Koniec tego panelu zakładek.", "tab-pnl-end2": "Powrót do listy zakładek", "tab-pnl-end3": "lub kontynuuj do końca strony.", "tab-play": "Odtwarzanie", /* Multimedia player */ "mmp-play": "Odtwarzanie", pause: "Pauza", open: "Otwórz", close: "Zamknij", volume: "Głośność", mute: { on: "Bez dźwięku", off: "Przywróć dźwięk" }, cc: { off: "Ukryj podpisy", on: "Pokaż podpisy" }, "cc-err": "Błąd w ładowaniu podpisów", adesc: { on: "Włącz informację audio", off: "Wyłącz informację audio" }, pos: "Aktualna pozycja:", dur: "Czas całkowity:", /* Share widget */ "shr-txt": "Prześlij", "shr-pg": " tę stronę", "shr-vid": " ten film", "shr-aud": " audiofile", "shr-hnt": " do {s} ", "shr-disc": "Nie wyrażamy bezposrednio lub pośrednio poparcia dla żadnych produktów ani usług.", /* Form validation */ "frm-nosubmit": "Nie można było wysłać formularza, ponieważ ", "errs-fnd": " znaleziono błędy", "err-fnd": " znaleziono błąd", /* Date picker */ "date-hide": "Ukryj kalendarz", "date-show": "Proszę wybrać datę z kalendarza:", "date-sel": "Wybrany", /* Calendar */ days: [ "Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota" ], mnths: [ "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień" ], cal: "Kalendarz", "cal-format": "<span class='wb-inv'>{ddd}, {M} </span>{d}<span class='wb-inv'>, {Y}</span>", currDay: "(Bieżący dzień)", "cal-goToLnk": "Idź do<span class=\"wb-inv\"> miesiąca w roku</span>", "cal-goToTtl": "Idź do miesiąca w roku", "cal-goToMnth": "Miesiąc:", "cal-goToYr": "Rok:", "cal-goToBtn": "Przejdź", prvMnth: "Poprzedni miesiąc: ", nxtMnth: "Następny miesiąc: ", /* Lightbox */ "lb-curr": "Pozycja %curr% z %total%", "lb-xhr-err": "Nie udało się załadować treści.", "lb-img-err": "Nie udało się załadować obrazu.", /* Charts widget */ "tbl-txt": "Tabela", "tbl-dtls": "Wykres. Szczegóły w tabeli poniżej.", /* Session timeout */ "st-to-msg-bgn": "Twoja sesja wygaśnie automatycznie w #min# min #sec# sek.", "st-to-msg-end": "Wybierz \"Kontynuuj sesję\" przedłużyć sesję.", "st-msgbx-ttl": "Ostrzeżenie: limit czasu sesji", "st-alrdy-to-msg": "Niestety sesja już się skończyła. Zaloguj się ponownie.", "st-btn-cont": "Kontynuuj sesji", "st-btn-end": "Koniec sesji teraz", /* Toggle details */ "td-toggle": "Wyłącz wszystko", "td-open": "Rozwiń wszystko", "td-close": "Zwiń wszystko", "td-ttl-open": "Rozwiń wszystkie sekcje zawartości", "td-ttl-close": "Zwiń wszystkie sekcje zawartości", /* Table enhancement */ sortAsc: ": włączyć dla sortowania rosnąco", sortDesc: ": włączyć dla sortowania malejąco", emptyTbl: "Nie ma danych w tabeli", infoEntr: "Wyświetlono _START_ do _END_ z _TOTAL_ pozycji", infoEmpty: "Wyświetlono 0 do 0 z 0 pozycji", infoFilt: "(filtrowane z _MAX_ wszystkich wpisów)", info1000: "&#160;", lenMenu: "Pokaż _MENU_ wpisów", filter: "Filtruj pozycje", /* Geomap */ "geo-mapctrl": "@geo-mapctrl@", "geo-zmin": "Powiększ", "geo-zmout": "Pomniejsz", "geo-zmwrld": "Powiększenie do zasięgu mapy", "geo-zmfeat": "Powiększ do elementu", "geo-sclln": "skala mapy", "geo-msepos": "Szerokość i długość geograficzna kursora myszy", "geo-ariamap": "Obiekt na mapie. Opisy funkcji na mapie są w tabeli poniżej.", "geo-ally": "<strong>Dla użytkowników klawiatury:</strong> Kiedy mapa jest w centrum, używaj klawiszy strzałek, aby przesunąć mapę oraz klawiszy plus i minus, aby ją powiększyć lub zmniejszyć. Klawisze strzałek nie będą przesuwać mapy po powiększeniu jej do granicy mapy.", "geo-allyttl": "Instrukcje: nawigacja mapy", "geo-tgllyr": "Przełączyć wyświetlanie warstwy", "geo-hdnlyr": "Warstwa ta jest obecnie ukryta.", "geo-bmapurl": "http://geoappext.nrcan.gc.ca/arcgis/rest/services/BaseMaps/CBMT_CBCT_GEOM_3978/MapServer/WMTS/tile/1.0.0/BaseMaps_CBMT3978/{Style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpg", "geo-bmapttl": "BaseMaps_CBMT3978", "geo-bmapurltxt": "http://geoappext.nrcan.gc.ca/arcgis/rest/services/BaseMaps/CBMT_TXT_3978/MapServer/WMTS/tile/1.0.0/BaseMaps_CBMT3978/{Style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpg", "geo-attrlnk": "http://geogratis.gc.ca/geogratis/CBM_CBC?lang=en", "geo-attrttl": "GeoGratis - Kanada baza map (tylko w języku angielskim lub francuskim)", "geo-sel": "Wybrać", "geo-lblsel": "Wybierz element na mapie", "geo-locurl-geogratis": "http://geogratis.gc.ca/services/geolocation/en/locate", "geo-loc-placeholder": "Podać nazwę miejscowości&#44; kod pocztowy&#44; adres (pocztowy)&#44; liczba NTS ...", "geo-loc-label": "Lokalizacja", "geo-aoi-north": "Północ", "geo-aoi-east": "Wschód", "geo-aoi-south": "Południe", "geo-aoi-west": "Zachód", "geo-aoi-instructions": "Narysuj pole na mapie lub wprowadź współrzędne poniżej i kliknij na przycisk \"Dodaj\".", "geo-aoi-btndraw": "Rysować", "geo-aoi-btnclear": "Usunąć", "geo-geoloc-btn": "Powiększyć się do bieżącej lokalizacji", "geo-geoloc-fail": "Lokalizacja nie powiodło się. Proszę upewnić się, że usługi lokalizacyjne są włączone.", "geo-geoloc-uncapable": "Lokalizacja nie jest obsługiwany przez przeglądarkę.", "geo-lgnd-grphc": "Grafika Legenda warstwy mapy.", /* Disable/enable WET plugins and polyfills */ "wb-disable": "Podstawowa wersja HTML", "wb-enable": "Wersja standardowa", /* Dismissable content */ "dismiss": "Dismiss", /* Template */ "tmpl-signin": "Zaloguj się" }; } )( wb ); wb.doc.one( "formLanguages.wb", function() { /* * Translated default messages for the jQuery validation plugin. * Locale: PL (Polish; język polski, polszczyzna) */ $.extend( $.validator.messages, { required: "To pole jest wymagane.", remote: "Proszę o wypełnienie tego pola.", email: "Proszę o podanie prawidłowego adresu email.", url: "Proszę o podanie prawidłowego URL.", date: "Proszę o podanie prawidłowej daty.", dateISO: "Proszę o podanie prawidłowej daty (ISO).", number: "Proszę o podanie prawidłowej liczby.", digits: "Proszę o podanie samych cyfr.", creditcard: "Proszę o podanie prawidłowej karty kredytowej.", equalTo: "Proszę o podanie tej samej wartości ponownie.", extension: "Proszę o podanie wartości z prawidłowym rozszerzeniem.", maxlength: $.validator.format( "Proszę o podanie nie więcej niż {0} znaków." ), minlength: $.validator.format( "Proszę o podanie przynajmniej {0} znaków." ), rangelength: $.validator.format( "Proszę o podanie wartości o długości od {0} do {1} znaków." ), range: $.validator.format( "Proszę o podanie wartości z przedziału od {0} do {1}." ), max: $.validator.format( "Proszę o podanie wartości mniejszej bądź równej {0}." ), min: $.validator.format( "Proszę o podanie wartości większej bądź równej {0}." ), pattern: $.validator.format( "Pole zawiera niedozwolone znaki." ) } ); });
gmyx/CSHealthCheck
GCDOCS Health Check/wet-boew/js/i18n/pl.js
JavaScript
apache-2.0
8,701
import styled from 'styled-components' import Atomic from '../style/atomic' import { colours } from '../style' export const Error = styled.div` color: ${ colours.error }; font-style: italic; border: 2px dotted ${ colours.error }; border-radius: 4px; ${ ({ atomic }) => Atomic({ ...Error.default.atomic, ...atomic }) } &:before { content: '😫'; margin-right: 10px; font-style: normal; } ` Error.default = { atomic: { fs: 4, m: 4, p: 4, }, }
ShandyClub/shandy-club-app
app/universal/shared/components/error.js
JavaScript
apache-2.0
489
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. (function($, cloudStack) { cloudStack.dialog = { /** * Error message form * * Returns callback, that can be plugged into a standard data provider response */ error: function(callback) { return function(args) { var message = args.message ? args.message : args; if (message) cloudStack.dialog.notice({ message: message }); if (callback) callback(); }; }, /** * Dialog with form */ createForm: function(args) { var $formContainer = $('<div>').addClass('form-container'); var $message = $('<span>').addClass('message').appendTo($formContainer).html( _l(args.form.desc) ); var $form = $('<form>').appendTo($formContainer) .submit(function() { $(this).closest('.ui-dialog').find('button.ok').click(); return false; }); var createLabel = _l(args.form.createLabel); var $submit = $('<input>') .attr({ type: 'submit' }) .hide() .appendTo($form); // Render fields and events var fields = $.map(args.form.fields, function(value, key) { return key; }) $(fields).each(function() { var key = this; var field = args.form.fields[key]; var $formItem = $('<div>') .addClass('form-item') .attr({ rel: key }); if (field.hidden || field.isHidden) $formItem.hide(); $formItem.appendTo($form); //Handling Escape KeyPress events /* $('.ui-dialog').keypress(function(event) { if ( event.which == 27 ) { event.stopPropagation(); } }); $(document).ready(function(){ $('.ui-dialog').keydown(function(event) { if(event.keyCode == 27) { alert("you pressed the Escape key"); event.preventdefault(); } }) }); $(':ui-dialog').dialog({ closeOnEscape: false }); */ // Label field //if( field.label == 'label.network.offering' || field.label == 'label.guest.gateway') // debugger; var $name = $('<div>').addClass('name') .appendTo($formItem) .append( $('<label>').html(_l(field.label) + ':') ); // red asterisk var $astersikSpan = $('<span>').addClass('field-required').html('*'); $name.find('label').prepend($astersikSpan); if (field.validation == null || field.validation.required == false) { $astersikSpan.hide(); } // Tooltip description if (field.desc) { $formItem.attr({ title: _l(field.desc) }); } // Input area var $value = $('<div>').addClass('value') .appendTo($formItem); var $input, $dependsOn, selectFn, selectArgs; var dependsOn = $.isArray(field.dependsOn) ? field.dependsOn : [field.dependsOn] ; //now an array // Depends on fields if (dependsOn.length) { $.each(dependsOn, function(key, value){ var dependsOn = value; $formItem.attr('depends-on-'+value, dependsOn); $dependsOn = $form.find('input, select').filter(function() { return $(this).attr('name') === dependsOn; }); if ($dependsOn.is('[type=checkbox]')) { var isReverse = args.form.fields[dependsOn].isReverse; // Checkbox $dependsOn.bind('click', function(event) { var $target = $(this); var $dependent = $target.closest('form').find('[depends-on-' + value + '=\'' + dependsOn + '\']'); if (($target.is(':checked') && !isReverse) || ($target.is(':unchecked') && isReverse)) { $dependent.css('display', 'inline-block'); $dependent.each(function() { if ($(this).find('select').data('dialog-select-fn')) { $(this).find('select').data('dialog-select-fn')(); } }); } else if (($target.is(':unchecked') && !isReverse) || ($target.is(':checked') && isReverse)) { $dependent.hide(); } $dependent.find('input[type=checkbox]').click(); if (!isReverse) { $dependent.find('input[type=checkbox]').attr('checked', false); } else { $dependent.find('input[type=checkbox]').attr('checked', true); } return true; }); // Show fields by default if it is reverse checkbox if (isReverse) { $dependsOn.click(); } }; }); } // Determine field type of input if (field.select) { selectArgs = { context: args.context, response: { success: function(args) { $(args.data).each(function() { var id = this.id; var description = this.description; if (args.descriptionField) description = this[args.descriptionField]; else description = this.description; var $option = $('<option>') .appendTo($input) .val(_s(id)) .html(_s(description)); }); if (field.defaultValue) { $input.val(_s(field.defaultValue)); } $input.trigger('change'); } } }; selectFn = field.select; $input = $('<select>') .attr({ name: key }) .data('dialog-select-fn', function(args) { selectFn(args ? $.extend(true, {}, selectArgs, args) : selectArgs); }) .appendTo($value); // Pass form item to provider for additional manipulation $.extend(selectArgs, { $select: $input }); if (dependsOn.length) { $.each(dependsOn, function(key, value){ var dependsOn = value; $dependsOn = $input.closest('form').find('input, select').filter(function() { return $(this).attr('name') === dependsOn; }); $dependsOn.bind('change', function(event) { var $target = $(this); if (!$dependsOn.is('select')) return true; var dependsOnArgs = {}; $input.find('option').remove(); if (!$target.children().size()) return true; dependsOnArgs[dependsOn] = $target.val(); selectFn($.extend(selectArgs, dependsOnArgs)); return true; }); if (!$dependsOn.is('select')) { selectFn(selectArgs); } }); } else { selectFn(selectArgs); } } else if (field.isBoolean) { if (field.multiArray) { $input = $('<div>') .addClass('multi-array').addClass(key).appendTo($value); $.each(field.multiArray, function(itemKey, itemValue) { $input.append( $('<div>').addClass('item') .append( $.merge( $('<div>').addClass('name').html(_l(itemValue.label)), $('<div>').addClass('value').append( $('<input>').attr({ name: itemKey, type: 'checkbox' }).appendTo($value) ) ) ) ); }); } else { $input = $('<input>').attr({ name: key, type: 'checkbox' }).appendTo($value); if (field.isChecked) { $input.attr('checked', 'checked'); } else { // This is mainly for IE compatibility setTimeout(function() { $input.attr('checked', false); }, 100); } } } else if (field.dynamic) { // Generate a 'sub-create-form' -- append resulting fields $input = $('<div>').addClass('dynamic-input').appendTo($value); $form.hide(); field.dynamic({ response: { success: function(args) { var form = cloudStack.dialog.createForm({ noDialog: true, form: { title: '', fields: args.fields } }); var $fields = form.$formContainer.find('.form-item').appendTo($input); $form.show(); // Form should be slightly wider $form.closest(':ui-dialog').dialog('option', { position: 'center',closeOnEscape: false }); } } }); } else if(field.isTextarea) { $input = $('<textarea>').attr({ name: key }).appendTo($value); if (field.defaultValue) { $input.val(field.defaultValue); } } else { // Text field if (field.range) { $input = $.merge( // Range start $('<input>').attr({ type: 'text', name: field.range[0] }), // Range end $('<input>').attr({ type: 'text', name: field.range[1] }) ).appendTo( $('<div>').addClass('range-edit').appendTo($value) ); $input.wrap($('<div>').addClass('range-item')); } else { $input = $('<input>').attr({ name: key, type: field.password || field.isPassword ? 'password' : 'text' }).appendTo($value); if (field.defaultValue) { $input.val(field.defaultValue); } if (field.id) { $input.attr('id', field.id); } } $input.addClass("disallowSpecialCharacters"); } if(field.validation != null) $input.data('validation-rules', field.validation); else $input.data('validation-rules', {}); var fieldLabel = field.label; var inputId = $input.attr('id') ? $input.attr('id') : fieldLabel.replace(/\./g,'_'); $input.attr('id', inputId); $name.find('label').attr('for', inputId); }); var getFormValues = function() { var formValues = {}; $.each(args.form.fields, function(key) {}); }; // Setup form validation $formContainer.find('form').validate(); $formContainer.find('input, select').each(function() { if ($(this).data('validation-rules')) { $(this).rules('add', $(this).data('validation-rules')); } else { $(this).rules('add', {}); } }); $form.find('select').trigger('change'); var complete = function($formContainer) { var $form = $formContainer.find('form'); var data = cloudStack.serializeForm($form); if (!$formContainer.find('form').valid()) { // Ignore hidden field validation if ($formContainer.find('input.error:visible, select.error:visible').size()) { return false; } } args.after({ data: data, ref: args.ref, // For backwards compatibility; use context context: args.context, $form: $form }); return true; }; if (args.noDialog) { return { $formContainer: $formContainer, completeAction: complete }; } return $formContainer.dialog({ dialogClass: 'create-form', closeOnEscape: false, width: 400, title: _l(args.form.title), open: function() { if (args.form.preFilter) { args.form.preFilter({ $form: $form, context: args.context }); } }, buttons: [ { text: createLabel ? createLabel : _l('label.ok'), 'class': 'ok', click: function() { if (!complete($formContainer)) { return false; } $('div.overlay').remove(); $formContainer.remove(); $(this).dialog('destroy'); return true; } }, { text: _l('label.cancel'), 'class': 'cancel', click: function() { $('div.overlay').remove(); $formContainer.remove(); $(this).dialog('destroy'); } } ] }).closest('.ui-dialog').overlay(); }, /** * to change a property(e.g. validation) of a createForm field after a createForm is rendered */ createFormField: { validation: { required: { add: function($formField) { var $input = $formField.find('input, select'); var validationRules = $input.data('validation-rules'); if(validationRules == null || validationRules.required == null || validationRules.required == false) { $formField.find('.name').find('label').find('span.field-required').css('display', 'inline'); //show red asterisk if(validationRules == null) validationRules = {}; validationRules.required = true; $input.data('validation-rules', validationRules); $input.rules('add', { required: true }); } }, remove: function($formField) { var $input = $formField.find('input, select'); var validationRules = $input.data('validation-rules'); if(validationRules != null && validationRules.required != null && validationRules.required == true) { $formField.find('.name').find('label').find('span.field-required').hide(); //hide red asterisk delete validationRules.required; $input.data('validation-rules', validationRules); $input.rules('remove', 'required'); $formField.find('.value').find('label.error').hide(); } } } } }, /** * Confirmation dialog */ confirm: function(args) { return $( $('<span>').addClass('message').html( _l(args.message) ) ).dialog({ title: _l('label.confirmation'), dialogClass: 'confirm', closeOnEscape: false, zIndex: 5000, buttons: [ { text: _l('label.no'), 'class': 'cancel', click: function() { $(this).dialog('destroy'); $('div.overlay').remove(); if (args.cancelAction) { args.cancelAction(); } } }, { text: _l('label.yes'), 'class': 'ok', click: function() { args.action(); $(this).dialog('destroy'); $('div.overlay').remove(); } } ] }).closest('.ui-dialog').overlay(); }, /** * Notice dialog */ notice: function(args) { return $( $('<span>').addClass('message').html( _l(args.message) ) ).dialog({ title: _l('label.status'), dialogClass: 'notice', closeOnEscape: false, zIndex: 5000, buttons: [ { text: _l('Close'), 'class': 'close', click: function() { $(this).dialog('destroy'); if (args.clickAction) args.clickAction(); } } ] }); } }; })(window.jQuery, window.cloudStack);
argv0/cloudstack
ui/scripts/ui/dialog.js
JavaScript
apache-2.0
17,101
const JSONPUtil = { request: function (url) { return new Promise(function (resolve, reject) { var callback = `jsonp_${Date.now().toString(16)}`; var script = document.createElement("script"); // Add jsonp callback window[callback] = function handleJSONPResponse(data) { if (data != null) { return resolve(data); } reject(new Error("Empty response")); }; // Add clean up method script.cleanUp = function () { if (this.parentNode) { this.parentNode.removeChild(script); } }; // Add handler script.onerror = function handleScriptError(error) { script.cleanUp(); reject(error); }; script.onload = function handleScriptLoad() { script.cleanUp(); }; // Load data script.src = `${url}${ /[?&]/.test(url) ? "&" : "?" }jsonp=${callback}`; document.head.appendChild(script); }); } }; export default JSONPUtil;
mesosphere/marathon-ui
src/js/helpers/JSONPUtil.js
JavaScript
apache-2.0
993
class SettingsController { constructor($log, $state) { 'ngInject'; this.$log = $log; this.$state = $state; } } export default SettingsController;
azavea/raster-foundry
app-frontend/src/app/pages/user/settings/settings.controller.js
JavaScript
apache-2.0
179
var searchData= [ ['saveall',['saveAll',['../d9/dc6/class_main_window.html#a149085ca2d6cce59ecb59dcbf0892c07',1,'MainWindow']]], ['saveas',['saveAs',['../d9/dc6/class_main_window.html#a7fbef0054cdec7bbbf3c06fb12af473c',1,'MainWindow']]], ['saveplayers',['savePlayers',['../d9/dc6/class_main_window.html#aff0a6c08ba9cb391b4c259d7e1e3e6ee',1,'MainWindow']]], ['search',['SEARCH',['../df/da9/class_dialog.html#ae78164fb050172481b9bc05bdbbdc9b0a3ee13ecddf383e1872ad53f5f1947ef1',1,'Dialog::SEARCH()'],['../d8/dad/class_dialog2.html#a8516d2f5d38e3777d9c6a99c3374159aa9e715c7822a53c88692a844d07be7891',1,'Dialog2::SEARCH()']]], ['searchelename',['searchEleName',['../d1/d34/class_list.html#aa614a359e8399195c71d14067484d3b2',1,'List']]], ['searchplayer',['searchPlayer',['../d8/dad/class_dialog2.html#a4de4b4481a18d1001ac600a4fdcd4256',1,'Dialog2::searchPlayer()'],['../d9/dc6/class_main_window.html#ac529c585e84254f8ea1493aa4e984fff',1,'MainWindow::searchPlayer()']]], ['searchpos',['searchPos',['../d1/d34/class_list.html#a69893c5ca361f9502a0dc1c967612d02',1,'List']]], ['searchteam',['searchTeam',['../df/da9/class_dialog.html#a14e25a37abc03cea2b0aaf7dc91fe857',1,'Dialog::searchTeam()'],['../d9/dc6/class_main_window.html#a963edb5b19f8d39b0c5bbacc0d9ed5d6',1,'MainWindow::searchTeam()']]], ['setderrotas',['setDerrotas',['../d1/d35/class_team.html#a0e8272a4c5127fcd4be5444dd22cda9f',1,'Team']]], ['setempates',['setEmpates',['../d1/d35/class_team.html#a9dfa2c82540d9321e6cafb6acded557f',1,'Team']]], ['setgolesafavor',['setGolesAFavor',['../d1/d35/class_team.html#af21b432f707a656148c6626f105a93cc',1,'Team']]], ['setgolesencontra',['setGolesEnContra',['../d1/d35/class_team.html#a68c254ae21bea1353f5398b9858e7ff6',1,'Team']]], ['setid',['setId',['../df/da9/class_dialog.html#ad8dc7674caf8ad80354371cb055e2d86',1,'Dialog']]], ['setlist',['setList',['../df/da9/class_dialog.html#a49ad60e52f0e52fa4ec27b67964913fa',1,'Dialog::setList()'],['../d8/dad/class_dialog2.html#a15d71b221052d782bfdf156fe4aa7d75',1,'Dialog2::setList()']]], ['setmode',['setMode',['../df/da9/class_dialog.html#adc05cff2da1c925917d2301d730eebd8',1,'Dialog::setMode()'],['../d8/dad/class_dialog2.html#ad11aeeec4bdf19f00fced524be1b4205',1,'Dialog2::setMode()']]], ['setngoles',['setNGoles',['../d8/d53/class_player.html#aeaa23561cac2c75d1f3cad94915f0835',1,'Player']]], ['setnode',['setNode',['../df/da9/class_dialog.html#a3fe34fdf51dce326e10b7b2eef8ae6ea',1,'Dialog::setNode()'],['../d8/dad/class_dialog2.html#afcb469b5706793d4048d621a0e4c3abd',1,'Dialog2::setNode()']]], ['setnombre',['setNombre',['../d8/d53/class_player.html#a3c26ab31dffaf71b9775459ae00e1735',1,'Player::setNombre()'],['../d1/d35/class_team.html#a4e2bdf61ee9103b54c01bf65a3300bed',1,'Team::setNombre()']]], ['setvictorias',['setVictorias',['../d1/d35/class_team.html#a43b0095989199cafdbdb1cf87a2eba2f',1,'Team']]], ['sort',['sort',['../d1/d34/class_list.html#adcdf869b2506e2332052eff47afc8412',1,'List']]], ['sortdesc',['sortDesc',['../d1/d34/class_list.html#a006226544e5e078fdb4207edac1fb154',1,'List']]], ['sortplayerlist',['sortPlayerList',['../d9/dc6/class_main_window.html#ac39f495a110346fa8f5aa152ea92c06d',1,'MainWindow']]], ['sortplayerlistdesc',['sortPlayerListDesc',['../d9/dc6/class_main_window.html#a3c3289fb0c25eb584d7041cd3ddccd43',1,'MainWindow']]], ['sortteamlist',['sortTeamList',['../d9/dc6/class_main_window.html#a32cf6689bc8f4597363cbe8e4e7e5146',1,'MainWindow']]], ['sortteamlistdesc',['sortTeamListDesc',['../d9/dc6/class_main_window.html#a8e71f51c64a9d0f27b0c7547604357be',1,'MainWindow']]] ];
delfernan/LP
release/doc/html/search/all_f.js
JavaScript
apache-2.0
3,604
define( //begin v1.x content { "days-standAlone-short": [ "Ня", "Да", "Мя", "Лх", "Пү", "Ба", "Бя" ], "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "quarters-standAlone-narrow": [ "1", "2", "3", "4" ], "field-weekday": "Гариг", "dateFormatItem-yQQQ": "y QQQ", "dateFormatItem-yMEd": "E, y-M-d", "dateFormatItem-MMMEd": "E MMM d", "eraNarrow": [ "м.э.ө", "м.э." ], "days-format-short": [ "Ня", "Да", "Мя", "Лх", "Пү", "Ба", "Бя" ], "dateFormat-long": "y 'оны' MMM 'сарын' d", "months-format-wide": [ "Хулгана", "Үхэр", "Бар", "Туулай", "Луу", "Могой", "Морь", "Хонь", "Бич", "Тахиа", "Нохой", "Гахай" ], "dateTimeFormat-medium": "{1} {0}", "dayPeriods-format-wide-pm": "ҮХ", "dateFormat-full": "EEEE, y 'оны' MMM 'сарын' dd", "dateFormatItem-Md": "M-d", "dateFormatItem-yMd": "y-M-d", "field-era": "Эрин", "dateFormatItem-yM": "y-M", "months-standAlone-wide": [ "Хулгана", "Үхэр", "Бар", "Туулай", "Луу", "Могой", "Морь", "Хонь", "Бич", "Тахиа", "Нохой", "Гахай" ], "timeFormat-short": "HH:mm", "quarters-format-wide": [ "1-р улирал", "2-р улирал", "3-р улирал", "4-р улирал" ], "dateFormatItem-yQQQQ": "y 'оны' QQQQ", "timeFormat-long": "HH:mm:ss z", "field-year": "Жил", "dateFormatItem-yMMM": "y MMM", "field-hour": "Цаг", "months-format-abbr": [ "хул", "үхэ", "бар", "туу", "луу", "мог", "мор", "хон", "бич", "тах", "нох", "гах" ], "timeFormat-full": "HH:mm:ss zzzz", "field-day-relative+0": "Өнөөдөр", "field-day-relative+1": "Маргааш", "field-day-relative+2": "Нөгөөдөр", "dateFormatItem-H": "HH", "months-standAlone-abbr": [ "хул", "үхэ", "бар", "туу", "луу", "мог", "мор", "хон", "бич", "тах", "нох", "гах" ], "quarters-format-abbr": [ "У1", "У2", "У3", "У4" ], "quarters-standAlone-wide": [ "1-р улирал", "2-р улирал", "3-р улирал", "4-р улирал" ], "dateFormatItem-M": "L", "days-standAlone-wide": [ "ням", "даваа", "мягмар", "лхагва", "пүрэв", "баасан", "бямба" ], "timeFormat-medium": "HH:mm:ss", "dateFormatItem-Hm": "HH:mm", "quarters-standAlone-abbr": [ "У1", "У2", "У3", "У4" ], "eraAbbr": [ "МЭӨ", "МЭ" ], "field-minute": "Минут", "field-dayperiod": "Өдрийн цаг", "days-standAlone-abbr": [ "Ня", "Да", "Мя", "Лх", "Пү", "Ба", "Бя" ], "dateFormatItem-d": "d", "dateFormatItem-ms": "mm:ss", "quarters-format-narrow": [ "1", "2", "3", "4" ], "field-day-relative+-1": "Өчигдөр", "dateFormatItem-h": "h a", "dateTimeFormat-long": "{1} {0}", "field-day-relative+-2": "Уржигдар", "dateFormatItem-MMMd": "MMM d", "dateFormatItem-MEd": "E, M-d", "dateTimeFormat-full": "{1} {0}", "field-day": "Өдөр", "days-format-wide": [ "ням", "даваа", "мягмар", "лхагва", "пүрэв", "баасан", "бямба" ], "field-zone": "Бүс", "dateFormatItem-y": "y", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "dateFormatItem-hm": "h:mm a", "days-format-abbr": [ "Ня", "Да", "Мя", "Лх", "Пү", "Ба", "Бя" ], "dateFormatItem-yMMMd": "y MMM d", "eraNames": [ "манай эриний өмнөх", "манай эриний" ], "days-format-narrow": [ "1", "2", "3", "4", "5", "6", "7" ], "field-month": "Сар", "days-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7" ], "dateFormatItem-MMM": "LLL", "dayPeriods-format-wide-am": "ҮӨ", "dateFormat-short": "y-MM-dd", "field-second": "Хором", "dateFormatItem-yMMMEd": "E, y MMM d", "dateFormatItem-Ed": "dd E", "field-week": "Долоо хоног", "dateFormat-medium": "y MMM d", "dateTimeFormat-short": "{1}, {0}", "dateFormatItem-Hms": "HH:mm:ss", "dateFormatItem-hms": "h:mm:ss a" } //end v1.x content );
abssi/poc-tijari
dojoLib/toolkit/dojo/dojo/cldr/nls/mn/gregorian.js
JavaScript
apache-2.0
4,430
/** * @classdesc Base class from which all core Flybits models are extended. * @class * @param {Object} serverObj Raw Flybits core model `Object` directly from API. */ var BaseModel = (function(){ var BaseModel = function(serverObj){ BaseObj.call(this); /** * @instance * @memberof BaseModel * @member {string} id Parsed ID of the Flybits core model. */ this.id; if(serverObj && serverObj.id){ this.id = serverObj.id; } }; BaseModel.prototype = Object.create(BaseObj.prototype); BaseModel.prototype.constructor = BaseModel; BaseModel.prototype.reqKeys = { id: 'id' }; return BaseModel; })();
flybits/flybits.js
src/models/baseModel.js
JavaScript
apache-2.0
664
// Copyright 2016, Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START complete] 'use strict'; // [START auth] // By default, gcloud will authenticate using the service account file specified // by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the // project specified by the GCLOUD_PROJECT environment variable. See // https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication var gcloud = require('gcloud'); // Get a reference to the bigquery component var bigquery = gcloud.bigquery(); // [END auth] // [START print] function printExample (rows) { console.log('Query Results:'); rows.forEach(function (row) { var str = ''; for (var key in row) { if (str) { str += '\t'; } str += key + ': ' + row[key]; } console.log(str); }); } // [END print] // [START query] /** * Run an example query. * * @param {Function} callback Callback function. */ function queryExample (callback) { var query = 'SELECT TOP(corpus, 10) as title, COUNT(*) as unique_words\n' + 'FROM [publicdata:samples.shakespeare];'; bigquery.query(query, function (err, rows) { if (err) { return callback(err); } printExample(rows); callback(null, rows); }); } // [END query] // [END complete] // Run the examples exports.main = function (cb) { queryExample(cb); }; if (module === require.main) { exports.main(console.log); }
kydev1986/nodejs-docs-samples
bigquery/getting_started.js
JavaScript
apache-2.0
1,952
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.net.xpc.CrossPageChannelTest'); goog.setTestOnly('goog.net.xpc.CrossPageChannelTest'); goog.require('goog.Disposable'); goog.require('goog.Promise'); goog.require('goog.Timer'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.labs.userAgent.browser'); goog.require('goog.log'); goog.require('goog.log.Level'); goog.require('goog.net.xpc'); goog.require('goog.net.xpc.CfgFields'); goog.require('goog.net.xpc.CrossPageChannel'); goog.require('goog.net.xpc.CrossPageChannelRole'); goog.require('goog.net.xpc.TransportTypes'); goog.require('goog.object'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.TestCase'); goog.require('goog.testing.jsunit'); // Set this to false when working on this test. It needs to be true for // automated testing, as some browsers (eg IE8) choke on the large numbers of // iframes this test would otherwise leave active. var CLEAN_UP_IFRAMES = true; var IFRAME_LOAD_WAIT_MS = 1000; var stubs = new goog.testing.PropertyReplacer(); var uniqueId = 0; var driver; var canAccessSameDomainIframe = true; var accessCheckPromise = null; function setUpPage() { // This test is insanely slow on IE8 and Safari for some reason. goog.testing.TestCase.getActiveTestCase().promiseTimeout = 40 * 1000; // Show debug log var debugDiv = goog.dom.getElement('debugDiv'); var logger = goog.log.getLogger('goog.net.xpc'); logger.setLevel(goog.log.Level.ALL); goog.log.addHandler(logger, function(logRecord) { var msgElm = goog.dom.createDom(goog.dom.TagName.DIV); msgElm.innerHTML = logRecord.getMessage(); goog.dom.appendChild(debugDiv, msgElm); }); accessCheckPromise = new goog.Promise(function(resolve, reject) { var accessCheckIframes = []; accessCheckIframes.push( create1x1Iframe('nonexistent', 'testdata/i_am_non_existent.html')); window.setTimeout(function() { accessCheckIframes.push( create1x1Iframe('existent', 'testdata/access_checker.html')); }, 10); // Called from testdata/access_checker.html window['sameDomainIframeAccessComplete'] = function(canAccess) { canAccessSameDomainIframe = canAccess; for (var i = 0; i < accessCheckIframes.length; i++) { document.body.removeChild(accessCheckIframes[i]); } resolve(); }; }); } function setUp() { driver = new Driver(); // Ensure that the access check is complete before starting each test. return accessCheckPromise; } function tearDown() { stubs.reset(); driver.dispose(); } function create1x1Iframe(iframeId, src) { var iframeAccessChecker = goog.dom.createElement(goog.dom.TagName.IFRAME); iframeAccessChecker.id = iframeAccessChecker.name = iframeId; iframeAccessChecker.style.width = iframeAccessChecker.style.height = '1px'; iframeAccessChecker.src = src; document.body.insertBefore(iframeAccessChecker, document.body.firstChild); return iframeAccessChecker; } function testCreateIframeSpecifyId() { driver.createPeerIframe('new_iframe'); return goog.Timer.promise(IFRAME_LOAD_WAIT_MS).then(function() { driver.checkPeerIframe(); }); } function testCreateIframeRandomId() { driver.createPeerIframe(); return goog.Timer.promise(IFRAME_LOAD_WAIT_MS).then(function() { driver.checkPeerIframe(); }); } function testGetRole() { var cfg = {}; cfg[goog.net.xpc.CfgFields.ROLE] = goog.net.xpc.CrossPageChannelRole.OUTER; var channel = new goog.net.xpc.CrossPageChannel(cfg); // If the configured role is ignored, this will cause the dynamicly // determined role to become INNER. channel.peerWindowObject_ = window.parent; assertEquals( 'Channel should use role from the config.', goog.net.xpc.CrossPageChannelRole.OUTER, channel.getRole()); channel.dispose(); } // The following batch of tests: // * Establishes a peer iframe // * Connects an XPC channel between the frames // * From the connection callback in each frame, sends an 'echo' request, and // expects a 'response' response. // * Reconnects the inner frame, sends an 'echo', expects a 'response'. // * Optionally, reconnects the outer frame, sends an 'echo', expects a // 'response'. // * Optionally, reconnects the inner frame, but first reconfigures it to the // alternate protocol version, simulating an inner frame navigation that // picks up a new/old version. // // Every valid combination of protocol versions is tested, with both single and // double ended handshakes. Two timing scenarios are tested per combination, // which is what the 'reverse' parameter distinguishes. // // Where single sided handshake is in use, reconnection by the outer frame is // not supported, and therefore is not tested. // // The only known issue migrating to V2 is that once two V2 peers have // connected, replacing either peer with a V1 peer will not work. Upgrading V1 // peers to v2 is supported, as is replacing the only v2 peer in a connection // with a v1. function testLifeCycle_v1_v1() { return checkLifeCycle( false /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v1_v1_rev() { return checkLifeCycle( false /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, true /* reverse */); } function testLifeCycle_v1_v1_onesided() { return checkLifeCycle( true /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v1_v1_onesided_rev() { return checkLifeCycle( true /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, true /* reverse */); } function testLifeCycle_v1_v2() { return checkLifeCycle( false /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v1_v2_rev() { return checkLifeCycle( false /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, true /* reverse */); } function testLifeCycle_v1_v2_onesided() { return checkLifeCycle( true /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v1_v2_onesided_rev() { return checkLifeCycle( true /* oneSidedHandshake */, 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, true /* reverse */); } function testLifeCycle_v2_v1() { return checkLifeCycle( false /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v2_v1_rev() { return checkLifeCycle( false /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, true /* reverse */); } function testLifeCycle_v2_v1_onesided() { return checkLifeCycle( true /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v2_v1_onesided_rev() { return checkLifeCycle( true /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, true /* innerFrameMigrationSupported */, true /* reverse */); } function testLifeCycle_v2_v2() { // Test flakes on IE 10+ and Chrome: see b/22873770 and b/18595666. if ((goog.labs.userAgent.browser.isIE() && goog.labs.userAgent.browser.isVersionOrHigher(10)) || goog.labs.userAgent.browser.isChrome()) { return; } return checkLifeCycle( false /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, false /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v2_v2_rev() { return checkLifeCycle( false /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */, false /* innerFrameMigrationSupported */, true /* reverse */); } function testLifeCycle_v2_v2_onesided() { return checkLifeCycle( true /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, false /* innerFrameMigrationSupported */, false /* reverse */); } function testLifeCycle_v2_v2_onesided_rev() { return checkLifeCycle( true /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */, false /* innerFrameMigrationSupported */, true /* reverse */); } function checkLifeCycle( oneSidedHandshake, innerProtocolVersion, outerProtocolVersion, outerFrameReconnectSupported, innerFrameMigrationSupported, reverse) { driver.createPeerIframe( 'new_iframe', oneSidedHandshake, innerProtocolVersion, outerProtocolVersion); return driver.connect( true /* fullLifeCycleTest */, outerFrameReconnectSupported, innerFrameMigrationSupported, reverse); } // testConnectMismatchedNames have been flaky on IEs. // Flakiness is tracked in http://b/18595666 // For now, not running these tests on IE. function testConnectMismatchedNames_v1_v1() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, false /* reverse */); } function testConnectMismatchedNames_v1_v1_rev() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, true /* reverse */); } function testConnectMismatchedNames_v1_v2() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, false /* reverse */); } function testConnectMismatchedNames_v1_v2_rev() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, true /* reverse */); } function testConnectMismatchedNames_v2_v1() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, false /* reverse */); } function testConnectMismatchedNames_v2_v1_rev() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */, true /* reverse */); } function testConnectMismatchedNames_v2_v2() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, false /* reverse */); } function testConnectMismatchedNames_v2_v2_rev() { if (goog.labs.userAgent.browser.isIE()) { return; } return checkConnectMismatchedNames( 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, true /* reverse */); } function checkConnectMismatchedNames( innerProtocolVersion, outerProtocolVersion, reverse) { driver.createPeerIframe( 'new_iframe', false /* oneSidedHandshake */, innerProtocolVersion, outerProtocolVersion, true /* opt_randomChannelNames */); return driver.connect( false /* fullLifeCycleTest */, false /* outerFrameReconnectSupported */, false /* innerFrameMigrationSupported */, reverse /* reverse */); } function testEscapeServiceName() { var escape = goog.net.xpc.CrossPageChannel.prototype.escapeServiceName_; assertEquals( 'Shouldn\'t escape alphanumeric name', 'fooBar123', escape('fooBar123')); assertEquals( 'Shouldn\'t escape most non-alphanumeric characters', '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\', escape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\')); assertEquals( 'Should escape %, |, and :', 'foo%3ABar%7C123%25', escape('foo:Bar|123%')); assertEquals('Should escape tp', '%25tp', escape('tp')); assertEquals('Should escape %tp', '%25%25tp', escape('%tp')); assertEquals('Should not escape stp', 'stp', escape('stp')); assertEquals('Should not escape s%tp', 's%25tp', escape('s%tp')); } function testSameDomainCheck_noMessageOrigin() { var channel = new goog.net.xpc.CrossPageChannel( goog.object.create( goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com')); assertTrue(channel.isMessageOriginAcceptable(undefined)); } function testSameDomainCheck_noPeerHostname() { var channel = new goog.net.xpc.CrossPageChannel({}); assertTrue(channel.isMessageOriginAcceptable('http://foo.com')); } function testSameDomainCheck_unconfigured() { var channel = new goog.net.xpc.CrossPageChannel({}); assertTrue(channel.isMessageOriginAcceptable(undefined)); } function testSameDomainCheck_originsMatch() { var channel = new goog.net.xpc.CrossPageChannel( goog.object.create( goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com')); assertTrue(channel.isMessageOriginAcceptable('http://foo.com')); } function testSameDomainCheck_originsMismatch() { var channel = new goog.net.xpc.CrossPageChannel( goog.object.create( goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com')); assertFalse(channel.isMessageOriginAcceptable('http://nasty.com')); } function testUnescapeServiceName() { var unescape = goog.net.xpc.CrossPageChannel.prototype.unescapeServiceName_; assertEquals( 'Shouldn\'t modify alphanumeric name', 'fooBar123', unescape('fooBar123')); assertEquals( 'Shouldn\'t modify most non-alphanumeric characters', '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\', unescape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\')); assertEquals( 'Should unescape URL-escapes', 'foo:Bar|123%', unescape('foo%3ABar%7C123%25')); assertEquals('Should unescape tp', 'tp', unescape('%25tp')); assertEquals('Should unescape %tp', '%tp', unescape('%25%25tp')); assertEquals('Should not escape stp', 'stp', unescape('stp')); assertEquals('Should not escape s%tp', 's%tp', unescape('s%25tp')); } /** * Tests the case where the channel is disposed before it is fully connected. */ function testDisposeBeforeConnect() { // Test flakes on IE: see b/22873770 and b/18595666. if (goog.labs.userAgent.browser.isIE() && goog.labs.userAgent.browser.isVersionOrHigher(9)) { return; } driver.createPeerIframe( 'new_iframe', false /* oneSidedHandshake */, 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */, true /* opt_randomChannelNames */); return driver.connectOuterAndDispose(); } /** * Driver for the tests for CrossPageChannel. * * @constructor * @extends {goog.Disposable} */ Driver = function() { goog.Disposable.call(this); /** * The peer iframe. * @type {!Element} * @private */ this.iframe_ = null; /** * The channel to use. * @type {goog.net.xpc.CrossPageChannel} * @private */ this.channel_ = null; /** * Outer frame configuration object. * @type {Object} * @private */ this.outerFrameCfg_ = null; /** * The initial name of the outer channel. * @type {?string} * @private */ this.initialOuterChannelName_ = null; /** * Inner frame configuration object. * @type {Object} * @private */ this.innerFrameCfg_ = null; /** * The contents of the payload of the 'echo' request sent by the inner frame. * @type {?string} * @private */ this.innerFrameEchoPayload_ = null; /** * The contents of the payload of the 'echo' request sent by the outer frame. * @type {?string} * @private */ this.outerFrameEchoPayload_ = null; /** * A resolver which fires its promise when the inner frame receives an echo. * @type {!goog.promise.Resolver} * @private */ this.innerFrameResponseReceived_ = goog.Promise.withResolver(); /** * A resolver which fires its promise when the outer frame receives an echo. * @type {!goog.promise.Resolver} * @private */ this.outerFrameResponseReceived_ = goog.Promise.withResolver(); }; goog.inherits(Driver, goog.Disposable); /** @override */ Driver.prototype.disposeInternal = function() { // Required to make this test perform acceptably (and pass) on slow browsers, // esp IE8. if (CLEAN_UP_IFRAMES) { goog.dom.removeNode(this.iframe_); delete this.iframe_; } goog.dispose(this.channel_); this.innerFrameResponseReceived_.promise.cancel(); this.outerFrameResponseReceived_.promise.cancel(); Driver.base(this, 'disposeInternal'); }; /** * Returns the child peer's window object. * @return {Window} Child peer's window. * @private */ Driver.prototype.getInnerPeer_ = function() { return this.iframe_.contentWindow; }; /** * Sets up the configuration objects for the inner and outer frames. * @param {string=} opt_iframeId If present, the ID of the iframe to use, * otherwise, tells the channel to generate an iframe ID. * @param {boolean=} opt_oneSidedHandshake Whether the one sided handshake * config option should be set. * @param {string=} opt_channelName The name of the channel to use, or null * to generate one. * @param {number=} opt_innerProtocolVersion The native transport protocol * version used in the inner iframe. * @param {number=} opt_outerProtocolVersion The native transport protocol * version used in the outer iframe. * @param {boolean=} opt_randomChannelNames Whether the different ends of the * channel should be allowed to pick differing, random names. * @return {string} The name of the created channel. * @private */ Driver.prototype.setConfiguration_ = function( opt_iframeId, opt_oneSidedHandshake, opt_channelName, opt_innerProtocolVersion, opt_outerProtocolVersion, opt_randomChannelNames) { var cfg = {}; if (opt_iframeId) { cfg[goog.net.xpc.CfgFields.IFRAME_ID] = opt_iframeId; } cfg[goog.net.xpc.CfgFields.PEER_URI] = 'testdata/inner_peer.html'; if (!opt_randomChannelNames) { var channelName = opt_channelName || 'test_channel' + uniqueId++; cfg[goog.net.xpc.CfgFields.CHANNEL_NAME] = channelName; } cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = 'does-not-exist.html'; cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = 'does-not-exist.html'; cfg[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE] = !!opt_oneSidedHandshake; cfg[goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] = opt_outerProtocolVersion; function resolveUri(fieldName) { cfg[fieldName] = goog.Uri.resolve(window.location.href, cfg[fieldName]).toString(); } resolveUri(goog.net.xpc.CfgFields.PEER_URI); resolveUri(goog.net.xpc.CfgFields.LOCAL_POLL_URI); resolveUri(goog.net.xpc.CfgFields.PEER_POLL_URI); this.outerFrameCfg_ = cfg; this.innerFrameCfg_ = goog.object.clone(cfg); this.innerFrameCfg_[goog.net.xpc.CfgFields .NATIVE_TRANSPORT_PROTOCOL_VERSION] = opt_innerProtocolVersion; }; /** * Creates an outer frame channel object. * @private */ Driver.prototype.createChannel_ = function() { if (this.channel_) { this.channel_.dispose(); } this.channel_ = new goog.net.xpc.CrossPageChannel(this.outerFrameCfg_); this.channel_.registerService('echo', goog.bind(this.echoHandler_, this)); this.channel_.registerService( 'response', goog.bind(this.responseHandler_, this)); return this.channel_.name; }; /** * Checks the names of the inner and outer frames meet expectations. * @private */ Driver.prototype.checkChannelNames_ = function() { var outerName = this.channel_.name; var innerName = this.getInnerPeer_().channel.name; var configName = this.innerFrameCfg_[goog.net.xpc.CfgFields.CHANNEL_NAME] || null; // The outer channel never changes its name. assertEquals(this.initialOuterChannelName_, outerName); // The name should be as configured, if it was configured. if (configName) { assertEquals(configName, innerName); } // The names of both ends of the channel should match. assertEquals(innerName, outerName); G_testRunner.log('Channel name: ' + innerName); }; /** * Returns the configuration of the xpc. * @return {?Object} The configuration of the xpc. */ Driver.prototype.getInnerFrameConfiguration = function() { return this.innerFrameCfg_; }; /** * Creates the peer iframe. * @param {string=} opt_iframeId If present, the ID of the iframe to create, * otherwise, generates an iframe ID. * @param {boolean=} opt_oneSidedHandshake Whether a one sided handshake is * specified. * @param {number=} opt_innerProtocolVersion The native transport protocol * version used in the inner iframe. * @param {number=} opt_outerProtocolVersion The native transport protocol * version used in the outer iframe. * @param {boolean=} opt_randomChannelNames Whether the ends of the channel * should be allowed to pick differing, random names. * @return {!Array<string>} The id of the created iframe and the name of the * created channel. */ Driver.prototype.createPeerIframe = function( opt_iframeId, opt_oneSidedHandshake, opt_innerProtocolVersion, opt_outerProtocolVersion, opt_randomChannelNames) { var expectedIframeId; if (opt_iframeId) { expectedIframeId = opt_iframeId = opt_iframeId + uniqueId++; } else { // Have createPeerIframe() generate an ID stubs.set(goog.net.xpc, 'getRandomString', function(length) { return '' + length; }); expectedIframeId = 'xpcpeer4'; } assertNull( 'element[id=' + expectedIframeId + '] exists', goog.dom.getElement(expectedIframeId)); this.setConfiguration_( opt_iframeId, opt_oneSidedHandshake, undefined /* opt_channelName */, opt_innerProtocolVersion, opt_outerProtocolVersion, opt_randomChannelNames); var channelName = this.createChannel_(); this.initialOuterChannelName_ = channelName; this.iframe_ = this.channel_.createPeerIframe(document.body); assertEquals(expectedIframeId, this.iframe_.id); }; /** * Checks if the peer iframe has been created. */ Driver.prototype.checkPeerIframe = function() { assertNotNull(this.iframe_); var peer = this.getInnerPeer_(); assertNotNull(peer); assertNotNull(peer.document); }; /** * Starts the connection. The connection happens asynchronously. */ Driver.prototype.connect = function( fullLifeCycleTest, outerFrameReconnectSupported, innerFrameMigrationSupported, reverse) { if (!this.isTransportTestable_()) { return; } // Set the criteria for the initial handshake portion of the test. this.reinitializePromises_(); this.innerFrameResponseReceived_.promise.then( this.checkChannelNames_, null, this); if (fullLifeCycleTest) { this.innerFrameResponseReceived_.promise.then( goog.bind( this.testReconnects_, this, outerFrameReconnectSupported, innerFrameMigrationSupported)); } this.continueConnect_(reverse); return this.innerFrameResponseReceived_.promise; }; Driver.prototype.continueConnect_ = function(reverse) { // Wait until the peer is fully established. Establishment is sometimes very // slow indeed, especially on virtual machines, so a fixed timeout is not // suitable. This wait is required because we want to take precise control // of the channel startup timing, and shouldn't be needed in production use, // where the inner frame's channel is typically not started by a DOM call as // it is here. if (!this.getInnerPeer_() || !this.getInnerPeer_().instantiateChannel) { window.setTimeout(goog.bind(this.continueConnect_, this, reverse), 100); return; } var connectFromOuterFrame = goog.bind( this.channel_.connect, this.channel_, goog.bind(this.outerFrameConnected_, this)); var innerConfig = this.innerFrameCfg_; var connectFromInnerFrame = goog.bind( this.getInnerPeer_().instantiateChannel, this.getInnerPeer_(), innerConfig); // Take control of the timing and reverse of each frame's first SETUP call. If // these happen to fire right on top of each other, that tends to mask // problems that reliably occur when there is a short delay. window.setTimeout(connectFromOuterFrame, reverse ? 1 : 10); window.setTimeout(connectFromInnerFrame, reverse ? 10 : 1); }; /** * Called by the outer frame connection callback. * @private */ Driver.prototype.outerFrameConnected_ = function() { var payload = this.outerFrameEchoPayload_ = goog.net.xpc.getRandomString(10); this.channel_.send('echo', payload); }; /** * Called by the inner frame connection callback in inner_peer.html. */ Driver.prototype.innerFrameConnected = function() { var payload = this.innerFrameEchoPayload_ = goog.net.xpc.getRandomString(10); this.getInnerPeer_().sendEcho(payload); }; /** * The handler function for incoming echo requests. * @param {string} payload The message payload. * @private */ Driver.prototype.echoHandler_ = function(payload) { assertTrue('outer frame should be connected', this.channel_.isConnected()); var peer = this.getInnerPeer_(); assertTrue('child should be connected', peer.isConnected()); this.channel_.send('response', payload); }; /** * The handler function for incoming echo responses. * @param {string} payload The message payload. * @private */ Driver.prototype.responseHandler_ = function(payload) { assertTrue('outer frame should be connected', this.channel_.isConnected()); var peer = this.getInnerPeer_(); assertTrue('child should be connected', peer.isConnected()); assertEquals(this.outerFrameEchoPayload_, payload); this.outerFrameResponseReceived_.resolve(true); }; /** * The handler function for incoming echo replies. Called from inner_peer.html. * @param {string} payload The message payload. */ Driver.prototype.innerFrameGotResponse = function(payload) { assertTrue('outer frame should be connected', this.channel_.isConnected()); var peer = this.getInnerPeer_(); assertTrue('child should be connected', peer.isConnected()); assertEquals(this.innerFrameEchoPayload_, payload); this.innerFrameResponseReceived_.resolve(true); }; /** * The second phase of the standard test, where reconnections of both the inner * and outer frames are performed. * @param {boolean} outerFrameReconnectSupported Whether outer frame reconnects * are supported, and should be tested. * @private */ Driver.prototype.testReconnects_ = function( outerFrameReconnectSupported, innerFrameMigrationSupported) { G_testRunner.log('Performing inner frame reconnect'); this.reinitializePromises_(); this.innerFrameResponseReceived_.promise.then( this.checkChannelNames_, null, this); if (outerFrameReconnectSupported) { this.innerFrameResponseReceived_.promise.then( goog.bind( this.performOuterFrameReconnect_, this, innerFrameMigrationSupported)); } else if (innerFrameMigrationSupported) { this.innerFrameResponseReceived_.promise.then( this.migrateInnerFrame_, null, this); } this.performInnerFrameReconnect_(); }; /** * Initializes the promise resolvers and clears the echo payloads, ready for * another sub-test. * @private */ Driver.prototype.reinitializePromises_ = function() { this.innerFrameEchoPayload_ = null; this.outerFrameEchoPayload_ = null; this.innerFrameResponseReceived_.promise.cancel(); this.innerFrameResponseReceived_ = goog.Promise.withResolver(); this.outerFrameResponseReceived_.promise.cancel(); this.outerFrameResponseReceived_ = goog.Promise.withResolver(); }; /** * Get the inner frame to reconnect, and repeat the echo test. * @private */ Driver.prototype.performInnerFrameReconnect_ = function() { var peer = this.getInnerPeer_(); peer.instantiateChannel(this.innerFrameCfg_); }; /** * Get the outer frame to reconnect, and repeat the echo test. * @private */ Driver.prototype.performOuterFrameReconnect_ = function( innerFrameMigrationSupported) { G_testRunner.log('Closing channel'); this.channel_.close(); // If there is another channel still open, the native transport's global // postMessage listener will still be active. This will mean that messages // being sent to the now-closed channel will still be received and delivered, // such as transport service traffic from its previous correspondent in the // other frame. Ensure these messages don't cause exceptions. try { this.channel_.xpcDeliver(goog.net.xpc.TRANSPORT_SERVICE_, 'payload'); } catch (e) { fail('Should not throw exception'); } G_testRunner.log('Reconnecting outer frame'); this.reinitializePromises_(); this.innerFrameResponseReceived_.promise.then( this.checkChannelNames_, null, this); if (innerFrameMigrationSupported) { this.outerFrameResponseReceived_.promise.then( this.migrateInnerFrame_, null, this); } this.channel_.connect(goog.bind(this.outerFrameConnected_, this)); }; /** * Migrate the inner frame to the alternate protocol version and reconnect it. * @private */ Driver.prototype.migrateInnerFrame_ = function() { G_testRunner.log('Migrating inner frame'); this.reinitializePromises_(); var innerFrameProtoVersion = this.innerFrameCfg_[goog.net.xpc.CfgFields .NATIVE_TRANSPORT_PROTOCOL_VERSION]; this.innerFrameResponseReceived_.promise.then( this.checkChannelNames_, null, this); this.innerFrameCfg_[goog.net.xpc.CfgFields .NATIVE_TRANSPORT_PROTOCOL_VERSION] = innerFrameProtoVersion == 1 ? 2 : 1; this.performInnerFrameReconnect_(); }; /** * Determines if the transport type for the channel is testable. * Some transports are misusing global state or making other * assumptions that cause connections to fail. * @return {boolean} Whether the transport is testable. * @private */ Driver.prototype.isTransportTestable_ = function() { var testable = false; var transportType = this.channel_.determineTransportType_(); switch (transportType) { case goog.net.xpc.TransportTypes.IFRAME_RELAY: case goog.net.xpc.TransportTypes.IFRAME_POLLING: testable = canAccessSameDomainIframe; break; case goog.net.xpc.TransportTypes.NATIVE_MESSAGING: case goog.net.xpc.TransportTypes.FLASH: case goog.net.xpc.TransportTypes.DIRECT: case goog.net.xpc.TransportTypes.NIX: testable = true; break; } return testable; }; /** * Connect the outer channel but not the inner one. Wait a short time, then * dispose the outer channel and make sure it was torn down properly. */ Driver.prototype.connectOuterAndDispose = function() { this.channel_.connect(); return goog.Timer.promise(2000).then(this.disposeAndCheck_, null, this); }; /** * Dispose the cross-page channel. Check that the transport was also * disposed, and allow to run briefly to make sure no timers which will cause * failures are still running. * @private */ Driver.prototype.disposeAndCheck_ = function() { assertFalse(this.channel_.isConnected()); var transport = this.channel_.transport_; this.channel_.dispose(); assertNull(this.channel_.transport_); assertTrue(this.channel_.isDisposed()); assertTrue(transport.isDisposed()); // Let any errors caused by erroneous retries happen. return goog.Timer.promise(2000); };
teppeis/closure-library
closure/goog/net/xpc/crosspagechannel_test.js
JavaScript
apache-2.0
33,245
'use strict'; var AddonsModel = require('../../../models').Addons; var shortid = require('shortid'); module.exports = function(router) { router.get('/', function(req, res) { AddonsModel.find(function(err, data) { res.json(err ? { 'error': 'API Error', 'message': 'Error occurred' } : data); }); }); router.post('/', function(req, res){ if ( !( req.body.name && req.body.price) ) return res.status(400).json({'message' : 'Invalid request format'}); if( typeof req.body.id == 'undefined' || req.body.id == '' ) req.body.id = shortid.generate(); var addon = new AddonsModel({ 'id' : req.body.id, 'name' : req.body.name, 'price' : Number(req.body.price) }); addon.save(function(err){ if(err) res.status(500).json({'message':'DB insertion error'}); else res.status(200).json({'message':'Success'}); }); }); router.delete('/:id',function(req, res){ var id = req.params.id; AddonsModel.find({'id' : id}).remove(function(err){ if(err) res.status(500).json({ 'error' : 'API Error', 'message': 'Could not delete addon'}); else res.status(200).json({'message':'Success'}); }); }); router.patch('/:id', function(req, res){ var id = req.params.id; console.log("patching + " + id); AddonsModel.update({'id': id}, req.body, function(err, numUpdated){ console.log(req.body); if(err) res.status(500).json({'error': 'API Error', 'message' : 'Could not update records'}); else res.json({'message' : 'Success', 'response' : numUpdated }); }); }); };
PayPal-Opportunity-Hack-Chennai-2015/YRG-Foundation
admin/controllers/api/addons/index.js
JavaScript
apache-2.0
1,886
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var jsm = {}; Cu.import("resource://gre/modules/XPCOMUtils.jsm", jsm); var XPCOMUtils = jsm.XPCOMUtils; /** * A service for adding, removing and notifying observers of notifications. * Wraps the nsIObserverService interface. * * @version 0.2 */ var service = Cc["@mozilla.org/observer-service;1"]. getService(Ci.nsIObserverService); /** * A cache of observers that have been added. * * We use this to remove observers when a caller calls |Observers.remove|. */ var cache = []; /** * Register the given callback as an observer of the given topic. * * @param topic {String} * the topic to observe * * @param callback {Object} * the callback; an Object that implements nsIObserver or a Function * that gets called when the notification occurs * * @param thisObject {Object} [optional] * the object to use as |this| when calling a Function callback * * @returns the observer */ var add = exports.add = function add(topic, callback, thisObject) { var observer = new Observer(topic, callback, thisObject); service.addObserver(observer, topic, true); cache.push(observer); return observer; }; /** * Unregister the given callback as an observer of the given topic. * * @param topic {String} * the topic being observed * * @param callback {Object} * the callback doing the observing * * @param thisObject {Object} [optional] * the object being used as |this| when calling a Function callback */ var remove = exports.remove = function remove(topic, callback, thisObject) { // This seems fairly inefficient, but I'm not sure how much better // we can make it. We could index by topic, but we can't index by callback // or thisObject, as far as I know, since the keys to JavaScript hashes // (a.k.a. objects) can apparently only be primitive values. var [observer] = cache.filter(function(v) { return (v.topic == topic && v.callback == callback && v.thisObject == thisObject); }); if (observer) { service.removeObserver(observer, topic); cache.splice(cache.indexOf(observer), 1); } }; /** * Notify observers about something. * * @param topic {String} * the topic to notify observers about * * @param subject {Object} [optional] * some information about the topic; can be any JS object or primitive * * @param data {String} [optional] [deprecated] * some more information about the topic; deprecated as the subject * is sufficient to pass all needed information to the JS observers * that this module targets; if you have multiple values to pass to * the observer, wrap them in an object and pass them via the subject * parameter (i.e.: { foo: 1, bar: "some string", baz: myObject }) */ var notify = exports.notify = function notify(topic, subject, data) { subject = (typeof subject == "undefined") ? null : new Subject(subject); data = (typeof data == "undefined") ? null : data; service.notifyObservers(subject, topic, data); }; function Observer(topic, callback, thisObject) { this.topic = topic; this.callback = callback; this.thisObject = thisObject; } Observer.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), observe: function(subject, topic, data) { // Extract the wrapped object for subjects that are one of our // wrappers around a JS object. This way we support both wrapped // subjects created using this module and those that are real // XPCOM components. if (subject && typeof subject == "object" && ("wrappedJSObject" in subject) && ("observersModuleSubjectWrapper" in subject.wrappedJSObject)) subject = subject.wrappedJSObject.object; try { if (typeof this.callback == "function") { if (this.thisObject) this.callback.call(this.thisObject, subject, data); else this.callback(subject, data); } else // typeof this.callback == "object" (nsIObserver) this.callback.observe(subject, topic, data); } catch (e) { console.exception(e); } } }; function Subject(object) { // Double-wrap the object and set a property identifying the // wrappedJSObject as one of our wrappers to distinguish between // subjects that are one of our wrappers (which we should unwrap // when notifying our observers) and those that are real JS XPCOM // components (which we should pass through unaltered). this.wrappedJSObject = { observersModuleSubjectWrapper: true, object: object }; } Subject.prototype = { QueryInterface: XPCOMUtils.generateQI([]), getHelperForLanguage: function() {}, getInterfaces: function() {} }; require("unload").when( function removeAllObservers() { // Make a copy of cache first, since cache will be changing as we // iterate through it. cache.slice().forEach( function(observer) { remove(observer.topic, observer.callback, observer.thisObject); }); });
sergecodd/FireFox-OS
B2G/gecko/browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/lib/observer-service.js
JavaScript
apache-2.0
5,477
Ti.include('../class/db.js'); Ti.include('../class/const.js'); Ti.include('../viewHelper/solucioDetailsViews.js'); var win = Ti.UI.currentWindow; var objSolucio = Db.retrieveSolucio(win.idSolucio); var votat = objSolucio.votat; var textTitolSolucio = "#"+ win.numSolucio + ': ' +objSolucio.tt; win.title = L("Idea") + " #" + objSolucio.id; var txtVot = null; if ( objSolucio.vt == 1 || objSolucio.vt == -1 ){ txtVot = objSolucio.vt + "\n" + L("Vot"); }else{ txtVot = objSolucio.vt + "\n" + L("Vots"); } var views = solucioDetailsViews.getViews(textTitolSolucio,txtVot,objSolucio.ds); if (objSolucio.vt > 0){ views.votsLabel.backgroundColor="#11f605"; }else{ if (objSolucio.vt < 0){ views.votsLabel.backgroundColor="#f00900"; }else{ views.votsLabel.backgroundColor="#ffa327"; } } views.titolSolucioView.add(views.votsLabel); views.titolSolucioView.add(views.titolSolucioLabel); win.add(views.titolSolucioView); views.solucioTableView.top =views.titolSolucioView.height; views.detailRow.add(views.descripcioSolucioLabel); views.solucioTableView.setData([views.detailRow]); win.add(views.solucioTableView); Ti.App.addEventListener('setVoteButtonColor',function(votatObj){ Ti.API.info("votat2:"+votatObj.votat + " status "+votatObj.status); if (votatObj.votat != 2){ if(votatObj.votat == 1){ upButton.votat = 1; upButton.backgroundColor='#11f605'; equalButton.votat = 0; equalButton.backgroundColor = "#CCC"; downButton.votat = 0; downButton.backgroundColor = "#CCC"; }else if(votatObj.votat == 0){ upButton.votat = 0; upButton.backgroundColor = "#CCC"; equalButton.votat = 1; equalButton.backgroundColor = "#ffa327"; downButton.votat = 0; downButton.backgroundColor = "#CCC"; }else if(votatObj.votat == -1){ upButton.votat = 0; upButton.backgroundColor = "#CCC"; equalButton.votat = 0; equalButton.backgroundColor = "#CCC"; downButton.votat = 1; downButton.backgroundColor = "#f00900"; } } if(votatObj.status == IDEA_STATUS_WAITING || votatObj.status == IDEA_STATUS_DONE){ upButton.enabled = false; equalButton.enabled = false; downButton.enabled = false; } if(votatObj.status == IDEA_STATUS_WAITING || (votatObj.status == IDEA_STATUS_DONE && votatObj.votat == 2)){ upButton.votat = 0; upButton.backgroundColor = "#CCC"; equalButton.votat = 0; equalButton.backgroundColor = "#CCC"; downButton.votat = 0; downButton.backgroundColor = "#CCC"; } }); if(Ti.App.user.hasToken()){ views.activityIndicatorView.add(views.activityIndicator); win.add(views.activityIndicatorView); Ti.API.info("votat:"+votat); var viewButtons = Ti.UI.createView({ height:45, bottom:0, layout:'horizontal' }); var colorUp = null; if (objSolucio.votat == 1 || objSolucio.votat == 2){ colorUp ='#11f605'; }else{ colorUp ='#CCC'; } var upButton = Ti.UI.createButton({ font:{size:"8"}, left:5, height:40, width:97, borderRadius:12, color:'#000', backgroundColor:colorUp, style:Titanium.UI.iPhone.SystemButtonStyle.PLAIN, title:L('Votar Si') }); var colorEqual = null; if (objSolucio.votat == 0 || objSolucio.votat == 2){ colorEqual ='#ffa327'; }else{ colorEqual ='#CCC'; } var equalButton = Ti.UI.createButton({ font:{size:"8"}, left:8, height:40, width:97, borderRadius:12, color:'#000', backgroundColor:colorEqual, style:Titanium.UI.iPhone.SystemButtonStyle.PLAIN, title:L('En Blanc') }); var colorDown = null; if (objSolucio.votat == 0 || objSolucio.votat == 2){ colorDown ='#f00900'; }else{ colorDown ='#CCC'; } var downButton = Ti.UI.createButton({ font:{size:"8"}, left:8, height:40, width:97, borderRadius:12, color:'#000', backgroundColor:colorDown, style:Titanium.UI.iPhone.SystemButtonStyle.PLAIN, title:L('Votar No') }); if(objSolucio.st == IDEA_STATUS_INCOURSE ){ upButton.addEventListener('click',function(){ if(upButton.votat !=1){ votat = 1; views.activityIndicatorView.show(); Ti.App.network_user.vote(win.idSolucio,votat); } }); equalButton.addEventListener('click',function(){ if(equalButton.votat !=1){ votat = 0; views.activityIndicatorView.show(); Ti.App.network_user.vote(win.idSolucio,votat); } }); downButton.addEventListener('click',function(){ if(downButton.votat != 1){ votat = -1; views.activityIndicatorView.show(); Ti.App.network_user.vote(win.idSolucio,votat); } }); } views.solucioTableView.bottom=45; Ti.App.fireEvent('setVoteButtonColor',{votat:votat,status:objSolucio.st}); win.barColor = '#333'; viewButtons.add(upButton); viewButtons.add(equalButton); viewButtons.add(downButton); win.add(viewButtons); } Ti.App.addEventListener('voteKo', function(){ Ti.App.network_user.showAlert(L('WARNING'),L("No s'ha pogut enviar el vot")); views.activityIndicatorView.hide(); }); Ti.App.addEventListener('voteOk', function(){ views.activityIndicatorView.hide(); var totalVots = Db.votarSolucio(win.idSolucio,votat); var totalVotsTxt = null; if ( totalVots == 1 || totalVots == -1 ){ totalVotsTxt = totalVots + "\n" + L("Vot"); }else{ totalVotsTxt = totalVots + "\n" + L("Vots"); } views.votsLabel.text = totalVotsTxt; if (totalVots > 0){ views.votsLabel.backgroundColor="#11f605"; }else{ if (totalVots < 0){ views.votsLabel.backgroundColor="#f00900"; }else{ views.votsLabel.backgroundColor="#ffa327"; } } Ti.App.fireEvent('setVoteButtonColor',{votat:votat,status:objSolucio.st}); Ti.App.fireEvent('updateSolucionsTableView'); });
pirata-cat/TitaniumPirataCat
old/window/solucioDetailsWindow.js
JavaScript
apache-2.0
5,553
/** * Return the list of attributes of a node. * @method getNodeAttributes * @memberof axe.utils * @param {Element} node * @deprecated * @returns {NamedNodeMap} */ function getNodeAttributes(node) { // eslint-disable-next-line no-restricted-syntax if (node.attributes instanceof window.NamedNodeMap) { // eslint-disable-next-line no-restricted-syntax return node.attributes; } // if the attributes property is not of type NamedNodeMap then the DOM // has been clobbered. E.g. <form><input name="attributes"></form>. // We can clone the node to isolate it and then return the attributes return node.cloneNode(false).attributes; } export default getNodeAttributes;
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/axe-core/lib/core/utils/get-node-attributes.js
JavaScript
apache-2.0
694
// Copyright 2017 The Kubernetes Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import DeployFromFilePageObject from './deployfromfile_po'; describe('Deploy from file view', () => { /** @type {!DeployFromFilePageObject} */ let page; beforeEach(() => { page = new DeployFromFilePageObject(); browser.get('#!/deploy'); page.deployFromFileTab.click(); }); it('should have upload button disabled when no file is selected', () => { expect(page.deployButton.getAttribute('disabled')).toContain('true'); }); });
kenan435/dashboard
src/test/integration/deploy/deployfromfile_test.js
JavaScript
apache-2.0
1,058
"use strict"; define('forum/rpg/training', ['translator'], function(translator) { var training = {}; training.init = function() { }; return training; });
Holyphoenix/nodebb-plugin-openfantasy
static/lib/openfantasy/training.js
JavaScript
bsd-2-clause
163
var searchData= [ ['end',['end',['../class_html_project.html#a41599236c5e453464627a23cd2314393',1,'HtmlProject']]] ];
semyon2105/simpleHTML
doc/html/search/functions_4.js
JavaScript
bsd-2-clause
120
// Copyright 2013 The Polymer Authors. All rights reserved. // Use of this source code is goverened by a BSD-style // license that can be found in the LICENSE file. (function(scope) { 'use strict'; var HTMLElement = scope.wrappers.HTMLElement; var mixin = scope.mixin; var registerWrapper = scope.registerWrapper; var OriginalHTMLShadowElement = window.HTMLShadowElement; function HTMLShadowElement(node) { HTMLElement.call(this, node); } HTMLShadowElement.prototype = Object.create(HTMLElement.prototype); mixin(HTMLShadowElement.prototype, { // TODO: attribute boolean resetStyleInheritance; }); if (OriginalHTMLShadowElement) registerWrapper(OriginalHTMLShadowElement, HTMLShadowElement); scope.wrappers.HTMLShadowElement = HTMLShadowElement; })(window.ShadowDOMPolyfill);
PolymerLabs/labs
dfreedm/core-icon-study/bower_components/ShadowDOM/src/wrappers/HTMLShadowElement.js
JavaScript
bsd-3-clause
818
import React from 'react'; import {storiesOf} from '@storybook/react'; import {withInfo} from '@storybook/addon-info'; import {number, boolean, array, color} from '@storybook/addon-knobs'; // import {action} from '@storybook/addon-actions'; import ScoreBar from 'app/components/scoreBar'; const stories = storiesOf('ScoreBar', module); stories .add( 'horizontal', withInfo('Description')(() => ( <div style={{backgroundColor: 'white', padding: 12}}> <ScoreBar vertical={boolean('Vertical', false)} size={number('Size')} thickness={number('Thickness')} score={number('Score', 3)} /> </div> )) ) .add( 'vertical', withInfo('Description')(() => { return ( <div style={{backgroundColor: 'white', padding: 12}}> <ScoreBar vertical={boolean('Vertical', true)} size={number('Size')} thickness={number('Thickness')} score={number('Score', 3)} /> </div> ); }) ) .add( 'custom palette', withInfo('Description')(() => { let palette = array('Palette', [ color('Lower', 'pink'), color('Low', 'yellow'), color('Med', 'lime'), color('High', 'blue'), color('Higher', 'purple'), ]); return ( <div style={{backgroundColor: 'white', padding: 12}}> <ScoreBar vertical={boolean('Vertical', false)} size={number('Size')} thickness={number('Thickness')} score={number('Score', 3)} palette={palette} /> </div> ); }) );
ifduyue/sentry
docs-ui/components/scoreBar.stories.js
JavaScript
bsd-3-clause
1,670
/** * @license * Copyright (c) 2015 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // jshint node:true 'use strict'; // jshint -W079 var Promise = global.Promise || require('es6-promise').Promise; // jshint +W079 var url = require('url'); var nodegit = require('nodegit'); var clone = nodegit.Clone.clone; var Repository = nodegit.Repository; var Stash = nodegit.Stash; var shell = require('shelljs'); var temp = require('temp'); var path = require('path'); var fs = require('fs'); shell.config.silent = true; function bower(args) { var cmd = path.join(__dirname, '..', 'node_modules', '.bin', 'bower'); return cmd + ' ' + args; } function readBower(dir) { return JSON.parse(fs.readFileSync(path.join(dir, "bower.json"))); } var Commands = function Commands(db, workdir) { this._db = db; this._workdir = workdir; this._tmpDir = temp.mkdirSync('wcw'); this._staticDirs = {}; }; function bowerDeps(bowerJson) { var dependencies = []; if (bowerJson.dependencies) { Object.keys(bowerJson.dependencies).forEach(function (dep){ dependencies.push(bowerJson.dependencies[dep]); }); } return dependencies; } Commands.prototype = { /** * Resolves a package. * @param {string} pkg A bower-like repository description, github repo, or other git url * @return {Array.<{{folder:string, repository:}}>} A list of packages and URLs to add to the workspace. */ resolve: function(pkg) { // Install the package to a tempdir shell.pushd(this._tmpDir); shell.exec(bower(' install ' + pkg)); shell.pushd('bower_components'); var packages = []; shell.ls('./').forEach(function(component){ var bowerjson = readBower(component); if (bowerjson.repository === undefined || bowerjson.repository.type != 'git') { if (!this._staticDirs[bowerjson.name]) { this._staticDirs[bowerjson.name] = true; console.warn("Repository must be specified for " + bowerjson.name + ". Falling back to static mode."); packages.push({folder: component, sourcedir: path.join(process.cwd(), component)}); } return; } packages.push({folder: component, repo: bowerjson.repository}); }.bind(this)); shell.popd(); return packages; }, load: function(dir, repo) { return this._db.addPackage(dir, repo).then(function(err){ if (err) { // The package has been loaded. return; } console.log("cloning " + dir); return nodegit.Clone( repo.url, path.join(this._workdir, dir), { remoteCallbacks: { certificateCheck: function() { // github will fail cert check on some OSX machines // this overrides that check return 1; } } }); }.bind(this)).then(function() { return dir; }).catch(function(err){ console.log("failed to initialize repo for dir " + dir); console.log(err); console.log(err.stack); this._db.removePackage(dir); }); }, deps: function(dir) { return this._db.hasPackage(dir).then(function(hasPackage){ var bowerJson = readBower(path.join(this._workdir, dir)); return bowerDeps(bowerJson); }); }, installDeps: function(dir) { return this.deps(dir).then(function(deps){ var depInstalls = []; deps.forEach(function(dep){ depInstalls.push(this.install(dep)); }.bind(this)); return Promise.all(depInstalls); }.bind(this)); }, install: function(pkg) { var resolved = this.resolve(pkg); var resolutions = []; resolved.forEach(function(pkg){ var loaded; if (pkg.repo) { loaded = this.load(pkg.folder, pkg.repo); } else { // If the directory exists but isn't a git checkout, we'll overwrite it here. if (!shell.test('-e', pkg.folder) || !shell.test('-e', path.join(pkg.folder, '.git'))) { shell.cp('-Rf', pkg.sourcedir, this._workdir); loaded = Promise.resolve(pkg.folder); } } loaded = loaded.then(function(dir){ return this.installDeps(dir); }.bind(this)); resolutions.push(loaded); }.bind(this)); return Promise.all(resolutions); }, update: function() { return this._db.getPackages().then(function(packages){ var repos = []; packages.forEach(function(pkg){ repos.push(Repository.open(path.join(this._workdir, pkg.folder)) .then(function(repo) { var statuses = repo.getStatusExt(); var modified = false; statuses.forEach(function(status){ if (status.isModified()) { modified = true; } }); var stash; if (modified) { stash = Stash.save(repo, repo.defaultSignature(), "wcwstash", 0); } else { stash = Promise.resolve(false); } var stashed; return stash.then(function(didStash){ stashed = didStash; return repo.fetchAll({ credentials: function(url, userName) { return nodegit.Cred.sshKeyFromAgent(userName); }, certificateCheck: function() { return 1; } }); }).then(function() { return repo.mergeBranches("master", "origin/master"); }).then(function(){ return {repo: repo, stashed: stashed, folder: pkg.folder}; }); })); }.bind(this)); return Promise.all(repos); }.bind(this)) .then(function(repos){ repos.forEach(function(stashedRepo) { this.installDeps(stashedRepo.folder); if (stashedRepo.stashed) { console.log("Folder " + stashedRepo.folder + " had local modifications that were stashed."); } }.bind(this)); }.bind(this)); } }; module.exports = Commands;
PolymerLabs/web-component-workspace
lib/commands.js
JavaScript
bsd-3-clause
6,471
/* f as callable(int) as int = { i | return (i * 2) } def time(block as callable()): pass */ var f:function(int):int = function(i) { return i*2; }; function time(block: function()) {}
bamboo/unityscript
tests/parser/function-types-1.js
JavaScript
bsd-3-clause
186
c3.load("../data/xkcd/c3_data.json"); var C = c3.color.length, W = c3.terms.length, map = {}; for (var i=0; i<W; ++i) { map[c3.terms[i]] = i; } $(function() { for (var w=0; w<W; ++w) { c3.terms.center[w].examples = c3.terms.relatedColors(w, 16); c3.terms.center[w].examples.sort(function(a, b) { a = c3.color[a.index]; b = c3.color[b.index]; return b.L-a.L || b.b-a.b || b.a-a.a; }); } var words = c3.terms.slice(); words.sort(); $("#input").autocomplete({ source: words, delay: 0 }); $("#input").bind("autocompleteclose", update); var q = location.hash.slice(1); if (q && q.length > 0) { d3.select("#input").property("value", q); update(); } }); function set(w) { d3.select("#input").property("value", c3.terms[w]); update(); } function update() { var term = d3.select("#input").property("value").toLowerCase(), idx = map[term]; if (idx === undefined) { d3.selectAll("div.output").html(""); d3.select(".ctrl").style("display", "none"); location.hash = null; return; } d3.selectAll("div.output").selectAll("*").remove(); d3.select(".ctrl").style("display", "block"); // create dictionary swatches var ex = c3.terms.center[idx].examples, cl = [], cur = []; for (var i=0, k=1; i<ex.length; ++i, ++k) { cur.push(ex[i]); if (k % 4 == 0) { cl.push(cur); cur = []; k=0; } } var dt = d3.select("#dict").append("table").attr("class","dict") .selectAll("tr") .data(cl) .enter().append("tr"); var td = dt.selectAll("td") .data(function(d) { return d; }).enter() .append("td") .attr("class", "miniswatch"); td.append("div") .attr("class", "dswatch") .style("background-color", function(c) { return c3.color[c.index]; }) .html("&nbsp;"); td.append("div") .attr("class", "hex") .text(function(c) { return c3.color[c.index]; }); // create thesaurus table // d3.select("#output").append("h3").text("Thesaurus"); // var terms = c3.terms.relatedTerms(idx); terms.shift(); // var tr = d3.select("#output").append("table").selectAll("tr") // .data(terms) // .enter().append("tr"); // tr.append("td").attr("class", "miniswatch").append("div") // .attr("class", "dswatch") // .style("background-color", function(d) { return c3.terms.center[d.index]; }); // tr.append("td").attr("class", "name").append("a") // .attr("href", function(d) { return "javascript:set("+d.index+");"; }) // .text(function(d) { return c3.terms[d.index]; }); // tr.append("td") // .attr("class", "hex") // .text(function(d) { return c3.terms.center[d.index]; }); var rel = c3.terms.relatedTerms(idx), num = 8; // create similar terms table d3.select("#sim").append("h3").text("Similar Colors"); var sim = rel.slice(1, num+1); var tr = d3.select("#sim").append("table") .attr("class", "thesaurus") .selectAll("tr") .data(sim) .enter().append("tr"); tr.append("td").attr("class", "miniswatch").append("div") .attr("class", "dswatch") .style("background-color", function(d) { return c3.terms.center[d.index]; }); tr.append("td").attr("class", "name").append("a") .attr("href", function(d) { return "javascript:set("+d.index+");"; }) .text(function(d) { return c3.terms[d.index]; }); tr.append("td") .attr("class", "hex") .text(function(d) { return c3.terms.center[d.index]; }); // create dissimlar terms table d3.select("#dis").append("h3").text("Opposite Colors"); var dis = rel.slice(rel.length-num, rel.length).reverse(); var tr = d3.select("#dis").append("table") .attr("class", "thesaurus") .selectAll("tr") .data(dis) .enter().append("tr"); tr.append("td").attr("class", "miniswatch").append("div") .attr("class", "dswatch") .style("background-color", function(d) { return c3.terms.center[d.index]; }); tr.append("td").attr("class", "name").append("a") .attr("href", function(d) { return "javascript:set("+d.index+");"; }) .text(function(d) { return c3.terms[d.index]; }); tr.append("td") .attr("class", "hex") .text(function(d) { return c3.terms.center[d.index]; }); location.hash = term; }
jheer/c3
examples/dictionary.js
JavaScript
bsd-3-clause
4,215
// test api var iqengines = require('./lib/iqengines.js'); var assert = require('assert'); var device_id = (new Date()).toISOString(); var api = new iqengines.Api(); var testCase = require('nodeunit').testCase; module.exports.testEnvironmentSetup = testCase({ test: function (test) { test.ok(process.env.IQE_SECRET, "no IQE_SECRET found in environment"); test.ok(process.env.IQE_KEY, "no IQE_KEY found in environment"); test.done(); } }); module.exports.testQueryApi = testCase({ test: function (test) { console.log('=> Sending sample query ..'); qid = api.sendQuery( { img: './testdata/default.jpg', device_id:device_id }, function (res) { // console.log(res); // console.log(qid); // console.log(device_id); console.log('=> Waiting for results ..'); test.deepEqual(res, { data: { error: 0 } }, "unexpected data after querying"); api.waitResults({ device_id:device_id }, function (res) { // console.log(JSON.stringify(res)); // console.log(res.data.results[0].qid); console.log('=> Received results verifying ..'); test.equal(res.data.results[0].qid, qid, "qid from waitResults does not match the qid sent"); console.log('=> Retrieving results manuall'); api.getResult({qid:qid}, function(res){ test.done(); // console.log(res); }); }); }); } }); module.exports.testSimpleRequest = testCase({ test: function(test){ console.log('=> Testing out simplerequest ..'); sRequest = require('./lib/simplerequest.js'); sRequest.test(); test.done(); } });
marks/nodejs-iqengines
tests.js
JavaScript
bsd-3-clause
2,003
/* global cdb */ var ExportMapView = require('../../../../../../javascripts/cartodb/common/dialogs/export_map/export_map_view'); // Just duplicated from old modal to maintain the exiting tests at least. describe('common/dialogs/export/export_view', function () { var view; beforeEach(function () { view = new ExportMapView({ model: new cdb.admin.ExportMapModel({ visualization_id: 'abcd-1234' }), clean_on_hide: true, enter_to_confirm: true }); }); it('should show confirmation', function () { view.render(); expect(view.$('.js-ok').text()).toContain('Ok, export'); }); it('should show pending state loading window', function () { view.model.set('state', 'pending'); view.render(); expect(view.$('.CDB-Text').text()).toContain('Pending ...'); }); it('should show exporting state loading window', function () { view.model.set('state', 'exporting'); view.render(); expect(view.$('.CDB-Text').text()).toContain('Exporting ...'); }); it('should show uploading state loading window', function () { view.model.set('state', 'uploading'); view.render(); expect(view.$('.CDB-Text').text()).toContain('Uploading ...'); }); });
CartoDB/cartodb
lib/assets/test/spec/cartodb/common/dialogs/export_map/export_map_view.spec.js
JavaScript
bsd-3-clause
1,218
require('../support/test_helper'); var assert = require('../support/assert'); var Windshaft = require('../../lib/windshaft'); var ServerOptions = require('../support/server_options'); var testClient = require('../support/test_client'); describe('torque tiles at 0,0 point', function() { var server = new Windshaft.Server(ServerOptions); server.setMaxListeners(0); /* Tiles are represented as in: --------- | TL | TR | |--(0,0)--| | BL | BR | --------- */ var tiles = [ { what: 'tl', x: 3, y: 3, expects: [] }, { what: 'tr', x: 4, y: 3, expects: [] }, { what: 'bl', x: 3, y: 4, expects: [{"x__uint8":1,"y__uint8":1,"vals__uint8":[1],"dates__uint16":[0]}] }, { what: 'br', x: 4, y: 4, expects: [{"x__uint8":0,"y__uint8":1,"vals__uint8":[1],"dates__uint16":[0]}] } ]; tiles.forEach(function(tile) { it(tile.what, function(done) { var query = 'select 1 cartodb_id,' + ' ST_Transform(ST_SetSRID(ST_MakePoint(0, 0), 4326), 3857) the_geom_webmercator'; var mapConfig = { version: '1.3.0', layers: [ { type: 'torque', options: { sql: query, cartocss: [ 'Map {', ' -torque-time-attribute: "cartodb_id";', ' -torque-aggregation-function: "count(cartodb_id)";', ' -torque-frame-count: 1;', ' -torque-animation-duration: 15;', ' -torque-resolution: 128', '}', '#layer {', ' marker-fill: #fff;', ' marker-fill-opacity: 0.4;', ' marker-width: 1;', '}' ].join(' '), cartocss_version: '2.3.0' } } ] }; testClient.getTorque(mapConfig, 0, 3, tile.x, tile.y, function(err, res) { assert.deepEqual(JSON.parse(res.body), tile.expects); done(); }); }); }); });
HydroLogic/Windshaft
test/acceptance/torque_zero_zero.js
JavaScript
bsd-3-clause
2,644
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Rxjs observers only triggered when the async action is matched/enabled */ const Observable_1 = require("rxjs/Observable"); exports.Observable = Observable_1.Observable; const filter_1 = require("rxjs/operators/filter"); const Subject_1 = require("rxjs/Subject"); exports.createObservers = ({ asyncTypes }) => { const createAllObservers = () => { // Gets all the actions through the middleware const rootSubject = new Subject_1.Subject(); // lock out .next api etc const obsOnAll = rootSubject.asObservable(); // filter by requests const obsOnRequest = obsOnAll .pipe(filter_1.filter((action) => action.type.endsWith(asyncTypes.REQUEST))); const obsOnEnd = obsOnAll .pipe(filter_1.filter((action) => action.type.endsWith(asyncTypes.END))); return { obsOnAll, obsOnEnd, obsOnRequest, rootSubject, }; }; return { // after dispatch after: createAllObservers(), // before dispatch before: createAllObservers(), }; }; //# sourceMappingURL=middleware-observers.js.map
beckend/redux-mw-async-flow
build-esnext/middleware/middleware-observers.js
JavaScript
isc
1,237
var Reflux=require("reflux"); var actions=Reflux.createActions([ "add" ,"clear" ]); module.exports=actions;
ksanaforge/testreflux
src/actions.js
JavaScript
isc
109
var request = require('request'); var async = require('async'); var fs = require('fs'); var crypto = require('crypto'); var backUpFileStream; var recoveryFileStream; exports.Reporting = Reporting; function Reporting(config, lgr) { validateConfig(config); this.config = config; if (lgr) { this.lgr = lgr; } else { this.lgr = {info: function(){}, debug: function(){}, error: function(){}}; } this.msgNumPrefix = crypto.createHash('md5').update(Math.random().toString()).digest('hex'); this.msgNumCounter = 0; } Reporting.prototype.msgNum = function () { return "" + this.msgNumPrefix + "_" + (this.msgNumCounter++); }; Reporting.prototype.logMessage = function (topic, msg, cb) { msg._ts = new Date().getTime(); msg._mn = this.msgNum(); msg._ho = this.config.host; msg._cl = this.config.cluster; var self = this; async.parallel([ function (callback) { self.logMessageToHTTP(topic, msg, callback); }, function (callback) { self.logMessageToFile(topic, msg, callback); } ], function (err, results) { if (cb) { return cb(err, results); } }); }; Reporting.prototype.logMessageToHTTP = function (topic, msg, cb) { var self = this; // bugfix 3102: only do realtime sending if config to do so is set if(this.config && this.config.realTimeLoggingEnabled !== true) return cb(); if (this.config && this.config.msgServer && this.config.msgServer.logMessageURL) { var apiToCall = this.config.msgServer.logMessageURL.replace(/TOPIC/g, topic); this.lgr.debug("logMessageToHTTP(): Calling API URL " + apiToCall); request({ uri: apiToCall, method: 'POST', json: msg }, function (error, response, body) { if (!error && response && response.statusCode === 200) { self.lgr.debug("Successfully logged message: " + body); // Print the response } else { self.lgr.error("Error logging message, error: " + JSON.stringify(error) + ", statusCode: " + ((response)?response.statusCode:"no response") + ", body: " + body); if (self.config && self.config.recoveryFiles && self.config.recoveryFiles.fileName) { var fileName = self.config.recoveryFiles.fileName.replace(/TOPIC/g, topic); self.saveToFile(fileName, formatMessageForFile(msg, topic), function () {}); } else { self.lgr.info('Not saving to recovery file, since no recoveryFiles config'); } } return cb(error, {handler: "logMessageToHTTP", result: {status: "ok", reason: "success", info: {response: response, body: body}}}); }); } else { self.lgr.info('Not sending to message server, since no msgServer config'); return cb(null, {handler: "logMessageToHTTP", result: {status: "fail", reason: "no config", info: {}}}); } }; function formatMessageForFile(msg, topic) { return {"MD5": reportingutils.MD5(JSON.stringify(msg)), "message": msg, "topic": topic}; } Reporting.prototype.logMessageToFile = function (topic, msg, cb) { if (this.config && this.config.backupFiles && this.config.backupFiles.fileName) { var fileName = this.config.backupFiles.fileName.replace(/TOPIC/g, topic); this.lgr.debug("logMessageToFile(): fileName: " + fileName); this.saveToFile(fileName, formatMessageForFile(msg, topic), function (err) { if (!err) { return cb(null, {handler: "logMessageToFile", result: {status: "ok", reason: "success", info: {}}}); } }); } else { this.lgr.info('Not saving to backup file, since no backupFiles config'); return cb(null, {handler: "logMessageToFile", result: {status: "fail", reason: "no config", info: {}}}); } }; //note backUpFileStream and recoveryFileStream are singletons and are only created once per application lifecycle. //this is to address the problem of having too many file handles open ticket Reporting.prototype.saveToFile = function (filepath, msg, cb) { var stream; var fileFlags = {flags:'a'}; if(this.config.backupFiles && filepath === this.config.backupFiles.fileName){ if(! backUpFileStream){ backUpFileStream = fs.createWriteStream(filepath,fileFlags); } stream = backUpFileStream; }else if (this.config.recoveryFiles && filepath === this.config.recoveryFiles.fileName){ if(! recoveryFileStream){ recoveryFileStream = fs.createWriteStream(filepath,fileFlags); } stream = recoveryFileStream; }else if(filepath){ //fallback to creating a write stream and destroying it? var tempStream = fs.createWriteStream(filepath , fileFlags); tempStream.write(JSON.stringify(msg) + "\n"); tempStream.destroySoon(); } if(stream){ stream.write(JSON.stringify(msg) + "\n"); } if (cb) return cb(); }; function validateConfig(config) { if (!config) { throw new Error("Invalid config"); } if (!config.host) { throw new Error("Invalid config: no host"); } if (!config.cluster) { throw new Error("Invalid config: no cluster"); } } var reportingutils = { generateID: function (message) { return reportingutils.MD5(JSON.stringify(message)) + "_" + reportingutils.getDatePart(message); }, prefixZeroIfReq: function (val) { val = val.toString(); return val.length > 1 ? val : '0' + val; }, parseMonth: function (month) { return reportingutils.prefixZeroIfReq(month + 1); }, parseDate: function (date) { return reportingutils.prefixZeroIfReq(date); }, toYYYYMMDD: function (ts) { var tsDate = new Date(ts); var ret = tsDate.getFullYear() + reportingutils.parseMonth(tsDate.getMonth()) + reportingutils.parseDate(tsDate.getDate()); return ret; }, getDefaultDateForMessage: function () { return 0; }, getDatePart: function(msg) { var ts = (msg._ts)?msg._ts:reportingutils.getDefaultDateForMessage(); return reportingutils.toYYYYMMDD(ts); }, MD5: function(str) { return crypto.createHash('md5').update(str).digest('hex'); } }; exports.reportingutils = reportingutils;
briangallagher/testDrivenDevelopment
node_modules/fh-mbaas-api/node_modules/fh-mbaas-express/node_modules/fh-reportingclient/lib/fh-reporting.js
JavaScript
mit
6,010
import React from 'react'; import {BaseMixin, ContentMixin} from './../../common/common.js'; import './label.less'; export default React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ContentMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: "UU5.Forms.Label", classNames: { main: "uu5-forms-label" } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { for: React.PropTypes.string }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps: function () { return { for: null }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle shouldComponentUpdate(newProps, newState){ let result = false; if (newProps.for != this.props.for || newProps.content != this.props.content || newProps.children != this.props.children) { result = true; } return result; }, //@@viewOff:standardComponentLifeCycle //@@viewOn:interface //@@viewOff:interface //@@viewOn:overridingMethods //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _getMainAttrs(){ let mainAttrs = this.getMainAttrs(); this.props.for && (mainAttrs.htmlFor = this.props.for); mainAttrs.className += ' ' + this.props.colWidth; return mainAttrs; }, //@@viewOff:componentSpecificHelpers //@@viewOn:render render: function () { return ( <label {...this._getMainAttrs()}> {this.getChildren()} </label> ); } //@@viewOn:render });
UnicornCollege/ucl.itkpd.configurator
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-forms-v3-internal-label.js
JavaScript
mit
1,523
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Web Job Information. * * @extends models['ProxyOnlyResource'] */ class FunctionEnvelope extends models['ProxyOnlyResource'] { /** * Create a FunctionEnvelope. * @member {string} [functionEnvelopeName] Function name. * @member {string} [functionAppId] Function App ID. * @member {string} [scriptRootPathHref] Script root path URI. * @member {string} [scriptHref] Script URI. * @member {string} [configHref] Config URI. * @member {string} [secretsFileHref] Secrets file URI. * @member {string} [href] Function URI. * @member {object} [config] Config information. * @member {object} [files] File list. * @member {string} [testData] Test data used when testing via the Azure * Portal. */ constructor() { super(); } /** * Defines the metadata of FunctionEnvelope * * @returns {object} metadata of FunctionEnvelope * */ mapper() { return { required: false, serializedName: 'FunctionEnvelope', type: { name: 'Composite', className: 'FunctionEnvelope', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, kind: { required: false, serializedName: 'kind', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, functionEnvelopeName: { required: false, readOnly: true, serializedName: 'properties.name', type: { name: 'String' } }, functionAppId: { required: false, readOnly: true, serializedName: 'properties.functionAppId', type: { name: 'String' } }, scriptRootPathHref: { required: false, serializedName: 'properties.scriptRootPathHref', type: { name: 'String' } }, scriptHref: { required: false, serializedName: 'properties.scriptHref', type: { name: 'String' } }, configHref: { required: false, serializedName: 'properties.configHref', type: { name: 'String' } }, secretsFileHref: { required: false, serializedName: 'properties.secretsFileHref', type: { name: 'String' } }, href: { required: false, serializedName: 'properties.href', type: { name: 'String' } }, config: { required: false, serializedName: 'properties.config', type: { name: 'Object' } }, files: { required: false, serializedName: 'properties.files', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, testData: { required: false, serializedName: 'properties.testData', type: { name: 'String' } } } } }; } } module.exports = FunctionEnvelope;
lmazuel/azure-sdk-for-node
lib/services/webSiteManagement2/lib/models/functionEnvelope.js
JavaScript
mit
4,334
/* * MelonJS Game Engine * Copyright (C) 2011 - 2013, Olivier BIOT * http://www.melonjs.org * */ (function($) { /** * a generic 2D Vector Object * @class * @extends Object * @memberOf me * @constructor * @param {Number} [x=0] x value of the vector * @param {Number} [y=0] y value of the vector */ me.Vector2d = Object.extend( /** @scope me.Vector2d.prototype */ { /** * x value of the vector * @public * @type Number * @name x * @memberOf me.Vector2d */ x : 0, /** * y value of the vector * @public * @type Number * @name y * @memberOf me.Vector2d */ y : 0, /** @ignore */ init : function(x, y) { this.x = x || 0; this.y = y || 0; }, /** * set the Vector x and y properties to the given values<br> * @name set * @memberOf me.Vector2d * @function * @param {Number} x * @param {Number} y * @return {me.Vector2d} Reference to this object for method chaining */ set : function(x, y) { this.x = x; this.y = y; return this; }, /** * set the Vector x and y properties to 0 * @name setZero * @memberOf me.Vector2d * @function * @return {me.Vector2d} Reference to this object for method chaining */ setZero : function() { return this.set(0, 0); }, /** * set the Vector x and y properties using the passed vector * @name setV * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {me.Vector2d} Reference to this object for method chaining */ setV : function(v) { this.x = v.x; this.y = v.y; return this; }, /** * Add the passed vector to this vector * @name add * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {me.Vector2d} Reference to this object for method chaining */ add : function(v) { this.x += v.x; this.y += v.y; return this; }, /** * Substract the passed vector to this vector * @name sub * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {me.Vector2d} Reference to this object for method chaining */ sub : function(v) { this.x -= v.x; this.y -= v.y; return this; }, /** * Multiply this vector values by the passed vector * @name scale * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {me.Vector2d} Reference to this object for method chaining */ scale : function(v) { this.x *= v.x; this.y *= v.y; return this; }, /** * Divide this vector values by the passed value * @name div * @memberOf me.Vector2d * @function * @param {Number} value * @return {me.Vector2d} Reference to this object for method chaining */ div : function(n) { this.x /= n; this.y /= n; return this; }, /** * Update this vector values to absolute values * @name abs * @memberOf me.Vector2d * @function * @return {me.Vector2d} Reference to this object for method chaining */ abs : function() { if (this.x < 0) this.x = -this.x; if (this.y < 0) this.y = -this.y; return this; }, /** * Clamp the vector value within the specified value range * @name clamp * @memberOf me.Vector2d * @function * @param {Number} low * @param {Number} high * @return {me.Vector2d} new me.Vector2d */ clamp : function(low, high) { return new me.Vector2d(this.x.clamp(low, high), this.y.clamp(low, high)); }, /** * Clamp this vector value within the specified value range * @name clampSelf * @memberOf me.Vector2d * @function * @param {Number} low * @param {Number} high * @return {me.Vector2d} Reference to this object for method chaining */ clampSelf : function(low, high) { this.x = this.x.clamp(low, high); this.y = this.y.clamp(low, high); return this; }, /** * Update this vector with the minimum value between this and the passed vector * @name minV * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {me.Vector2d} Reference to this object for method chaining */ minV : function(v) { this.x = this.x < v.x ? this.x : v.x; this.y = this.y < v.y ? this.y : v.y; return this; }, /** * Update this vector with the maximum value between this and the passed vector * @name maxV * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {me.Vector2d} Reference to this object for method chaining */ maxV : function(v) { this.x = this.x > v.x ? this.x : v.x; this.y = this.y > v.y ? this.y : v.y; return this; }, /** * Floor the vector values * @name floor * @memberOf me.Vector2d * @function * @return {me.Vector2d} new me.Vector2d */ floor : function() { return new me.Vector2d(~~this.x, ~~this.y); }, /** * Floor this vector values * @name floorSelf * @memberOf me.Vector2d * @function * @return {me.Vector2d} Reference to this object for method chaining */ floorSelf : function() { this.x = ~~this.x; this.y = ~~this.y; return this; }, /** * Ceil the vector values * @name ceil * @memberOf me.Vector2d * @function * @return {me.Vector2d} new me.Vector2d */ ceil : function() { return new me.Vector2d(Math.ceil(this.x), Math.ceil(this.y)); }, /** * Ceil this vector values * @name ceilSelf * @memberOf me.Vector2d * @function * @return {me.Vector2d} Reference to this object for method chaining */ ceilSelf : function() { this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); return this; }, /** * Negate the vector values * @name negate * @memberOf me.Vector2d * @function * @return {me.Vector2d} new me.Vector2d */ negate : function() { return new me.Vector2d(-this.x, -this.y); }, /** * Negate this vector values * @name negateSelf * @memberOf me.Vector2d * @function * @return {me.Vector2d} Reference to this object for method chaining */ negateSelf : function() { this.x = -this.x; this.y = -this.y; return this; }, /** * Copy the x,y values of the passed vector to this one * @name copy * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {me.Vector2d} Reference to this object for method chaining */ copy : function(v) { this.x = v.x; this.y = v.y; return this; }, /** * return true if the two vectors are the same * @name equals * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {Boolean} */ equals : function(v) { return ((this.x === v.x) && (this.y === v.y)); }, /** * return the length (magnitude) of this vector * @name length * @memberOf me.Vector2d * @function * @return {Number} */ length : function() { return Math.sqrt(this.x * this.x + this.y * this.y); }, /** * normalize this vector (scale the vector so that its magnitude is 1) * @name normalize * @memberOf me.Vector2d * @function * @return {Number} */ normalize : function() { var len = this.length(); // some limit test if (len < Number.MIN_VALUE) { return 0.0; } var invL = 1.0 / len; this.x *= invL; this.y *= invL; return len; }, /** * return the dot product of this vector and the passed one * @name dotProduct * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {Number} */ dotProduct : function(/**me.Vector2d*/ v) { return this.x * v.x + this.y * v.y; }, /** * return the distance between this vector and the passed one * @name distance * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {Number} */ distance : function(v) { return Math.sqrt((this.x - v.x) * (this.x - v.x) + (this.y - v.y) * (this.y - v.y)); }, /** * return the angle between this vector and the passed one * @name angle * @memberOf me.Vector2d * @function * @param {me.Vector2d} v * @return {Number} angle in radians */ angle : function(v) { return Math.atan2((v.y - this.y), (v.x - this.x)); }, /** * return a clone copy of this vector * @name clone * @memberOf me.Vector2d * @function * @return {me.Vector2d} new me.Vector2d */ clone : function() { return new me.Vector2d(this.x, this.y); }, /** * convert the object to a string representation * @name toString * @memberOf me.Vector2d * @function * @return {String} */ toString : function() { return 'x:' + this.x + ',y:' + this.y; } }); })(window);
CreativeOutbreak/melonJS
src/math/vector.js
JavaScript
mit
8,644
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['en-nr'] = [ 'en-NR', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'AUD', '$', 'Australian Dollar', {'AUD': ['$'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural, [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
Toxicable/angular
packages/common/locales/global/en-NR.js
JavaScript
mit
2,409
// Karma configuration // Generated on Wed Apr 29 2015 16:48:15 GMT-0400 (EDT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai', 'sinon'], // list of files / patterns to load in the browser files: [ 'examples/vendor/javascripts/jquery-1.11.2.js', 'src/index.js', 'test/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
artsy/day-schedule-selector
karma.conf.js
JavaScript
mit
1,655
'use strict'; const helper = require('./common').helper; const validate = require('./common').validate; /** * Tests for the Grant Type of Client. * This follows the testing guide roughly from * https://github.com/FrankHassanabad/Oauth2orizeRecipes/wiki/OAuth2orize-Authorization-Server-Tests */ describe('Grant Type Client', () => { it('should work with asking for an access token', () => helper.postOAuthClient({}) .then(([response, body]) => { validate.accessToken(response, body); return JSON.parse(body); }) .then(tokens => helper.getClientInfo(tokens.access_token)) .then(([response, body]) => validate.clientJson(response, body))); it('should work with a scope of undefined', () => helper.postOAuthClient(undefined) .then(([response, body]) => { validate.accessToken(response, body); return JSON.parse(body); }) .then(tokens => helper.getClientInfo(tokens.access_token)) .then(([response, body]) => validate.clientJson(response, body))); });
cmcampione/thingshub
useful-projects/Oauth2orizeRecipes/authorization-server/test/integration/grant_type_client.js
JavaScript
mit
1,025
/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); class RelativeUrlRuntimeModule extends HelperRuntimeModule { constructor() { super("relative url"); } /** * @returns {string} runtime code */ generate() { const { runtimeTemplate } = this.compilation; return Template.asString([ `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, Template.indent([ 'var realUrl = new URL(url, "x:/");', "var values = {};", "for (var key in realUrl) values[key] = realUrl[key];", "values.href = url;", 'values.pathname = url.replace(/[?#].*/, "");', 'values.origin = values.protocol = "";', `values.toString = values.toJSON = ${runtimeTemplate.returningFunction( "url" )};`, "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" ]), "};", `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;` ]); } } module.exports = RelativeUrlRuntimeModule;
webpack/webpack
lib/runtime/RelativeUrlRuntimeModule.js
JavaScript
mit
1,178
/* @flow */ import { EventEmitter } from 'events'; import Dispatcher from "./dispatcher"; import IncomingMessage from "./incoming-message"; import ServerResponse from "./server-response"; let dispatcher: Dispatcher; export type EmulatedXMLHttpRequestType = { method: string, _parsedUrl: { path: string, pathname: string, search: string, query: string, href: string }, requestHeaders: Object, send: () => void }; export type CookieType = { name: string, value: string }; class Server extends EventEmitter { timeout: number; port: number; host: string; maxHeadersCount: number; dispatcher: Dispatcher; requestListener: (req: IncomingMessage, res: ServerResponse) => void; constructor(requestListener: (req: IncomingMessage, res: ServerResponse) => void) { super(); this.requestListener = requestListener; if (!dispatcher) { dispatcher = new Dispatcher(); } this.dispatcher = dispatcher; this.timeout = 120000; this.maxHeadersCount = 1000; } get connections() : number { return 1; } getConnections(cb: (err: ?Object, connections: number) => void) { cb(null, 1); } get address() : { port: number, family: string, address: string } { return { port: this.port, family: 'IPv4', address: this.host }; } listen() { let cb; if (arguments.length === 3) { this.port = arguments[0]; this.host = arguments[1]; cb = arguments[2]; } else if (arguments.length === 2) { this.port = arguments[0]; if (typeof arguments[1] === "function") { cb = arguments[1]; } else { this.host = arguments[1]; } } else if (arguments.length === 1) { this.port = arguments[0]; this.host = ""; } this.dispatcher.add(this.port, this.host, this); this.emit("listening"); if (cb) { cb(); } } close() : void { if (this.port) { this.dispatcher.remove(this.port, this.host); } else { throw new Error("Server is not listening."); } } setTimeout(msecs: number, cb: Function) : Server { setTimeout(cb, msecs); return this; } __XMLHttpRequest_send(xhr: EmulatedXMLHttpRequestType, data: Object) { console.log(xhr); const req = new IncomingMessage(); req.method = xhr.method; req.url = xhr._parsedUrl.path; req.headers = xhr.requestHeaders; const res = new ServerResponse(); res.setHeader("Date", Date.now().toString()); this.requestListener(req, res); } } export default Server;
foraproject/isotropy-http-in-browser
src/server.js
JavaScript
mit
2,549
StartTest(function(outerT) { outerT.testExtJS(function (t) { var viewport = new Ext.Viewport({ id : 'viewport', items : [ { id : 'panel1', title : 'foo1', height : 50, html : '<div class="quix" id="test_div1"></div>' }, { id : 'panel2', title : 'foo2', html : '<div class="quix" id="test_div2"></div>', height : 50, items : [ { xtype : 'button', text : 'test', id : 'test-button' } ] }, { xtype : 'textfield', cls : 'test-field', id : 'test-field' } ] }) t.is(t.normalizeElement('>>#panel1'), Ext.getCmp('panel1').body.dom, "Normalize element accept component query"); t.is(t.normalizeElement('body'), document.body, 'body element is found with CSS selector'); t.throwsOk(function () { t.compositeQuery('panel[title=foo]') }, '', 'Invalid composite query selector: panel[title=foo]') t.throwsOk(function () { t.compositeQuery('panel[title=barbaz] => div.quix', null, false) }, '', 'Component query selector should return at least one component') t.isDeeply( t.compositeQuery('viewport => div.quix'), [ Ext.get('test_div1').dom, Ext.get('test_div2').dom ], 'Found the div with class `quix` inside of whole viewport' ) t.isDeeply( t.compositeQuery('panel[title=foo1] => div.quix'), [ Ext.get('test_div1').dom ], 'Found the div with class `quix` only inside of panel1' ) t.isDeeply( t.compositeQuery('panel[title=foo1] => div.quix', Ext.getCmp('viewport')), [ Ext.get('test_div1').dom ], 'Same result with specified root' ) t.isDeeply( t.compositeQuery('panel[title=foo1] => div.quix', Ext.getCmp('panel2'), true), [], 'Not found any results with `panel2` as root' ) t.willFireNTimes(Ext.getCmp('test-button'), 'click', 1, 'A single click on this button should be detected') // not using `t.chain` on purpose - to verify that usual methods can accept the composite query t.type('viewport => .test-field input', 'Some text', function () { t.is(Ext.getCmp('test-field').getValue(), 'Some text', 'The result of the composite query, passed as argument to the `t.type` is correct') t.click('panel[title="foo2"] => .x-btn') }) }); });
arthurakay/AppInspector
app/test/siesta-2.0.5-lite/tests/530_extjs_composite_query.t.js
JavaScript
mit
3,257
import { Button, Icon } from '@rocket.chat/fuselage'; import React from 'react'; import { useTranslation } from '../../contexts/TranslationContext'; export function ResetSettingButton(props) { const t = useTranslation(); return <Button aria-label={t('Reset')} danger ghost small title={t('Reset')} style={{ padding: 0 }} {...props} > <Icon name='undo' /> </Button>; }
Sing-Li/Rocket.Chat
client/admin/settings/ResetSettingButton.js
JavaScript
mit
391
function fib(){ var start = 0; var next = 0; function nacci(){ if ((start == 0) && (next == 0)){ next = 1; sum = 1; }//end if else{ var sum = start + next; start = next; next = sum; }//end else console.log(sum); } return nacci; }; var fibCounter = fib(); fibCounter() // should console.log "1" fibCounter() // should console.log "1" fibCounter() // should console.log "2" fibCounter() // should console.log "3" fibCounter() // should console.log "5" fibCounter() // should console.log "8"
dallaspythondojo/nice
Hodge_Zach/Assignments/fib_nacci/fib_nacci.js
JavaScript
mit
611
/* product all the arguments passed in to the function usage: product(1, 2) returns 2 product(1, 2, 3) returns 6 product(1, 2, 3, 4) returns 24 */ var product = function () { var args = Array.prototype.slice.call(arguments); var product = args.reduce(function (a, b) { return a * b; }); return product; } anything.prototype.product = product
Sha-Grisha/anything.js
src/product.js
JavaScript
mit
383
#!/usr/bin/env node ;(function(undefined) { 'use strict'; /** Load modules */ var fs = require('fs'), path = require('path'), vm = require('vm'), build = require('../build.js'), minify = require('../build/minify'), _ = require('../lodash.js'); /** The unit testing framework */ var QUnit = ( global.addEventListener || (global.addEventListener = Function.prototype), global.QUnit = require('../vendor/qunit/qunit/qunit.js'), require('../vendor/qunit-clib/qunit-clib.js'), global.addEventListener === Function.prototype && delete global.addEventListener, global.QUnit ); /** The time limit for the tests to run (milliseconds) */ var timeLimit = process.argv.reduce(function(result, value, index) { if (/--time-limit/.test(value)) { return parseInt(process.argv[index + 1].replace(/(\d+h)?(\d+m)?(\d+s)?/, function(match, h, m, s) { return ((parseInt(h) || 0) * 3600000) + ((parseInt(m) || 0) * 60000) + ((parseInt(s) || 0) * 1000); })) || result; } return result; }, 0); /** Used to associate aliases with their real names */ var aliasToRealMap = { 'all': 'every', 'any': 'some', 'collect': 'map', 'detect': 'find', 'drop': 'rest', 'each': 'forEach', 'extend': 'assign', 'foldl': 'reduce', 'foldr': 'reduceRight', 'head': 'first', 'include': 'contains', 'inject': 'reduce', 'methods': 'functions', 'select': 'filter', 'tail': 'rest', 'take': 'first', 'unique': 'uniq' }; /** Used to associate real names with their aliases */ var realToAliasMap = { 'assign': ['extend'], 'contains': ['include'], 'every': ['all'], 'filter': ['select'], 'find': ['detect'], 'first': ['head', 'take'], 'forEach': ['each'], 'functions': ['methods'], 'map': ['collect'], 'reduce': ['foldl', 'inject'], 'reduceRight': ['foldr'], 'rest': ['drop', 'tail'], 'some': ['any'], 'uniq': ['unique'] }; /** List of all Lo-Dash methods */ var allMethods = _.functions(_) .filter(function(methodName) { return !/^_/.test(methodName); }) .concat('chain') .sort(); /** List of "Arrays" category methods */ var arraysMethods = [ 'compact', 'difference', 'drop', 'first', 'flatten', 'head', 'indexOf', 'initial', 'intersection', 'last', 'lastIndexOf', 'object', 'range', 'rest', 'sortedIndex', 'tail', 'take', 'union', 'uniq', 'unique', 'without', 'zip' ]; /** List of "Chaining" category methods */ var chainingMethods = [ 'mixin', 'tap', 'value' ]; /** List of "Collections" category methods */ var collectionsMethods = [ 'all', 'any', 'at', 'collect', 'contains', 'countBy', 'detect', 'each', 'every', 'filter', 'find', 'foldl', 'foldr', 'forEach', 'groupBy', 'include', 'inject', 'invoke', 'map', 'max', 'min', 'pluck', 'reduce', 'reduceRight', 'reject', 'select', 'shuffle', 'size', 'some', 'sortBy', 'toArray', 'where' ]; /** List of "Functions" category methods */ var functionsMethods = [ 'after', 'bind', 'bindAll', 'bindKey', 'compose', 'debounce', 'defer', 'delay', 'memoize', 'once', 'partial', 'partialRight', 'throttle', 'wrap' ]; /** List of "Objects" category methods */ var objectsMethods = [ 'assign', 'clone', 'cloneDeep', 'defaults', 'extend', 'forIn', 'forOwn', 'functions', 'has', 'invert', 'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement', 'isEmpty', 'isEqual', 'isFinite', 'isFunction', 'isNaN', 'isNull', 'isNumber', 'isObject', 'isPlainObject', 'isRegExp', 'isString', 'isUndefined', 'keys', 'methods', 'merge', 'omit', 'pairs', 'pick', 'values' ]; /** List of "Utilities" category methods */ var utilityMethods = [ 'escape', 'identity', 'noConflict', 'random', 'result', 'template', 'times', 'unescape', 'uniqueId' ]; /** List of Backbone's Lo-Dash dependencies */ var backboneDependencies = [ 'bind', 'bindAll', 'chain', 'clone', 'contains', 'countBy', 'defaults', 'escape', 'every', 'extend', 'filter', 'find', 'first', 'forEach', 'groupBy', 'has', 'indexOf', 'initial', 'invoke', 'isArray', 'isEmpty', 'isEqual', 'isFunction', 'isObject', 'isRegExp', 'isString', 'keys', 'last', 'lastIndexOf', 'map', 'max', 'min', 'mixin', 'once', 'pick', 'reduce', 'reduceRight', 'reject', 'rest', 'result', 'shuffle', 'size', 'some', 'sortBy', 'sortedIndex', 'toArray', 'uniqueId', 'value', 'without' ]; /** List of methods used by Underscore */ var underscoreMethods = _.without.apply(_, [allMethods].concat([ 'at', 'bindKey', 'cloneDeep', 'forIn', 'forOwn', 'isPlainObject', 'merge', 'partialRight' ])); /*--------------------------------------------------------------------------*/ /** * Creates a context object to use with `vm.runInContext`. * * @private * @returns {Object} Returns a new context object. */ function createContext() { return vm.createContext({ 'clearTimeout': clearTimeout, 'setTimeout': setTimeout }); } /** * Expands a list of method names to include real and alias names. * * @private * @param {Array} methodNames The array of method names to expand. * @returns {Array} Returns a new array of expanded method names. */ function expandMethodNames(methodNames) { return methodNames.reduce(function(result, methodName) { var realName = getRealName(methodName); result.push.apply(result, [realName].concat(getAliases(realName))); return result; }, []); } /** * Gets the aliases associated with a given function name. * * @private * @param {String} funcName The name of the function to get aliases for. * @returns {Array} Returns an array of aliases. */ function getAliases(funcName) { return realToAliasMap[funcName] || []; } /** * Gets the names of methods belonging to the given `category`. * * @private * @param {String} category The category to filter by. * @returns {Array} Returns a new array of method names belonging to the given category. */ function getMethodsByCategory(category) { switch (category) { case 'Arrays': return arraysMethods.slice(); case 'Chaining': return chainingMethods.slice(); case 'Collections': return collectionsMethods.slice(); case 'Functions': return functionsMethods.slice(); case 'Objects': return objectsMethods.slice(); case 'Utilities': return utilityMethods.slice(); } return []; } /** * Gets the real name, not alias, of a given function name. * * @private * @param {String} funcName The name of the function to resolve. * @returns {String} Returns the real name. */ function getRealName(funcName) { return aliasToRealMap[funcName] || funcName; } /** * Tests if a given method on the `lodash` object can be called successfully. * * @private * @param {Object} lodash The built Lo-Dash object. * @param {String} methodName The name of the Lo-Dash method to test. * @param {String} message The unit test message. */ function testMethod(lodash, methodName, message) { var pass = true, array = [['a', 1], ['b', 2], ['c', 3]], object = { 'a': 1, 'b': 2, 'c': 3 }, noop = function() {}, string = 'abc', template = '<%= a %>', func = lodash[methodName]; try { if (arraysMethods.indexOf(methodName) > -1) { if (/(?:indexOf|sortedIndex|without)$/i.test(methodName)) { func(array, string); } else if (/^(?:difference|intersection|union|uniq|zip)/.test(methodName)) { func(array, array); } else if (methodName == 'range') { func(2, 4); } else { func(array); } } else if (chainingMethods.indexOf(methodName) > -1) { if (methodName == 'chain') { lodash.chain(array); lodash(array).chain(); } else if (methodName == 'mixin') { lodash.mixin({}); } else { lodash(array)[methodName](noop); } } else if (collectionsMethods.indexOf(methodName) > -1) { if (/^(?:count|group|sort)By$/.test(methodName)) { func(array, noop); func(array, string); func(object, noop); func(object, string); } else if (/^(?:size|toArray)$/.test(methodName)) { func(array); func(object); } else if (methodName == 'at') { func(array, 0, 2); func(object, 'a', 'c'); } else if (methodName == 'invoke') { func(array, 'slice'); func(object, 'toFixed'); } else if (methodName == 'where') { func(array, object); func(object, object); } else { func(array, noop, object); func(object, noop, object); } } else if (functionsMethods.indexOf(methodName) > -1) { if (methodName == 'after') { func(1, noop); } else if (methodName == 'bindAll') { func({ 'noop': noop }); } else if (methodName == 'bindKey') { func(lodash, 'identity', array, string); } else if (/^(?:bind|partial(?:Right)?)$/.test(methodName)) { func(noop, object, array, string); } else if (/^(?:compose|memoize|wrap)$/.test(methodName)) { func(noop, noop); } else if (/^(?:debounce|throttle)$/.test(methodName)) { func(noop, 100); } else { func(noop); } } else if (objectsMethods.indexOf(methodName) > -1) { if (methodName == 'clone') { func(object); func(object, true); } else if (/^(?:defaults|extend|merge)$/.test(methodName)) { func({}, object); } else if (/^(?:forIn|forOwn)$/.test(methodName)) { func(object, noop); } else if (/^(?:omit|pick)$/.test(methodName)) { func(object, 'b'); } else if (methodName == 'has') { func(object, string); } else { func(object); } } else if (utilityMethods.indexOf(methodName) > -1) { if (methodName == 'result') { func(object, 'b'); } else if (methodName == 'template') { func(template, object); func(template, null, { 'imports': object })(object); } else if (methodName == 'times') { func(2, noop, object); } else { func(string, object); } } } catch(e) { console.log(e); pass = false; } ok(pass, '_.' + methodName + ': ' + message); } /*--------------------------------------------------------------------------*/ QUnit.module('minified AMD snippet'); (function() { var start = _.once(QUnit.start); asyncTest('`lodash`', function() { build(['-s'], function(data) { // used by r.js build optimizer var defineHasRegExp = /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g, basename = path.basename(data.outputPath, '.js'); ok(!!defineHasRegExp.exec(data.source), basename); start(); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('template builds'); (function() { var templatePath = __dirname + '/template'; asyncTest('`lodash template=*.jst`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'template=' + templatePath + '/*.jst'], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); var object = { 'a': { 'people': ['moe', 'larry', 'curly'] }, 'b': { 'epithet': 'stooge' }, 'c': { 'name': 'ES6' } }; context._ = _; vm.runInContext(data.source, context); equal(_.templates.a(object.a).replace(/[\r\n]+/g, ''), '<ul><li>moe</li><li>larry</li><li>curly</li></ul>', basename); equal(_.templates.b(object.b), 'Hello stooge.', basename); equal(_.templates.c(object.c), 'Hello ES6!', basename); delete _.templates; start(); }); }); var commands = [ '', 'moduleId=underscore' ]; commands.forEach(function(command) { var expectedId = /underscore/.test(command) ? 'underscore' : 'lodash'; asyncTest('`lodash template=*.jst exports=amd' + (command ? ' ' + command : '') + '`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'template=' + templatePath + '/*.jst', 'exports=amd'].concat(command || []), function(data) { var moduleId, basename = path.basename(data.outputPath, '.js'), context = createContext(); context.define = function(requires, factory) { factory(_); moduleId = requires[0]; }; context.define.amd = {}; vm.runInContext(data.source, context); equal(moduleId, expectedId, basename); ok('a' in _.templates && 'b' in _.templates, basename); equal(_.templates.a({ 'people': ['moe', 'larry'] }), '<ul>\n<li>moe</li><li>larry</li>\n</ul>', basename); delete _.templates; start(); }); }); asyncTest('`lodash settings=...' + (command ? ' ' + command : '') + '`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'template=' + templatePath + '/*.tpl', 'settings={interpolate:/{{([\\s\\S]+?)}}/}'].concat(command || []), function(data) { var moduleId, basename = path.basename(data.outputPath, '.js'), context = createContext(); var object = { 'd': { 'name': 'Mustache' } }; context.define = function(requires, factory) { factory(_); moduleId = requires[0]; }; context.define.amd = {}; vm.runInContext(data.source, context); equal(moduleId, expectedId, basename); equal(_.templates.d(object.d), 'Hello Mustache!', basename); delete _.templates; start(); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('independent builds'); (function() { var reCustom = /Custom Build/, reLicense = /^\/\**\s+\* @license[\s\S]+?\*\/\n/; asyncTest('debug only', function() { var start = _.once(QUnit.start); build(['-d', '-s'], function(data) { equal(path.basename(data.outputPath, '.js'), 'lodash'); start(); }); }); asyncTest('debug custom', function() { var start = _.once(QUnit.start); build(['-d', '-s', 'backbone'], function(data) { equal(path.basename(data.outputPath, '.js'), 'lodash.custom'); var comment = data.source.match(reLicense); ok(reCustom.test(comment)); start(); }); }); asyncTest('minified only', function() { var start = _.once(QUnit.start); build(['-m', '-s'], function(data) { equal(path.basename(data.outputPath, '.js'), 'lodash.min'); start(); }); }); asyncTest('minified custom', function() { var start = _.once(QUnit.start); build(['-m', '-s', 'backbone'], function(data) { equal(path.basename(data.outputPath, '.js'), 'lodash.custom.min'); var comment = data.source.match(reLicense); ok(reCustom.test(comment)); start(); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('source maps'); (function() { var commands = [ '-p', '--source-map' ]; var outputPaths = [ '', '-o foo.js' ]; commands.forEach(function(command) { outputPaths.forEach(function(outputPath) { asyncTest('`lodash ' + command + (outputPath ? ' ' + outputPath : '') + '`', function() { var start = _.once(QUnit.start); outputPath = outputPath ? outputPath.split(' ') : []; build(['-s', '-m', command].concat(outputPath), function(data) { var basename = path.basename(data.outputPath, '.js'), comment = (/(\s*\/\/.*\s*|\s*\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\s*)$/.exec(data.source) || [])[0], sourceMap = JSON.parse(data.sourceMap); ok(RegExp('/\\*\\n//@ sourceMappingURL=' + basename + '.map\\n\\*/').test(comment), basename); equal(sourceMap.file, basename + '.js', basename); deepEqual(sourceMap.sources, ['lodash.js'], basename); start(); }); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('strict modifier'); (function() { var object = Object.freeze({ 'a': _.identity, 'b': undefined }); var modes = [ 'non-strict', 'strict' ]; modes.forEach(function(strictMode, index) { asyncTest(strictMode + ' should ' + (index ? 'error': 'silently fail') + ' attempting to overwrite read-only properties', function() { var commands = ['-s', 'include=bindAll,defaults,extend'], start = _.after(2, _.once(QUnit.start)); if (index) { commands.push('strict'); } build(commands, function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); vm.runInContext(data.source, context); var lodash = context._; var actual = _.every([ function() { lodash.bindAll(object); }, function() { lodash.extend(object, { 'a': 1 }); }, function() { lodash.defaults(object, { 'b': 2 }); } ], function(fn) { var pass = !index; try { fn(); } catch(e) { pass = !!index; } return pass; }); ok(actual, basename); start(); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('underscore chaining methods'); (function() { var commands = [ 'backbone', 'underscore' ]; commands.forEach(function(command) { asyncTest('`lodash ' + command +'`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', command], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); vm.runInContext(data.source, context); var lodash = context._; ok(lodash.chain(1) instanceof lodash, '_.chain: ' + basename); ok(lodash(1).chain() instanceof lodash, '_#chain: ' + basename); var wrapped = lodash(1); strictEqual(wrapped.identity(), 1, '_(...) wrapped values are not chainable by default: ' + basename); equal(String(wrapped) === '1', false, '_#toString should not be implemented: ' + basename); equal(Number(wrapped) === 1 , false, '_#valueOf should not be implemented: ' + basename); wrapped.chain(); ok(wrapped.has('x') instanceof lodash, '_#has returns wrapped values when chaining: ' + basename); ok(wrapped.join() instanceof lodash, '_#join returns wrapped values when chaining: ' + basename); wrapped = lodash([1, 2, 3]); ok(wrapped.pop() instanceof lodash, '_#pop returns wrapped values: ' + basename); ok(wrapped.shift() instanceof lodash, '_#shift returns wrapped values: ' + basename); deepEqual(wrapped.splice(0, 0).value(), [2], '_#splice returns wrapper: ' + basename); start(); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('underscore modifier'); (function() { asyncTest('modified methods should work correctly', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'underscore'], function(data) { var last, array = [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }], basename = path.basename(data.outputPath, '.js'), context = createContext(); vm.runInContext(data.source, context); var lodash = context._; var object = { 'fn': lodash.bind(function(foo) { return foo + this.bar; }, { 'bar': 1 }, 1) }; equal(object.fn(), 2, '_.bind: ' + basename); var actual = lodash.clone('a', function() { return this.a; }, { 'a': 'A' }); equal(actual, 'a', '_.clone should ignore `callback` and `thisArg`: ' + basename); strictEqual(lodash.clone(array, true)[0], array[0], '_.clone should ignore `deep`: ' + basename); strictEqual(lodash.contains({ 'a': 1, 'b': 2 }, 1), true, '_.contains should work with objects: ' + basename); strictEqual(lodash.contains([1, 2, 3], 1, 2), true, '_.contains should ignore `fromIndex`: ' + basename); strictEqual(lodash.every([true, false, true]), false, '_.every: ' + basename); function Foo() {} Foo.prototype = { 'a': 1 }; actual = lodash.defaults({ 'a': null }, { 'a': 1 }); strictEqual(actual.a, 1, '_.defaults should overwrite `null` values: ' + basename); deepEqual(lodash.defaults({}, new Foo), Foo.prototype, '_.defaults should assign inherited `source` properties: ' + basename); deepEqual(lodash.extend({}, new Foo), Foo.prototype, '_.extend should assign inherited `source` properties: ' + basename); actual = lodash.extend({}, { 'a': 0 }, function(a, b) { return this[b]; }, [2]); strictEqual(actual.a, 0, '_.extend should ignore `callback` and `thisArg`: ' + basename); actual = lodash.find(array, function(value) { return 'a' in value; }); equal(actual, _.first(array), '_.find: ' + basename); actual = lodash.forEach(array, function(value) { last = value; return false; }); equal(last, _.last(array), '_.forEach should not exit early: ' + basename); equal(actual, undefined, '_.forEach should return `undefined`: ' + basename); object = { 'length': 0, 'splice': Array.prototype.splice }; equal(lodash.isEmpty(object), false, '_.isEmpty should return `false` for jQuery/MooTools DOM query collections: ' + basename); object = { 'a': 1, 'b': 2, 'c': 3 }; equal(lodash.isEqual(object, { 'a': 1, 'b': 0, 'c': 3 }), false, '_.isEqual: ' + basename); actual = lodash.isEqual('a', 'b', function(a, b) { return this[a] == this[b]; }, { 'a': 1, 'b': 1 }); strictEqual(actual, false, '_.isEqual should ignore `callback` and `thisArg`: ' + basename); equal(lodash.max('abc'), -Infinity, '_.max should return `-Infinity` for strings: ' + basename); equal(lodash.min('abc'), Infinity, '_.min should return `Infinity` for strings: ' + basename); // avoid issues comparing objects with `deepEqual` object = { 'a': 1, 'b': 2, 'c': 3 }; actual = lodash.omit(object, function(value) { return value == 3; }); deepEqual(_.keys(actual).sort(), ['a', 'b', 'c'], '_.omit should not accept a `callback`: ' + basename); actual = lodash.pick(object, function(value) { return value != 3; }); deepEqual(_.keys(actual), [], '_.pick should not accept a `callback`: ' + basename); strictEqual(lodash.result(), null, '_.result should return `null` for falsey `object` arguments: ' + basename); strictEqual(lodash.some([false, true, false]), true, '_.some: ' + basename); equal(lodash.template('${a}', object), '${a}', '_.template should ignore ES6 delimiters: ' + basename); equal('imports' in lodash.templateSettings, false, '_.templateSettings should not have an "imports" property: ' + basename); strictEqual(lodash.uniqueId(0), '1', '_.uniqueId should ignore a prefix of `0`: ' + basename); var collection = [{ 'a': { 'b': 1, 'c': 2 } }]; deepEqual(lodash.where(collection, { 'a': { 'b': 1 } }), [], '_.where performs shallow comparisons: ' + basename); collection = [{ 'a': 1 }, { 'a': 1 }]; deepEqual(lodash.where(collection, { 'a': 1 }, true), collection[0], '_.where supports a `first` argument: ' + basename); deepEqual(lodash.where(collection, {}, true), null, '_.where should return `null` when passed `first` and falsey `properties`: ' + basename); deepEqual(lodash.findWhere(collection, { 'a': 1 }), collection[0], '_.findWhere: ' + basename); strictEqual(lodash.findWhere(collection, {}), null, '_.findWhere should return `null` for falsey `properties`: ' + basename); start(); }); }); asyncTest('should not have any Lo-Dash-only methods', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'underscore'], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); vm.runInContext(data.source, context); var lodash = context._; _.each([ 'assign', 'at', 'bindKey', 'forIn', 'forOwn', 'isPlainObject', 'merge', 'partialRight' ], function(methodName) { equal(lodash[methodName], undefined, '_.' + methodName + ' should not exist: ' + basename); }); start(); }); }); asyncTest('`lodash underscore include=findWhere`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'underscore', 'include=findWhere'], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); vm.runInContext(data.source, context); var lodash = context._; var collection = [{ 'a': 1 }, { 'a': 1 }]; deepEqual(lodash.findWhere(collection, { 'a': 1 }), collection[0], '_.findWhere: ' + basename); start(); }); }); asyncTest('`lodash underscore include=partial`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'underscore', 'include=partial'], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); vm.runInContext(data.source, context); var lodash = context._; equal(lodash.partial(_.identity, 2)(), 2, '_.partial: ' + basename); start(); }); }); asyncTest('`lodash underscore plus=clone`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'underscore', 'plus=clone'], function(data) { var array = [{ 'value': 1 }], basename = path.basename(data.outputPath, '.js'), context = createContext(); vm.runInContext(data.source, context); var lodash = context._, clone = lodash.clone(array, true); ok(_.isEqual(array, clone), basename); notEqual(array[0], clone[0], basename); start(); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('exports command'); (function() { var commands = [ 'exports=amd', 'exports=commonjs', 'exports=global', 'exports=node', 'exports=none' ]; commands.forEach(function(command, index) { asyncTest('`lodash ' + command +'`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', command], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(), pass = false, source = data.source; switch(index) { case 0: context.define = function(fn) { pass = true; context._ = fn(); }; context.define.amd = {}; vm.runInContext(source, context); ok(pass, basename); break; case 1: context.exports = {}; vm.runInContext(source, context); ok(_.isFunction(context.exports._), basename); strictEqual(context._, undefined, basename); break; case 2: vm.runInContext(source, context); ok(_.isFunction(context._), basename); break; case 3: context.exports = {}; context.module = { 'exports': context.exports }; vm.runInContext(source, context); ok(_.isFunction(context.module.exports), basename); strictEqual(context._, undefined, basename); break; case 4: vm.runInContext(source, context); strictEqual(context._, undefined, basename); } start(); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('iife command'); (function() { var commands = [ 'iife=this["lodash"]=(function(window,undefined){%output%;return lodash}(this))', 'iife=define(function(window,undefined){return function(){%output%;return lodash}}(this));' ]; commands.forEach(function(command) { asyncTest('`lodash ' + command +'`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'exports=none', command], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); context.define = function(func) { context.lodash = func(); }; try { vm.runInContext(data.source, context); } catch(e) { console.log(e); } var lodash = context.lodash || {}; ok(_.isString(lodash.VERSION), basename); start(); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('output options'); (function() { var commands = [ '-o a.js', '--output a.js' ]; commands.forEach(function(command, index) { asyncTest('`lodash ' + command +'`', function() { var counter = -1, start = _.after(2, _.once(QUnit.start)); build(['-s'].concat(command.split(' ')), function(data) { equal(path.basename(data.outputPath, '.js'), (++counter ? 'a.min' : 'a'), command); start(); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('stdout options'); (function() { var commands = [ '-c', '-c -d', '--stdout', ]; commands.forEach(function(command, index) { asyncTest('`lodash ' + command +'`', function() { var written, start = _.once(QUnit.start), write = process.stdout.write; process.stdout.write = function(string) { written = string; }; build(['exports=', 'include='].concat(command.split(' ')), function(data) { process.stdout.write = write; equal(written, data.source); equal(arguments.length, 1); start(); }); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('mobile build'); (function() { asyncTest('`lodash mobile`', function() { var start = _.after(2, _.once(QUnit.start)); build(['-s', 'mobile'], function(data) { var basename = path.basename(data.outputPath, '.js'), context = createContext(); try { vm.runInContext(data.source, context); } catch(e) { console.log(e); } var array = [1, 2, 3], object1 = [{ 'a': 1 }], object2 = [{ 'b': 2 }], object3 = [{ 'a': 1, 'b': 2 }], circular1 = { 'a': 1 }, circular2 = { 'a': 1 }, lodash = context._; circular1.b = circular1; circular2.b = circular2; deepEqual(lodash.merge(object1, object2), object3, basename); deepEqual(lodash.sortBy([3, 2, 1], _.identity), array, basename); strictEqual(lodash.isEqual(circular1, circular2), true, basename); var actual = lodash.cloneDeep(circular1); ok(actual != circular1 && actual.b == actual, basename); start(); }); }); asyncTest('`lodash csp`', function() { var sources = []; var check = _.after(2, _.once(function() { equal(sources[0], sources[1]); QUnit.start(); })); var callback = function(data) { // remove copyright header and append source sources.push(data.source.replace(/^\/\**[\s\S]+?\*\/\n/, '')); check(); }; build(['-s', '-d', 'csp'], callback); build(['-s', '-d', 'mobile'], callback); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash build'); (function() { var commands = [ 'backbone', 'csp', 'legacy', 'mobile', 'modern', 'strict', 'underscore', 'category=arrays', 'category=chaining', 'category=collections', 'category=functions', 'category=objects', 'category=utilities', 'exclude=union,uniq,zip', 'include=each,filter,map', 'include=once plus=bind,Chaining', 'category=collections,functions', 'backbone legacy category=utilities minus=first,last', 'underscore include=debounce,throttle plus=after minus=throttle', 'underscore mobile strict category=functions exports=amd,global plus=pick,uniq', ] .concat( allMethods.map(function(methodName) { return 'include=' + methodName; }) ); commands.forEach(function(origCommand) { _.times(4, function(index) { var command = origCommand; if (index == 1) { if (/mobile/.test(command)) { return; } command = 'mobile ' + command; } if (index == 2) { if (/modern/.test(command)) { return; } command = 'modern ' + command; } if (index == 3) { if (/category|underscore/.test(command)) { return; } command = 'underscore ' + command; } asyncTest('`lodash ' + command +'`', function() { var start = _.after(2, _.once(QUnit.start)); build(['--silent'].concat(command.split(' ')), function(data) { var methodNames, basename = path.basename(data.outputPath, '.js'), context = createContext(), isUnderscore = /backbone|underscore/.test(command), exposeAssign = !isUnderscore; try { vm.runInContext(data.source, context); } catch(e) { console.log(e); } // add method names explicitly if (/include/.test(command)) { methodNames = command.match(/include=(\S*)/)[1].split(/, */); } // add method names required by Backbone and Underscore builds if (/backbone/.test(command) && !methodNames) { methodNames = backboneDependencies.slice(); } if (isUnderscore) { if (methodNames) { exposeAssign = methodNames.indexOf('assign') > -1; } else { methodNames = underscoreMethods.slice(); } } // add method names explicitly by category if (/category/.test(command)) { // resolve method names belonging to each category (case-insensitive) methodNames = command.match(/category=(\S*)/)[1].split(/, */).reduce(function(result, category) { var capitalized = category[0].toUpperCase() + category.toLowerCase().slice(1); return result.concat(getMethodsByCategory(capitalized)); }, methodNames || []); } // init `methodNames` if it hasn't been inited if (!methodNames) { methodNames = allMethods.slice(); } if (/plus/.test(command)) { methodNames = methodNames.concat(command.match(/plus=(\S*)/)[1].split(/, */)); } if (/minus/.test(command)) { methodNames = _.without.apply(_, [methodNames] .concat(expandMethodNames(command.match(/minus=(\S*)/)[1].split(/, */)))); } if (/exclude/.test(command)) { methodNames = _.without.apply(_, [methodNames] .concat(expandMethodNames(command.match(/exclude=(\S*)/)[1].split(/, */)))); } // expand aliases and categories to real method names methodNames = expandMethodNames(methodNames).reduce(function(result, methodName) { return result.concat(methodName, getMethodsByCategory(methodName)); }, []); // remove nonexistent and duplicate method names methodNames = _.uniq(_.intersection(allMethods, expandMethodNames(methodNames))); if (!exposeAssign) { methodNames = _.without(methodNames, 'assign'); } var lodash = context._ || {}; methodNames.forEach(function(methodName) { testMethod(lodash, methodName, basename); }); start(); }); }); }); }); }()); /*--------------------------------------------------------------------------*/ if (timeLimit > 0) { setTimeout(function() { process.exit(QUnit.config.stats.bad ? 1 : 0); }, timeLimit); } // explicitly call `QUnit.start()` for Narwhal, Node.js, Rhino, and RingoJS if (!global.document) { QUnit.start(); } }());
sifu/trellonext
node_modules/grunt-bower-hooks/node_modules/lodash/test/test-build.js
JavaScript
mit
39,220
'use strict'; /* global describe, it */ var assert = require('chai').assert; var Tests = require('../tests.js'), tmpTests = require('./tmp-classes.fixture.js').Tests; describe('Initialization', function() { it('Should be possible to initialize Tests', function() { assert.isFunction(Tests, 'Require Tests returns a function'); var tests = new Tests('some_path', 'some_mount'); assert.isObject(tests, 'Call to Tests constructor returns object.'); assert.equal(tests.path, 'some_path', 'Path has been set correctly.'); assert.equal(tests.mount, 'some_mount', 'Mount has been set correctly.'); }); }); describe('Configuring and running tests', function() { var tests = new Tests('fixtures', '/tests'); it('Should be possible to add directory with tests', function() { [ '/tests/somedir1/ok.simpletest.js', '/tests/somedir1/fail.simpletest.js', '/tests/somedir1/error.simpletest.js', '/tests/somedir1/somedir2/ok.simpletest.js' ].forEach(function(url) { assert(tests.index().tests[url], 'The url ' + url + ' must be present in the test list'); }); assert.equal(Object.keys(tests.index().tests).length, 4, 'Just four test scripts'); }); it('Should be possible to run an ok test', function(done) { var ok_test = tests.get('/somedir1/ok.simpletest.js'); assert(ok_test, 'Ok test exists.'); assert.equal(ok_test.name, 'ok.simpletest.js', 'Ok test has right name.'); ok_test.run(function(exitCode, output) { assert.equal(exitCode, 0, 'Ok test exited with exit code 0'); assert.match(output, /writing to stdout/, 'Ok test wrote to stdout'); assert.match(output, /writing to stderr/, 'Ok test wrote to stderr'); done(); }); }); it('Should be possible to run a failing test', function(done) { var ok_test = tests.get('/somedir1/fail.simpletest.js'); assert(ok_test, 'Failing test exists.'); assert.equal(ok_test.name, 'fail.simpletest.js', 'Failing test has right name.'); ok_test.run(function(exitCode, output) { assert.notEqual(exitCode, 0, 'Failing test exited with nonzero exit code'); done(); }); }); it('Should be possible to run a failing test', function(done) { var ok_test = tests.get('/somedir1/error.simpletest.js'); assert(ok_test, 'Failing test exists.'); assert.equal(ok_test.name, 'error.simpletest.js', 'Failing test has right name.'); ok_test.run(function(exitCode, output) { assert.notEqual(exitCode, 0, 'Failing test exited with nonzero exit code'); done(); }); }); it('Runs the install command specified', function(done) { var archive = require('../archive.js'); tmpTests('tests', function(tests) { tests.extract('.', archive.pack('fixtures/somedir1'), function(err, stdout, stderr) { assert.include(stdout, 'install ok', 'Stdout contains ok message'); assert(!stderr, 'Stderr is empty'); assert(!err, 'No error code (or message) provided'); done(); }); }); }); it('Handles errors returned by install command specified', function(done) { var archive = require('../archive.js'); tmpTests('tests', function(tests) { tests.extract('.', archive.pack('fixtures/somedir4'), function(err, stdout, stderr) { assert.include(stdout, 'install not ok', 'Stdout contains error message'); assert(!stderr, 'Stderr is not empty'); assert(err, 'Error code (or message) provided: ' + err); done(); }); }); }); it('Handles errors when trying to remove directories gracefully', function(done) { var sinon = require('sinon'), shell = require('shelljs'), archive = require('../archive.js'), stream = require('stream'), tests = new Tests('fixtures', '/tests'); sinon.stub(shell, 'rm', function() { shell.rm.restore(); sinon.stub(shell, 'error', function() { shell.error.restore(); return 'stub error'; }); }); tests.extract('somewhere', archive.pack('fixtures/somedir1/somedir2'), function(err) { assert(err, 'Reports error when rm fails'); done(); }); }); it('Should be possible to insert new test directories'); });
Notalib/Dori
js/test/tests.spec.js
JavaScript
mit
4,244
/* */ "format register"; "use strict"; var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var ResourceType = require("aurelia-metadata").ResourceType; var BehaviorInstance = require("./behavior-instance").BehaviorInstance; var configureBehavior = require("./behaviors").configureBehavior; var hyphenate = require("./util").hyphenate; var TemplateController = exports.TemplateController = (function (ResourceType) { function TemplateController(attribute) { this.name = attribute; this.properties = []; this.attributes = {}; this.liftsContent = true; } _inherits(TemplateController, ResourceType); _prototypeProperties(TemplateController, { convention: { value: function convention(name) { if (name.endsWith("TemplateController")) { return new TemplateController(hyphenate(name.substring(0, name.length - 18))); } }, writable: true, configurable: true } }, { analyze: { value: function analyze(container, target) { configureBehavior(container, this, target); }, writable: true, configurable: true }, load: { value: function load(container, target) { return Promise.resolve(this); }, writable: true, configurable: true }, register: { value: function register(registry, name) { registry.registerAttribute(name || this.name, this, this.name); }, writable: true, configurable: true }, compile: { value: function compile(compiler, resources, node, instruction, parentNode) { if (!instruction.viewFactory) { var template = document.createElement("template"), fragment = document.createDocumentFragment(); node.removeAttribute(instruction.originalAttrName); if (node.parentNode) { node.parentNode.replaceChild(template, node); } else if (window.ShadowDOMPolyfill) { ShadowDOMPolyfill.unwrap(parentNode).replaceChild(ShadowDOMPolyfill.unwrap(template), ShadowDOMPolyfill.unwrap(node)); } else { parentNode.replaceChild(template, node); } fragment.appendChild(node); instruction.viewFactory = compiler.compile(fragment, resources); node = template; } instruction.suppressBind = true; return node; }, writable: true, configurable: true }, create: { value: function create(container, instruction, element) { var executionContext = instruction.executionContext || container.get(this.target), behaviorInstance = new BehaviorInstance(this, executionContext, instruction); element.primaryBehavior = behaviorInstance; if (!(this.apiName in element)) { element[this.apiName] = behaviorInstance.executionContext; } return behaviorInstance; }, writable: true, configurable: true } }); return TemplateController; })(ResourceType); exports.__esModule = true;
Maidan-hackaton/ua-tenders-aurelia
jspm_packages/github/aurelia/templating@0.8.9/commonjs/template-controller.js
JavaScript
mit
3,654
"use strict"; /* global casper */ module.exports.init = function (steps) { steps .when("I am on product page", function () { casper.open(document.app.parameters.base_url + "search") .thenClick('.product-thumbnail a'); }) .then("I should see basic product info", function () { casper.test.assertExist("img.scaled-image"); casper.test.assertTruthy(casper.fetchText('.product-panel .panel-heading')); casper.test.assertTruthy(casper.fetchText('.price')); casper.test.assertTextExist("Manufacturer"); casper.test.assertTextExist("Grape"); casper.test.assertTextExist("Alcohol level"); casper.test.assertTextExist("Wine colour"); }) ; return steps; }
GrandLTU/ongr-sandbox
src/ONGR/DemoBundle/Tests/Acceptance/Steps/Library/Product/product.js
JavaScript
mit
805
'use strict'; // Configuring the Articles module angular.module('diapers').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Diapers', 'diapers', 'dropdown', '/diapers(/create)?'); Menus.addSubMenuItem('topbar', 'diapers', 'List Diapers', 'diapers'); Menus.addSubMenuItem('topbar', 'diapers', 'New Diaper', 'diapers/create'); } ]);
dproebsting/GroupEight
public/modules/diapers/config/diapers.client.config.js
JavaScript
mit
379
'use strict'; module.exports = function(grunt) { var fs = require('fs'), swig = require('swig'), path = require('path'); grunt.registerMultiTask('swig', 'swig templater', function(tpl_context) { var config = this, context = tpl_context || '', pages = [], date = new Date(), d = date.toISOString(), defaultPriority = (config.data.sitemap_priorities !== undefined)? config.data.sitemap_priorities._DEFAULT_ : '0.5', generateSitemap = config.data.generateSitemap != undefined ? config.data.generateSitemap : true, generateRobotstxt = config.data.generateRobotstxt != undefined ? config.data.generateSitemap : true, globalVars = {}; if (config.data.init !== undefined) { swig.setDefaults(config.data.init); } try { globalVars = grunt.util._.extend(config.data, grunt.file.readJSON(process.cwd() + '/global.json')); } catch (err) { globalVars = grunt.util._.clone(config.data); } this.filesSrc.forEach(function(file) { if (!grunt.file.exists(file)) { grunt.log.warn('Source file "' + file.src + '" not found.'); return false; } else { var dirName = path.dirname(file).split('/'), destPath = dirName.splice(1, dirName.length).join('/'), outputFile = path.basename(file, '.swig'), htmlFile = config.data.dest + '/' + destPath + '/' + outputFile + '.html', tplVars = {}, contextVars = {}; try { tplVars = grunt.file.readJSON(path.dirname(file) + '/' + outputFile + ".json"); } catch(err) { tplVars = {}; } try { contextVars = grunt.file.readJSON(path.dirname(file) + '/' + outputFile + "." + context + ".json"); } catch(err) { contextVars = {}; } tplVars.context = context; tplVars.tplFile = { path: destPath, basename: outputFile }; grunt.log.writeln('Writing HTML to ' + htmlFile); grunt.file.write(htmlFile, swig.renderFile(file, grunt.util._.extend(globalVars, tplVars, contextVars))); if (config.data.sitemap_priorities !== undefined && config.data.sitemap_priorities[destPath + '/' + outputFile + '.html'] !== undefined) { pages.push({ url: config.data.siteUrl + htmlFile.replace(config.data.dest + '/', ''), date: d, changefreq: 'weekly', priority: config.data.sitemap_priorities[destPath + '/' + outputFile + '.html'] }); } else { pages.push({ url: config.data.siteUrl + htmlFile.replace(config.data.dest + '/', ''), date: d, changefreq: 'weekly', priority: defaultPriority }); } } }); if (generateSitemap) { grunt.log.writeln('Creating sitemap.xml'); grunt.file.write(config.data.dest + '/sitemap.xml', swig.renderFile(__dirname + '/../templates/sitemap.xml.swig', { pages: pages})); } if (generateRobotstxt) { grunt.log.writeln('Creating robots.txt'); grunt.file.write(config.data.dest + '/robots.txt', swig.renderFile(__dirname + '/../templates/robots.txt.swig', { robots_directive: config.data.robots_directive || '' })); } }); };
uhtred/grunt-swig
tasks/swig.js
JavaScript
mit
3,332
var bigInt = require('big-integer'); var ecdsa = require('ecdsa'); var config = require('./config.js'); var crypto = require('./crypto.js'); function StackEmptyException() { this.toString = () => { return 'Attempted to pop from an empty stack.'; }; } var serialize = (data) => { return data.toString(config.base); }; var deserialize = (data) => { return bigInt(data, config.base); }; class ScriptStack { constructor() { } // Basic array operations push() { var serialized = [].map.call(arguments, serialize); return Array.prototype.push.apply(this, serialized); } pop() { if (this.length === 0 || this.length == null) { throw new StackEmptyException(); } return deserialize(Array.prototype.pop.apply(this)); } peek() { var value = this.pop(); this.push(value); return value; } // Constants OP_0() { this.push(0); } OP_FALSE() { this.OP_0(); } OP_1NEGATE() { this.OP_1(); this.OP_NEGATE(); } OP_1() { this.push(1); } OP_TRUE() { this.OP_1(); } // Stack operations OP_IFDUP() { var top = this.peek(); if (top.compare(0) !== 0) { this.push(top); } } OP_DEPTH() { this.push(this.length); } OP_DROP() { this.pop(); } OP_2DROP() { this.OP_DROP(); this.OP_DROP(); } OP_DUP(n) { n = n || 1; // Extract top `n` values var values = []; for (var i = 0; i < n; i++) { values.push(this.pop()); } values.reverse(); for (var i = 0; i < 2 * n; i++) { this.push(values[i % values.length]); } } OP_2DUP() { this.OP_DUP(2); } OP_3DUP() { this.OP_DUP(3); } OP_NIP() { var top = this.pop(); this.pop(); this.push(top); } OP_OVER() { var top = this.pop(); var bottom = this.peek(); this.push(top); this.push(bottom); } OP_PICK() { var n = this.pop(); var temp = []; for (var i = 0; i < n - 1; i++) { temp.push(this.pop()); } var nth = this.peek(); for (var i = 0; i < n - 1; i++) { this.push(temp[i]); } this.push(nth); } OP_ROLL() { var n = this.pop(); var temp = []; for (var i = 0; i < n - 1; i++) { temp.push(this.pop()); } var nth = this.pop(); for (var i = 0; i < n - 1; i++) { this.push(temp[i]); } this.push(nth); } OP_ROT() { var values = [this.pop(), this.pop(), this.pop()]; values.reverse(); for (var i = 0; i < values.length; i++) { this.push(values[(i + 1) % values.length]); } } OP_SWAP() { var values = [this.pop(), this.pop()]; for (var i = 0; i < values.length; i++) { this.push(values[i]); } } OP_TUCK() { var values = [this.pop(), this.pop()]; values.reverse(); for (var i = 0; i < values.length + 1; i++) { this.push(values[i % values.length]); } } OP_2OVER() { var values = [this.pop(), this.pop(), this.pop(), this.pop()]; values.reverse(); for (var i = 0; i < values.length + 2; i++) { this.push(values[i % values.length]); } } OP_2ROT() { var values = [this.pop(), this.pop(), this.pop(), this.pop(), this.pop(), this.pop()]; values.reverse(); for (var i = 0; i < values.length; i++) { this.push(values[(i + 2) % values.length]); } } OP_2SWAP() { var values = [this.pop(), this.pop(), this.pop(), this.pop()]; values.reverse(); for (var i = 0; i < values.length; i++) { this.push(values[(i + 2) % values.length]); } } // Bitwise logic OP_INVERT() { this.push(this.pop().not()); } OP_AND() { this.push(this.pop().and(this.pop())); } OP_OR() { this.push(this.pop().or(this.pop())); } OP_XOR() { this.push(this.pop().xor(this.pop())); } OP_EQUAL() { var b = this.pop(); var a = this.pop(); if (a.equals(b)) { this.OP_1(); } else { this.OP_0(); } } // Artithmetic operations OP_1ADD() { this.push(this.pop().add(1)); } OP_1SUB() { this.push(this.pop().minus(1)); } OP_2MUL() { this.push(this.pop().multiply(2)); } OP_2DIV() { this.push(this.pop().divide(2)); } OP_NEGATE() { this.push(this.pop().multiply(-1)); } OP_ABS() { this.push(this.pop().abs()); } OP_NOT() { if (this.pop().equals(0)) { this.OP_1(); } else { this.OP_0(); } } OP_0NOTEQUAL() { if (this.pop().equals(0)) { this.OP_0(); } else { this.OP_1(); } } OP_ADD() { var b = this.pop(); var a = this.pop(); this.push(a.add(b)); } OP_SUB() { var b = this.pop(); var a = this.pop(); this.push(a.minus(b)); } OP_MUL() { this.push(this.pop().multiply(this.pop())); } OP_DIV() { var divisor = this.pop(); var dividend = this.pop(); this.push(dividend.divide(divisor)); } OP_MOD() { var divisor = this.pop(); var dividend = this.pop(); this.push(dividend.mod(divisor)); } OP_LSHIFT() { var numBits = this.pop(); var value = this.pop(); this.push(value.shiftLeft(numBits)); } OP_RSHIFT() { var numBits = this.pop(); var value = this.pop(); this.push(value.shiftRight(numBits)); } OP_BOOLAND() { var b = this.pop(); var a = this.pop(); if (a.compare(0) !== 0 && b.compare(0) !== 0) { this.OP_1(); } else { this.OP_0(); } } OP_BOOLOR() { var b = this.pop(); var a = this.pop(); if (a.compare(0) !== 0 || b.compare(0) !== 0) { this.OP_1(); } else { this.OP_0(); } } OP_NUMEQUAL() { this.OP_EQUAL(); } OP_NUMNOTEQUAL() { var b = this.pop(); var a = this.pop(); if (a.compare(b) !== 0) { this.OP_1(); } else { this.OP_0(); } } OP_LESSTHAN() { var b = this.pop(); var a = this.pop(); if (a.compare(b) < 0) { this.OP_1(); } else { this.OP_0(); } } OP_GREATERTHAN() { var b = this.pop(); var a = this.pop(); if (a.compare(b) > 0) { this.OP_1(); } else { this.OP_0(); } } OP_LESSTHANOREQUAL() { var b = this.pop(); var a = this.pop(); if (a.compare(b) <= 0) { this.OP_1(); } else { this.OP_0(); } } OP_GREATERTHANOREQUAL() { var b = this.pop(); var a = this.pop(); if (a.compare(b) >= 0) { this.OP_1(); } else { this.OP_0(); } } OP_MIN() { var b = this.pop(); var a = this.pop(); if (a.compare(b) <= 0) { this.push(a); } else { this.push(b); } } OP_MAX() { var b = this.pop(); var a = this.pop(); if (a.compare(b) >= 0) { this.push(a); } else { this.push(b); } } OP_WITHIN() { var max = this.pop(); var min = this.pop(); var x = this.pop(); if (x.compare(min) >= 0 && x.compare(max) < 0) { this.OP_1(); } else { this.OP_0(); } } // Crypto OP_RIPEMD160() { this.push(crypto.ripemd160(this.pop())); } OP_SHA1() { this.push(crypto.sha1(this.pop())); } OP_SHA256() { this.push(crypto.sha256(this.pop())); } OP_HASH160() { this.push(crypto.ripemd160(crypto.sha256(this.pop()))); } OP_HASH256() { this.push(crypto.sha256(crypto.sha256(this.pop()))); } OP_CHECKSIG() { // Parse public key var pubKey = crypto.processPubKey(this.pop()); // Parse signature var signature = crypto.processSignature(this.pop()); // Verify signature if (crypto.verifySignature(signature, pubKey)) { this.OP_1(); } else { this.OP_0(); } } OP_CHECKMULTISIG() { // Extract public keys var numPubKeys = this.pop(); var pubKeys = []; var i = 0; while (numPubKeys.compare(i) === 1) { pubKeys.push(crypto.processPubKey(this.pop())); i++; } // Extract signatures var numSignatures = this.pop(); var signatures = [] i = 0; while (numSignatures.compare(i) === 1) { signatures.push(crypto.processSignature(this.pop())); i++; } // Match keys against signatures. Note that any public key that // fails a comparison is then removed, in accordance with the spec. for (i = 0; i < signatures.length; i++) { var matched = -1; for (var j = 0; j < pubKeys.length; j++) { if (crypto.verifySignature(signatures[i], pubKeys[j])) { matched = j; break; } } if (matched === -1) { this.OP_0(); return; } else { // Remove used public keys pubKeys = pubKeys.splice(matched + 1); } var remainingSignatures = signatures.length - (i + 1); if (pubKeys.length < remainingSignatures) { this.OP_0(); return; } } // If all checks passed, push `true` this.OP_1(); } // Terminals OP_VERIFY() { return (this.pop().compare(0) !== 0); } OP_EQUALVERIFY() { this.OP_EQUAL(); return this.OP_VERIFY(); } OP_CHECKSIGVERIFY() { this.OP_CHECKSIG(); return this.OP_VERIFY(); } OP_CHECKMULTISIGVERIFY() { this.OP_CHECKMULTISIG(); return this.OP_VERIFY(); } OP_RETURN() { return false; } }; module.exports = ScriptStack;
kustomzone/blockScript
src/script-stack.js
JavaScript
mit
10,797
/** * A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays. * Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly * @param instance * @constructor */ function WalkontableDebugOverlay(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('debug'); this.clone.wtTable.holder.style.opacity = 0.4; this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000'; var that = this; var lastTimeout; var lastX = 0; var lastY = 0; var overlayContainer = that.clone.wtTable.holder.parentNode; $(document.body).on('mousemove.' + this.instance.guid, function (event) { if (!that.instance.wtTable.holder.parentNode) { return; //removed from DOM } if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) { return; //ignore minor mouse movement } lastX = event.clientX; lastY = event.clientY; WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugVisible'); clearTimeout(lastTimeout); lastTimeout = setTimeout(function () { WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugVisible'); }, 1000); }); } WalkontableDebugOverlay.prototype = new WalkontableOverlay(); WalkontableDebugOverlay.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box = this.instance.wtTable.holder.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; }; WalkontableDebugOverlay.prototype.prepare = function () { }; WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) { this.clone && this.clone.draw(selectionsOnly); }; WalkontableDebugOverlay.prototype.getScrollPosition = function () { }; WalkontableDebugOverlay.prototype.getLastCell = function () { }; WalkontableDebugOverlay.prototype.applyToDOM = function () { }; WalkontableDebugOverlay.prototype.scrollTo = function () { }; WalkontableDebugOverlay.prototype.readWindowSize = function () { }; WalkontableDebugOverlay.prototype.readSettings = function () { };
digitaltech/handsontable
src/3rdparty/walkontable/src/debugOverlay.js
JavaScript
mit
2,521
/* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com> * Copyright (C) 2009 Joseph Pecoraro * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @extends {TreeElement} * @param {!WebInspector.DOMNode} node * @param {boolean=} elementCloseTag */ WebInspector.ElementsTreeElement = function(node, elementCloseTag) { // The title will be updated in onattach. TreeElement.call(this, "", elementCloseTag ? null : node); this._node = node; this._elementCloseTag = elementCloseTag; if (this._node.nodeType() == Node.ELEMENT_NODE && !elementCloseTag) this._canAddAttributes = true; this._searchQuery = null; this._expandedChildrenLimit = WebInspector.ElementsTreeElement.InitialChildrenLimit; } WebInspector.ElementsTreeElement.InitialChildrenLimit = 500; // A union of HTML4 and HTML5-Draft elements that explicitly // or implicitly (for HTML5) forbid the closing tag. WebInspector.ElementsTreeElement.ForbiddenClosingTagElements = [ "area", "base", "basefont", "br", "canvas", "col", "command", "embed", "frame", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr" ].keySet(); // These tags we do not allow editing their tag name. WebInspector.ElementsTreeElement.EditTagBlacklist = [ "html", "head", "body" ].keySet(); /** @enum {number} */ WebInspector.ElementsTreeElement.ChildrenDisplayMode = { NoChildren: 0, InlineText: 1, HasChildren: 2 } /** * @param {!WebInspector.ElementsTreeElement} treeElement */ WebInspector.ElementsTreeElement.animateOnDOMUpdate = function(treeElement) { var tagName = treeElement.listItemElement.querySelector(".webkit-html-tag-name"); WebInspector.runCSSAnimationOnce(tagName || treeElement.listItemElement, "dom-update-highlight"); } WebInspector.ElementsTreeElement.prototype = { /** * @return {boolean} */ isClosingTag: function() { return !!this._elementCloseTag; }, /** * @return {!WebInspector.DOMNode} */ node: function() { return this._node; }, /** * @return {boolean} */ isEditing: function() { return !!this._editing; }, /** * @param {string} searchQuery */ highlightSearchResults: function(searchQuery) { if (this._searchQuery !== searchQuery) this._hideSearchHighlight(); this._searchQuery = searchQuery; this._searchHighlightsVisible = true; this.updateTitle(true); }, hideSearchHighlights: function() { delete this._searchHighlightsVisible; this._hideSearchHighlight(); }, _hideSearchHighlight: function() { if (!this._highlightResult) return; function updateEntryHide(entry) { switch (entry.type) { case "added": entry.node.remove(); break; case "changed": entry.node.textContent = entry.oldText; break; } } for (var i = (this._highlightResult.length - 1); i >= 0; --i) updateEntryHide(this._highlightResult[i]); delete this._highlightResult; }, /** * @param {boolean} inClipboard */ setInClipboard: function(inClipboard) { if (this._inClipboard === inClipboard) return; this._inClipboard = inClipboard; this.listItemElement.classList.toggle("in-clipboard", inClipboard); }, get hovered() { return this._hovered; }, set hovered(x) { if (this._hovered === x) return; this._hovered = x; if (this.listItemElement) { if (x) { this.updateSelection(); this.listItemElement.classList.add("hovered"); } else { this.listItemElement.classList.remove("hovered"); } } }, /** * @return {number} */ expandedChildrenLimit: function() { return this._expandedChildrenLimit; }, /** * @param {number} expandedChildrenLimit */ setExpandedChildrenLimit: function(expandedChildrenLimit) { this._expandedChildrenLimit = expandedChildrenLimit; }, /** * @return {!WebInspector.ElementsTreeElement.ChildrenDisplayMode} */ childrenDisplayMode: function() { return this._childrenDisplayMode; }, /** * @param {!WebInspector.ElementsTreeElement.ChildrenDisplayMode} displayMode */ setChildrenDisplayMode: function(displayMode) { this._childrenDisplayMode = displayMode; }, updateSelection: function() { var listItemElement = this.listItemElement; if (!listItemElement) return; if (!this._readyToUpdateSelection) { if (listItemElement.ownerDocument.body.offsetWidth > 0) this._readyToUpdateSelection = true; else { // The stylesheet hasn't loaded yet or the window is closed, // so we can't calculate what we need. Return early. return; } } if (!this.selectionElement) { this.selectionElement = createElement("div"); this.selectionElement.className = "selection selected"; listItemElement.insertBefore(this.selectionElement, listItemElement.firstChild); } this.selectionElement.style.height = listItemElement.offsetHeight + "px"; }, onattach: function() { if (this._hovered) { this.updateSelection(); this.listItemElement.classList.add("hovered"); } this.updateTitle(); this._preventFollowingLinksOnDoubleClick(); this.listItemElement.draggable = true; }, _preventFollowingLinksOnDoubleClick: function() { var links = this.listItemElement.querySelectorAll("li .webkit-html-tag > .webkit-html-attribute > .webkit-html-external-link, li .webkit-html-tag > .webkit-html-attribute > .webkit-html-resource-link"); if (!links) return; for (var i = 0; i < links.length; ++i) links[i].preventFollowOnDoubleClick = true; }, onpopulate: function() { this.populated = true; this.treeOutline.populateTreeElement(this); }, /** * @param {?WebInspector.ElementsTreeOutline.UpdateInfo} updateInfo */ setUpdateInfo: function(updateInfo) { this._updateInfo = updateInfo; }, expandRecursively: function() { /** * @this {WebInspector.ElementsTreeElement} */ function callback() { TreeElement.prototype.expandRecursively.call(this, Number.MAX_VALUE); } this._node.getSubtree(-1, callback.bind(this)); }, /** * @override */ onexpand: function() { if (this._elementCloseTag) return; this.updateTitle(); this.treeOutline.updateSelection(); }, oncollapse: function() { if (this._elementCloseTag) return; this.updateTitle(); this.treeOutline.updateSelection(); }, /** * @override */ onreveal: function() { if (this.listItemElement) { var tagSpans = this.listItemElement.getElementsByClassName("webkit-html-tag-name"); if (tagSpans.length) tagSpans[0].scrollIntoViewIfNeeded(true); else this.listItemElement.scrollIntoViewIfNeeded(true); } }, /** * @override * @param {boolean=} omitFocus * @param {boolean=} selectedByUser * @return {boolean} */ select: function(omitFocus, selectedByUser) { if (this._editing) return false; if (this.treeOutline.handlePickNode(this.title, this._node)) return true; return TreeElement.prototype.select.call(this, omitFocus, selectedByUser); }, /** * @override * @param {boolean=} selectedByUser * @return {boolean} */ onselect: function(selectedByUser) { this.treeOutline.suppressRevealAndSelect = true; this.treeOutline.selectDOMNode(this._node, selectedByUser); if (selectedByUser) this._node.highlight(); this.updateSelection(); this.treeOutline.suppressRevealAndSelect = false; return true; }, /** * @override * @return {boolean} */ ondelete: function() { var startTagTreeElement = this.treeOutline.findTreeElement(this._node); startTagTreeElement ? startTagTreeElement.remove() : this.remove(); return true; }, /** * @override * @return {boolean} */ onenter: function() { // On Enter or Return start editing the first attribute // or create a new attribute on the selected element. if (this._editing) return false; this._startEditing(); // prevent a newline from being immediately inserted return true; }, selectOnMouseDown: function(event) { TreeElement.prototype.selectOnMouseDown.call(this, event); if (this._editing) return; // Prevent selecting the nearest word on double click. if (event.detail >= 2) event.preventDefault(); }, /** * @override * @return {boolean} */ ondblclick: function(event) { if (this._editing || this._elementCloseTag) return false; if (this._startEditingTarget(/** @type {!Element} */(event.target))) return false; if (this.hasChildren && !this.expanded) this.expand(); return false; }, /** * @return {boolean} */ hasEditableNode: function() { return !this._node.isShadowRoot() && !this._node.ancestorUserAgentShadowRoot(); }, _insertInLastAttributePosition: function(tag, node) { if (tag.getElementsByClassName("webkit-html-attribute").length > 0) tag.insertBefore(node, tag.lastChild); else { var nodeName = tag.textContent.match(/^<(.*?)>$/)[1]; tag.textContent = ''; tag.createTextChild('<' + nodeName); tag.appendChild(node); tag.createTextChild('>'); } this.updateSelection(); }, /** * @param {!Element} eventTarget * @return {boolean} */ _startEditingTarget: function(eventTarget) { if (this.treeOutline.selectedDOMNode() != this._node) return false; if (this._node.nodeType() != Node.ELEMENT_NODE && this._node.nodeType() != Node.TEXT_NODE) return false; if (this.treeOutline.pickNodeMode()) return false; var textNode = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (textNode) return this._startEditingTextNode(textNode); var attribute = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-attribute"); if (attribute) return this._startEditingAttribute(attribute, eventTarget); var tagName = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-tag-name"); if (tagName) return this._startEditingTagName(tagName); var newAttribute = eventTarget.enclosingNodeOrSelfWithClass("add-attribute"); if (newAttribute) return this._addNewAttribute(); return false; }, /** * @param {!WebInspector.ContextMenu} contextMenu * @param {!Event} event */ populateTagContextMenu: function(contextMenu, event) { // Add attribute-related actions. var treeElement = this._elementCloseTag ? this.treeOutline.findTreeElement(this._node) : this; contextMenu.appendItem(WebInspector.UIString.capitalize("Add ^attribute"), treeElement._addNewAttribute.bind(treeElement)); var attribute = event.target.enclosingNodeOrSelfWithClass("webkit-html-attribute"); var newAttribute = event.target.enclosingNodeOrSelfWithClass("add-attribute"); if (attribute && !newAttribute) contextMenu.appendItem(WebInspector.UIString.capitalize("Edit ^attribute"), this._startEditingAttribute.bind(this, attribute, event.target)); contextMenu.appendSeparator(); if (this.treeOutline.setPseudoClassCallback) { var pseudoSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString.capitalize("Force ^element ^state")); this._populateForcedPseudoStateItems(pseudoSubMenu); contextMenu.appendSeparator(); } this.populateNodeContextMenu(contextMenu); this.populateScrollIntoView(contextMenu); }, /** * @param {!WebInspector.ContextMenu} contextMenu */ populateScrollIntoView: function(contextMenu) { contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString.capitalize("Scroll into ^view"), this._scrollIntoView.bind(this)); }, _populateForcedPseudoStateItems: function(subMenu) { const pseudoClasses = ["active", "hover", "focus", "visited"]; var node = this._node; var forcedPseudoState = (node ? node.getUserProperty("pseudoState") : null) || []; for (var i = 0; i < pseudoClasses.length; ++i) { var pseudoClassForced = forcedPseudoState.indexOf(pseudoClasses[i]) >= 0; var setPseudoClassCallback = this.treeOutline.setPseudoClassCallback.bind(this.treeOutline, node, pseudoClasses[i], !pseudoClassForced); subMenu.appendCheckboxItem(":" + pseudoClasses[i], setPseudoClassCallback, pseudoClassForced, false); } }, populateTextContextMenu: function(contextMenu, textNode) { if (!this._editing) contextMenu.appendItem(WebInspector.UIString.capitalize("Edit ^text"), this._startEditingTextNode.bind(this, textNode)); this.populateNodeContextMenu(contextMenu); }, populateNodeContextMenu: function(contextMenu) { // Add free-form node-related actions. var openTagElement = this.treeOutline.getCachedTreeElement(this._node) || this; var isEditable = this.hasEditableNode(); if (isEditable && !this._editing) contextMenu.appendItem(WebInspector.UIString("Edit as HTML"), openTagElement.toggleEditAsHTML.bind(openTagElement)); var isShadowRoot = this._node.isShadowRoot(); // Place it here so that all "Copy"-ing items stick together. if (this._node.nodeType() === Node.ELEMENT_NODE) contextMenu.appendItem(WebInspector.UIString.capitalize("Copy CSS ^path"), this._copyCSSPath.bind(this)); if (!isShadowRoot) contextMenu.appendItem(WebInspector.UIString("Copy XPath"), this._copyXPath.bind(this)); if (!isShadowRoot) { var treeOutline = this.treeOutline; contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString("Cut"), treeOutline.performCopyOrCut.bind(treeOutline, true, this._node), !this.hasEditableNode()); contextMenu.appendItem(WebInspector.UIString("Copy"), treeOutline.performCopyOrCut.bind(treeOutline, false, this._node)); contextMenu.appendItem(WebInspector.UIString("Paste"), treeOutline.pasteNode.bind(treeOutline, this._node), !treeOutline.canPaste(this._node)); } if (isEditable) contextMenu.appendItem(WebInspector.UIString("Delete"), this.remove.bind(this)); contextMenu.appendSeparator(); }, _startEditing: function() { if (this.treeOutline.selectedDOMNode() !== this._node) return; var listItem = this._listItemNode; if (this._canAddAttributes) { var attribute = listItem.getElementsByClassName("webkit-html-attribute")[0]; if (attribute) return this._startEditingAttribute(attribute, attribute.getElementsByClassName("webkit-html-attribute-value")[0]); return this._addNewAttribute(); } if (this._node.nodeType() === Node.TEXT_NODE) { var textNode = listItem.getElementsByClassName("webkit-html-text-node")[0]; if (textNode) return this._startEditingTextNode(textNode); return; } }, _addNewAttribute: function() { // Cannot just convert the textual html into an element without // a parent node. Use a temporary span container for the HTML. var container = createElement("span"); this._buildAttributeDOM(container, " ", ""); var attr = container.firstElementChild; attr.style.marginLeft = "2px"; // overrides the .editing margin rule attr.style.marginRight = "2px"; // overrides the .editing margin rule var tag = this.listItemElement.getElementsByClassName("webkit-html-tag")[0]; this._insertInLastAttributePosition(tag, attr); attr.scrollIntoViewIfNeeded(true); return this._startEditingAttribute(attr, attr); }, _triggerEditAttribute: function(attributeName) { var attributeElements = this.listItemElement.getElementsByClassName("webkit-html-attribute-name"); for (var i = 0, len = attributeElements.length; i < len; ++i) { if (attributeElements[i].textContent === attributeName) { for (var elem = attributeElements[i].nextSibling; elem; elem = elem.nextSibling) { if (elem.nodeType !== Node.ELEMENT_NODE) continue; if (elem.classList.contains("webkit-html-attribute-value")) return this._startEditingAttribute(elem.parentNode, elem); } } } }, _startEditingAttribute: function(attribute, elementForSelection) { console.assert(this.listItemElement.isAncestor(attribute)); if (WebInspector.isBeingEdited(attribute)) return true; var attributeNameElement = attribute.getElementsByClassName("webkit-html-attribute-name")[0]; if (!attributeNameElement) return false; var attributeName = attributeNameElement.textContent; var attributeValueElement = attribute.getElementsByClassName("webkit-html-attribute-value")[0]; // Make sure elementForSelection is not a child of attributeValueElement. elementForSelection = attributeValueElement.isAncestor(elementForSelection) ? attributeValueElement : elementForSelection; function removeZeroWidthSpaceRecursive(node) { if (node.nodeType === Node.TEXT_NODE) { node.nodeValue = node.nodeValue.replace(/\u200B/g, ""); return; } if (node.nodeType !== Node.ELEMENT_NODE) return; for (var child = node.firstChild; child; child = child.nextSibling) removeZeroWidthSpaceRecursive(child); } var attributeValue = attributeName && attributeValueElement ? this._node.getAttribute(attributeName) : undefined; if (attributeValue !== undefined) attributeValueElement.textContent = attributeValue; // Remove zero-width spaces that were added by nodeTitleInfo. removeZeroWidthSpaceRecursive(attribute); var config = new WebInspector.InplaceEditor.Config(this._attributeEditingCommitted.bind(this), this._editingCancelled.bind(this), attributeName); function handleKeyDownEvents(event) { var isMetaOrCtrl = WebInspector.isMac() ? event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey : event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey; if (isEnterKey(event) && (event.isMetaOrCtrlForTest || !config.multiline || isMetaOrCtrl)) return "commit"; else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B") return "cancel"; else if (event.keyIdentifier === "U+0009") // Tab key return "move-" + (event.shiftKey ? "backward" : "forward"); else { WebInspector.handleElementValueModifications(event, attribute); return ""; } } config.customFinishHandler = handleKeyDownEvents; this._editing = WebInspector.InplaceEditor.startEditing(attribute, config); this.listItemElement.getComponentSelection().setBaseAndExtent(elementForSelection, 0, elementForSelection, 1); return true; }, /** * @param {!Element} textNodeElement */ _startEditingTextNode: function(textNodeElement) { if (WebInspector.isBeingEdited(textNodeElement)) return true; var textNode = this._node; // We only show text nodes inline in elements if the element only // has a single child, and that child is a text node. if (textNode.nodeType() === Node.ELEMENT_NODE && textNode.firstChild) textNode = textNode.firstChild; var container = textNodeElement.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (container) container.textContent = textNode.nodeValue(); // Strip the CSS or JS highlighting if present. var config = new WebInspector.InplaceEditor.Config(this._textNodeEditingCommitted.bind(this, textNode), this._editingCancelled.bind(this)); this._editing = WebInspector.InplaceEditor.startEditing(textNodeElement, config); this.listItemElement.getComponentSelection().setBaseAndExtent(textNodeElement, 0, textNodeElement, 1); return true; }, /** * @param {!Element=} tagNameElement */ _startEditingTagName: function(tagNameElement) { if (!tagNameElement) { tagNameElement = this.listItemElement.getElementsByClassName("webkit-html-tag-name")[0]; if (!tagNameElement) return false; } var tagName = tagNameElement.textContent; if (WebInspector.ElementsTreeElement.EditTagBlacklist[tagName.toLowerCase()]) return false; if (WebInspector.isBeingEdited(tagNameElement)) return true; var closingTagElement = this._distinctClosingTagElement(); /** * @param {!Event} event */ function keyupListener(event) { if (closingTagElement) closingTagElement.textContent = "</" + tagNameElement.textContent + ">"; } /** * @param {!Element} element * @param {string} newTagName * @this {WebInspector.ElementsTreeElement} */ function editingComitted(element, newTagName) { tagNameElement.removeEventListener('keyup', keyupListener, false); this._tagNameEditingCommitted.apply(this, arguments); } /** * @this {WebInspector.ElementsTreeElement} */ function editingCancelled() { tagNameElement.removeEventListener('keyup', keyupListener, false); this._editingCancelled.apply(this, arguments); } tagNameElement.addEventListener('keyup', keyupListener, false); var config = new WebInspector.InplaceEditor.Config(editingComitted.bind(this), editingCancelled.bind(this), tagName); this._editing = WebInspector.InplaceEditor.startEditing(tagNameElement, config); this.listItemElement.getComponentSelection().setBaseAndExtent(tagNameElement, 0, tagNameElement, 1); return true; }, /** * @param {function(string, string)} commitCallback * @param {?Protocol.Error} error * @param {string} initialValue */ _startEditingAsHTML: function(commitCallback, error, initialValue) { if (error) return; if (this._editing) return; function consume(event) { if (event.eventPhase === Event.AT_TARGET) event.consume(true); } initialValue = this._convertWhitespaceToEntities(initialValue).text; this._htmlEditElement = createElement("div"); this._htmlEditElement.className = "source-code elements-tree-editor"; // Hide header items. var child = this.listItemElement.firstChild; while (child) { child.style.display = "none"; child = child.nextSibling; } // Hide children item. if (this._childrenListNode) this._childrenListNode.style.display = "none"; // Append editor. this.listItemElement.appendChild(this._htmlEditElement); this.treeOutline.childrenListElement.parentElement.addEventListener("mousedown", consume, false); this.updateSelection(); /** * @param {!Element} element * @param {string} newValue * @this {WebInspector.ElementsTreeElement} */ function commit(element, newValue) { commitCallback(initialValue, newValue); dispose.call(this); } /** * @this {WebInspector.ElementsTreeElement} */ function dispose() { delete this._editing; this.treeOutline.setMultilineEditing(null); // Remove editor. this.listItemElement.removeChild(this._htmlEditElement); delete this._htmlEditElement; // Unhide children item. if (this._childrenListNode) this._childrenListNode.style.removeProperty("display"); // Unhide header items. var child = this.listItemElement.firstChild; while (child) { child.style.removeProperty("display"); child = child.nextSibling; } this.treeOutline.childrenListElement.parentElement.removeEventListener("mousedown", consume, false); this.updateSelection(); this.treeOutline.focus(); } var config = new WebInspector.InplaceEditor.Config(commit.bind(this), dispose.bind(this)); config.setMultilineOptions(initialValue, { name: "xml", htmlMode: true }, "web-inspector-html", WebInspector.settings.domWordWrap.get(), true); WebInspector.InplaceEditor.startMultilineEditing(this._htmlEditElement, config).then(markAsBeingEdited.bind(this)); /** * @param {!Object} controller * @this {WebInspector.ElementsTreeElement} */ function markAsBeingEdited(controller) { this._editing = /** @type {!WebInspector.InplaceEditor.Controller} */ (controller); this._editing.setWidth(this.treeOutline.visibleWidth()); this.treeOutline.setMultilineEditing(this._editing); } }, _attributeEditingCommitted: function(element, newText, oldText, attributeName, moveDirection) { delete this._editing; var treeOutline = this.treeOutline; /** * @param {?Protocol.Error=} error * @this {WebInspector.ElementsTreeElement} */ function moveToNextAttributeIfNeeded(error) { if (error) this._editingCancelled(element, attributeName); if (!moveDirection) return; treeOutline.runPendingUpdates(); // Search for the attribute's position, and then decide where to move to. var attributes = this._node.attributes(); for (var i = 0; i < attributes.length; ++i) { if (attributes[i].name !== attributeName) continue; if (moveDirection === "backward") { if (i === 0) this._startEditingTagName(); else this._triggerEditAttribute(attributes[i - 1].name); } else { if (i === attributes.length - 1) this._addNewAttribute(); else this._triggerEditAttribute(attributes[i + 1].name); } return; } // Moving From the "New Attribute" position. if (moveDirection === "backward") { if (newText === " ") { // Moving from "New Attribute" that was not edited if (attributes.length > 0) this._triggerEditAttribute(attributes[attributes.length - 1].name); } else { // Moving from "New Attribute" that holds new value if (attributes.length > 1) this._triggerEditAttribute(attributes[attributes.length - 2].name); } } else if (moveDirection === "forward") { if (!/^\s*$/.test(newText)) this._addNewAttribute(); else this._startEditingTagName(); } } if ((attributeName.trim() || newText.trim()) && oldText !== newText) { this._node.setAttribute(attributeName, newText, moveToNextAttributeIfNeeded.bind(this)); return; } this.updateTitle(); moveToNextAttributeIfNeeded.call(this); }, _tagNameEditingCommitted: function(element, newText, oldText, tagName, moveDirection) { delete this._editing; var self = this; function cancel() { var closingTagElement = self._distinctClosingTagElement(); if (closingTagElement) closingTagElement.textContent = "</" + tagName + ">"; self._editingCancelled(element, tagName); moveToNextAttributeIfNeeded.call(self); } /** * @this {WebInspector.ElementsTreeElement} */ function moveToNextAttributeIfNeeded() { if (moveDirection !== "forward") { this._addNewAttribute(); return; } var attributes = this._node.attributes(); if (attributes.length > 0) this._triggerEditAttribute(attributes[0].name); else this._addNewAttribute(); } newText = newText.trim(); if (newText === oldText) { cancel(); return; } var treeOutline = this.treeOutline; var wasExpanded = this.expanded; function changeTagNameCallback(error, nodeId) { if (error || !nodeId) { cancel(); return; } var newTreeItem = treeOutline.selectNodeAfterEdit(wasExpanded, error, nodeId); moveToNextAttributeIfNeeded.call(newTreeItem); } this._node.setNodeName(newText, changeTagNameCallback); }, /** * @param {!WebInspector.DOMNode} textNode * @param {!Element} element * @param {string} newText */ _textNodeEditingCommitted: function(textNode, element, newText) { delete this._editing; /** * @this {WebInspector.ElementsTreeElement} */ function callback() { this.updateTitle(); } textNode.setNodeValue(newText, callback.bind(this)); }, /** * @param {!Element} element * @param {*} context */ _editingCancelled: function(element, context) { delete this._editing; // Need to restore attributes structure. this.updateTitle(); }, /** * @return {!Element} */ _distinctClosingTagElement: function() { // FIXME: Improve the Tree Element / Outline Abstraction to prevent crawling the DOM // For an expanded element, it will be the last element with class "close" // in the child element list. if (this.expanded) { var closers = this._childrenListNode.querySelectorAll(".close"); return closers[closers.length-1]; } // Remaining cases are single line non-expanded elements with a closing // tag, or HTML elements without a closing tag (such as <br>). Return // null in the case where there isn't a closing tag. var tags = this.listItemElement.getElementsByClassName("webkit-html-tag"); return (tags.length === 1 ? null : tags[tags.length-1]); }, /** * @param {boolean=} onlySearchQueryChanged */ updateTitle: function(onlySearchQueryChanged) { // If we are editing, return early to prevent canceling the edit. // After editing is committed updateTitle will be called. if (this._editing) return; if (onlySearchQueryChanged) { this._hideSearchHighlight(); } else { var nodeInfo = this._nodeTitleInfo(WebInspector.linkifyURLAsNode); if (nodeInfo.shadowRoot) this.listItemElement.classList.add("shadow-root"); var highlightElement = createElement("span"); highlightElement.className = "highlight"; highlightElement.appendChild(nodeInfo.titleDOM); this.title = highlightElement; this._updateDecorations(); delete this._highlightResult; } delete this.selectionElement; if (this.selected) this.updateSelection(); this._preventFollowingLinksOnDoubleClick(); this._highlightSearchResults(); }, /** * @return {?Element} */ _createDecoratorElement: function() { var node = this._node; var decoratorMessages = []; var parentDecoratorMessages = []; var decorators = this.treeOutline.nodeDecorators(); for (var i = 0; i < decorators.length; ++i) { var decorator = decorators[i]; var message = decorator.decorate(node); if (message) { decoratorMessages.push(message); continue; } if (this.expanded || this._elementCloseTag) continue; message = decorator.decorateAncestor(node); if (message) parentDecoratorMessages.push(message) } if (!decoratorMessages.length && !parentDecoratorMessages.length) return null; var decoratorElement = createElement("div"); decoratorElement.classList.add("elements-gutter-decoration"); if (!decoratorMessages.length) decoratorElement.classList.add("elements-has-decorated-children"); decoratorElement.title = decoratorMessages.concat(parentDecoratorMessages).join("\n"); return decoratorElement; }, _updateDecorations: function() { if (this._decoratorElement) this._decoratorElement.remove(); this._decoratorElement = this._createDecoratorElement(); if (this._decoratorElement && this.listItemElement) this.listItemElement.insertBefore(this._decoratorElement, this.listItemElement.firstChild); }, /** * @param {!Node} parentElement * @param {string} name * @param {string} value * @param {boolean=} forceValue * @param {!WebInspector.DOMNode=} node * @param {function(string, string, string, boolean=, string=)=} linkify */ _buildAttributeDOM: function(parentElement, name, value, forceValue, node, linkify) { var closingPunctuationRegex = /[\/;:\)\]\}]/g; var highlightIndex = 0; var highlightCount; var additionalHighlightOffset = 0; var result; /** * @param {string} match * @param {number} replaceOffset * @return {string} */ function replacer(match, replaceOffset) { while (highlightIndex < highlightCount && result.entityRanges[highlightIndex].offset < replaceOffset) { result.entityRanges[highlightIndex].offset += additionalHighlightOffset; ++highlightIndex; } additionalHighlightOffset += 1; return match + "\u200B"; } /** * @param {!Element} element * @param {string} value * @this {WebInspector.ElementsTreeElement} */ function setValueWithEntities(element, value) { result = this._convertWhitespaceToEntities(value); highlightCount = result.entityRanges.length; value = result.text.replace(closingPunctuationRegex, replacer); while (highlightIndex < highlightCount) { result.entityRanges[highlightIndex].offset += additionalHighlightOffset; ++highlightIndex; } element.textContent = value; WebInspector.highlightRangesWithStyleClass(element, result.entityRanges, "webkit-html-entity-value"); } var hasText = (forceValue || value.length > 0); var attrSpanElement = parentElement.createChild("span", "webkit-html-attribute"); var attrNameElement = attrSpanElement.createChild("span", "webkit-html-attribute-name"); attrNameElement.textContent = name; if (hasText) attrSpanElement.createTextChild("=\u200B\""); var attrValueElement = attrSpanElement.createChild("span", "webkit-html-attribute-value"); var updates = this._updateInfo; if (updates && updates.isAttributeModified(name)) WebInspector.runCSSAnimationOnce(hasText ? attrValueElement : attrNameElement, "dom-update-highlight"); /** * @this {WebInspector.ElementsTreeElement} * @param {string} value * @return {!Element} */ function linkifyValue(value) { var rewrittenHref = node.resolveURL(value); if (rewrittenHref === null) { var span = createElement("span"); setValueWithEntities.call(this, span, value); return span; } value = value.replace(closingPunctuationRegex, "$&\u200B"); if (value.startsWith("data:")) value = value.trimMiddle(60); var anchor = linkify(rewrittenHref, value, "", node.nodeName().toLowerCase() === "a"); anchor.preventFollow = true; return anchor; } if (linkify && (name === "src" || name === "href")) { attrValueElement.appendChild(linkifyValue.call(this, value)); } else if (linkify && node.nodeName().toLowerCase() === "img" && name === "srcset") { var sources = value.split(","); for (var i = 0; i < sources.length; ++i) { if (i > 0) attrValueElement.createTextChild(", "); var source = sources[i].trim(); var indexOfSpace = source.indexOf(" "); var url = source.substring(0, indexOfSpace); var tail = source.substring(indexOfSpace); attrValueElement.appendChild(linkifyValue.call(this, url)); attrValueElement.createTextChild(tail); } } else { setValueWithEntities.call(this, attrValueElement, value); } if (hasText) attrSpanElement.createTextChild("\""); }, /** * @param {!Node} parentElement * @param {string} pseudoElementName */ _buildPseudoElementDOM: function(parentElement, pseudoElementName) { var pseudoElement = parentElement.createChild("span", "webkit-html-pseudo-element"); pseudoElement.textContent = "::" + pseudoElementName; parentElement.createTextChild("\u200B"); }, /** * @param {!Node} parentElement * @param {string} tagName * @param {boolean} isClosingTag * @param {boolean} isDistinctTreeElement * @param {function(string, string, string, boolean=, string=)=} linkify */ _buildTagDOM: function(parentElement, tagName, isClosingTag, isDistinctTreeElement, linkify) { var node = this._node; var classes = [ "webkit-html-tag" ]; if (isClosingTag && isDistinctTreeElement) classes.push("close"); var tagElement = parentElement.createChild("span", classes.join(" ")); tagElement.createTextChild("<"); var tagNameElement = tagElement.createChild("span", isClosingTag ? "" : "webkit-html-tag-name"); tagNameElement.textContent = (isClosingTag ? "/" : "") + tagName; if (!isClosingTag) { if (node.hasAttributes()) { var attributes = node.attributes(); for (var i = 0; i < attributes.length; ++i) { var attr = attributes[i]; tagElement.createTextChild(" "); this._buildAttributeDOM(tagElement, attr.name, attr.value, false, node, linkify); } } var hasUpdates; var updates = this._updateInfo; if (updates) { hasUpdates |= updates.hasRemovedAttributes(); var hasInlineText = this._childrenDisplayMode === WebInspector.ElementsTreeElement.ChildrenDisplayMode.InlineText; hasUpdates |= (!hasInlineText || this.expanded) && updates.hasChangedChildren(); // Highlight the tag name, as the inserted node is not visible (either child of a collapsed tree element or empty inline text). hasUpdates |= !this.expanded && updates.hasInsertedNodes() && (!hasInlineText || this._node.firstChild.nodeValue().length === 0); // Highlight the tag name, as the inline text node value has been cleared. // The respective empty node will be highlighted, but the highlight will not be visible to the user. hasUpdates |= hasInlineText && (updates.isCharDataModified() || updates.hasChangedChildren()) && this._node.firstChild.nodeValue().length === 0; } if (hasUpdates) WebInspector.runCSSAnimationOnce(tagNameElement, "dom-update-highlight"); } tagElement.createTextChild(">"); parentElement.createTextChild("\u200B"); }, /** * @param {string} text * @return {!{text: string, entityRanges: !Array.<!WebInspector.SourceRange>}} */ _convertWhitespaceToEntities: function(text) { var result = ""; var lastIndexAfterEntity = 0; var entityRanges = []; var charToEntity = WebInspector.ElementsTreeOutline.MappedCharToEntity; for (var i = 0, size = text.length; i < size; ++i) { var char = text.charAt(i); if (charToEntity[char]) { result += text.substring(lastIndexAfterEntity, i); var entityValue = "&" + charToEntity[char] + ";"; entityRanges.push({offset: result.length, length: entityValue.length}); result += entityValue; lastIndexAfterEntity = i + 1; } } if (result) result += text.substring(lastIndexAfterEntity); return {text: result || text, entityRanges: entityRanges}; }, /** * @param {function(string, string, string, boolean=, string=)=} linkify */ _nodeTitleInfo: function(linkify) { var node = this._node; var info = {titleDOM: createDocumentFragment(), hasChildren: this.hasChildren}; switch (node.nodeType()) { case Node.ATTRIBUTE_NODE: this._buildAttributeDOM(info.titleDOM, /** @type {string} */ (node.name), /** @type {string} */ (node.value), true); break; case Node.ELEMENT_NODE: var pseudoType = node.pseudoType(); if (pseudoType) { this._buildPseudoElementDOM(info.titleDOM, pseudoType); info.hasChildren = false; break; } var tagName = node.nodeNameInCorrectCase(); if (this._elementCloseTag) { this._buildTagDOM(info.titleDOM, tagName, true, true); info.hasChildren = false; break; } this._buildTagDOM(info.titleDOM, tagName, false, false, linkify); switch (this._childrenDisplayMode) { case WebInspector.ElementsTreeElement.ChildrenDisplayMode.HasChildren: if (!this.expanded) { var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node bogus"); textNodeElement.textContent = "\u2026"; info.titleDOM.createTextChild("\u200B"); this._buildTagDOM(info.titleDOM, tagName, true, false); } break; case WebInspector.ElementsTreeElement.ChildrenDisplayMode.InlineText: var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node"); var result = this._convertWhitespaceToEntities(node.firstChild.nodeValue()); textNodeElement.textContent = result.text; WebInspector.highlightRangesWithStyleClass(textNodeElement, result.entityRanges, "webkit-html-entity-value"); info.titleDOM.createTextChild("\u200B"); info.hasChildren = false; this._buildTagDOM(info.titleDOM, tagName, true, false); var updates = this._updateInfo; if (updates && (updates.hasInsertedNodes() || updates.hasChangedChildren())) WebInspector.runCSSAnimationOnce(textNodeElement, "dom-update-highlight"); updates = this._updateInfo; if (updates && updates.isCharDataModified()) WebInspector.runCSSAnimationOnce(textNodeElement, "dom-update-highlight"); break; case WebInspector.ElementsTreeElement.ChildrenDisplayMode.NoChildren: if (this.treeOutline.isXMLMimeType || !WebInspector.ElementsTreeElement.ForbiddenClosingTagElements[tagName]) this._buildTagDOM(info.titleDOM, tagName, true, false); break; } break; case Node.TEXT_NODE: if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "script") { var newNode = info.titleDOM.createChild("span", "webkit-html-text-node webkit-html-js-node"); newNode.textContent = node.nodeValue(); var javascriptSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/javascript", true); javascriptSyntaxHighlighter.syntaxHighlightNode(newNode).then(updateSearchHighlight.bind(this)); } else if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "style") { var newNode = info.titleDOM.createChild("span", "webkit-html-text-node webkit-html-css-node"); newNode.textContent = node.nodeValue(); var cssSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/css", true); cssSyntaxHighlighter.syntaxHighlightNode(newNode).then(updateSearchHighlight.bind(this)); } else { info.titleDOM.createTextChild("\""); var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node"); var result = this._convertWhitespaceToEntities(node.nodeValue()); textNodeElement.textContent = result.text; WebInspector.highlightRangesWithStyleClass(textNodeElement, result.entityRanges, "webkit-html-entity-value"); info.titleDOM.createTextChild("\""); var updates = this._updateInfo; if (updates && updates.isCharDataModified()) WebInspector.runCSSAnimationOnce(textNodeElement, "dom-update-highlight"); } break; case Node.COMMENT_NODE: var commentElement = info.titleDOM.createChild("span", "webkit-html-comment"); commentElement.createTextChild("<!--" + node.nodeValue() + "-->"); break; case Node.DOCUMENT_TYPE_NODE: var docTypeElement = info.titleDOM.createChild("span", "webkit-html-doctype"); docTypeElement.createTextChild("<!DOCTYPE " + node.nodeName()); if (node.publicId) { docTypeElement.createTextChild(" PUBLIC \"" + node.publicId + "\""); if (node.systemId) docTypeElement.createTextChild(" \"" + node.systemId + "\""); } else if (node.systemId) docTypeElement.createTextChild(" SYSTEM \"" + node.systemId + "\""); if (node.internalSubset) docTypeElement.createTextChild(" [" + node.internalSubset + "]"); docTypeElement.createTextChild(">"); break; case Node.CDATA_SECTION_NODE: var cdataElement = info.titleDOM.createChild("span", "webkit-html-text-node"); cdataElement.createTextChild("<![CDATA[" + node.nodeValue() + "]]>"); break; case Node.DOCUMENT_FRAGMENT_NODE: var fragmentElement = info.titleDOM.createChild("span", "webkit-html-fragment"); fragmentElement.textContent = node.nodeNameInCorrectCase().collapseWhitespace(); delete this.shadowHostToolbar; if (node.isInShadowTree()) { var shadowRootType = node.shadowRootType(); if (shadowRootType) { info.shadowRoot = true; fragmentElement.classList.add("shadow-root"); if (Runtime.experiments.isEnabled("composedShadowDOM")) { var isYoungestShadowRoot = node === node.parentNode.shadowRoots()[0]; if (isYoungestShadowRoot) { var toolbarElement = info.titleDOM.createChild("span", "webkit-html-fragment"); this.shadowHostToolbar = this._createShadowHostToolbar(); toolbarElement.appendChild(this.shadowHostToolbar); } } } } break; default: info.titleDOM.createTextChild(node.nodeNameInCorrectCase().collapseWhitespace()); } /** * @this {WebInspector.ElementsTreeElement} */ function updateSearchHighlight() { delete this._highlightResult; this._highlightSearchResults(); } return info; }, /** * @param {?WebInspector.ElementsTreeOutline.ShadowHostDisplayMode} mode */ setShadowHostToolbarMode: function(mode) { this._shadowHostToolbarMode = mode; }, /** * @return {!Element} */ _createShadowHostToolbar: function() { /** * @this {WebInspector.ElementsTreeElement} * @param {string} label * @param {string} tooltip * @param {?WebInspector.ElementsTreeOutline.ShadowHostDisplayMode} mode */ function createButton(label, tooltip, mode) { var button = createElement("button"); button.className = "shadow-host-display-mode-toolbar-button"; button.textContent = label; button.title = tooltip; button.tabIndex = -1; button.mode = mode; if (mode) button.classList.add("custom-mode") button.addEventListener("click", buttonClicked.bind(this), true); toolbar.appendChild(button); return button; } /** * @this {WebInspector.ElementsTreeElement} * @param {!Event} event */ function buttonClicked(event) { var button = event.target; if (button.disabled) return; this.treeOutline.setShadowHostDisplayMode(this._node.parentNode, button.mode); event.consume(); } var toolbar = createElementWithClass("span", "shadow-host-display-mode-toolbar"); var buttons = []; buttons.push(createButton.call(this, "Logical", WebInspector.UIString("Logical view \n(Light and Shadow DOM are shown separately)."), null)); buttons.push(createButton.call(this, "Composed", WebInspector.UIString("Composed view\n(Light DOM is shown as distributed into Shadow DOM)."), WebInspector.ElementsTreeOutline.ShadowHostDisplayMode.Composed)); var mode = this._shadowHostToolbarMode || null; for (var i = 0; i < buttons.length; ++i) { var currentModeButton = mode === buttons[i].mode; buttons[i].classList.toggle("toggled", currentModeButton); buttons[i].disabled = currentModeButton; } return toolbar; }, remove: function() { if (this._node.pseudoType()) return; var parentElement = this.parent; if (!parentElement) return; if (!this._node.parentNode || this._node.parentNode.nodeType() === Node.DOCUMENT_NODE) return; this._node.removeNode(); }, /** * @param {function(boolean)=} callback */ toggleEditAsHTML: function(callback) { if (this._editing && this._htmlEditElement && WebInspector.isBeingEdited(this._htmlEditElement)) { this._editing.commit(); return; } /** * @param {?Protocol.Error} error */ function selectNode(error) { if (callback) callback(!error); } /** * @param {string} initialValue * @param {string} value */ function commitChange(initialValue, value) { if (initialValue !== value) node.setOuterHTML(value, selectNode); } var node = this._node; node.getOuterHTML(this._startEditingAsHTML.bind(this, commitChange)); }, _copyCSSPath: function() { InspectorFrontendHost.copyText(WebInspector.DOMPresentationUtils.cssPath(this._node, true)); }, _copyXPath: function() { InspectorFrontendHost.copyText(WebInspector.DOMPresentationUtils.xPath(this._node, true)); }, _highlightSearchResults: function() { if (!this._searchQuery || !this._searchHighlightsVisible) return; this._hideSearchHighlight(); var text = this.listItemElement.textContent; var regexObject = createPlainTextSearchRegex(this._searchQuery, "gi"); var match = regexObject.exec(text); var matchRanges = []; while (match) { matchRanges.push(new WebInspector.SourceRange(match.index, match[0].length)); match = regexObject.exec(text); } // Fall back for XPath, etc. matches. if (!matchRanges.length) matchRanges.push(new WebInspector.SourceRange(0, text.length)); this._highlightResult = []; WebInspector.highlightSearchResults(this.listItemElement, matchRanges, this._highlightResult); }, _scrollIntoView: function() { function scrollIntoViewCallback(object) { /** * @suppressReceiverCheck * @this {!Element} */ function scrollIntoView() { this.scrollIntoViewIfNeeded(true); } if (object) object.callFunction(scrollIntoView); } this._node.resolveToObject("", scrollIntoViewCallback); }, __proto__: TreeElement.prototype }
monaca/chrome-devtools-app
app/devtools/front_end/elements/ElementsTreeElement.js
JavaScript
mit
58,106
/* * Copyright (c) 2015, Bruce Schubert <bruce@emxsys.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Bruce Schubert, Emxsys nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * See: http://stackoverflow.com/questions/11167628/trees-in-twitter-bootstrap#16823729 * See: http://jsfiddle.net/jayhilwig/hv8vU/ */ $(function () { $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch'); $('.tree li.parent_li > span').on('click', function (e) { var children = $(this).parent('li.parent_li').find(' > ul > li'); if (children.is(":visible")) { children.hide('fast'); $(this).attr('title', 'Expand').find(' > i').addClass('glyphicon-plus-sign').removeClass('glyphicon-minus-sign'); } else { children.show('fast'); $(this).attr('title', 'Collapse').find(' > i').addClass('glyphicon-minus-sign').removeClass('glyphicon-plus-sign'); } e.stopPropagation(); }); });
WorldWindEarth/WWExplorerLib
src/model/util/Tree.js
JavaScript
mit
2,460
Meteor.settings.contactForm = { emailTo: 'to@test.com' }; var emailData = { name: 'Test Name', email: 'from@test.com', subject: 'Test Subject', message: 'Test Message' }; var dataSent = null; // Email sending stub Email = { send: function(data) { dataSent = data; } }; Tinytest.add('Schema', function (test) { test.instanceOf(Schema, Object); }); Tinytest.add('Schema - contactForm', function (test) { test.instanceOf(Schema.contactForm, SimpleSchema); }); Tinytest.add('Schema - contactForm - name', function (test) { test.instanceOf(Schema.contactForm._schema.name, Object); }); Tinytest.add('Schema - contactForm - email', function (test) { test.instanceOf(Schema.contactForm._schema.email, Object); }); Tinytest.add('Schema - contactForm - subject', function (test) { test.instanceOf(Schema.contactForm._schema.subject, Object); }); Tinytest.add('Schema - contactForm - message', function (test) { test.instanceOf(Schema.contactForm._schema.message, Object); }); if (Meteor.isServer) { Tinytest.add('Meteor - methods - sendEmail - exists', function (test) { test.include(Meteor.server.method_handlers, 'sendEmail'); }); Tinytest.add('Meteor - methods - sendEmail - fails on malformed data', function (test) { test.throws(function() { Meteor.call('sendEmail', {something: 'wrong'}); }); }); Tinytest.add('Meteor - methods - sendEmail - sends email successfully', function (test) { dataSent = null; Meteor.call('sendEmail', emailData); test.equal(dataSent.from, emailData.email); test.equal(dataSent.to, Meteor.settings.contactForm.emailTo); test.include(dataSent.text, emailData.subject); test.include(dataSent.text, emailData.message); }); } if (Meteor.isClient) { Tinytest.add('Meteor - templates - contactForm - has a schema helper', function (test) { test.equal(typeof Template.contactForm.__helpers.get('contactFormSchema'), 'function'); test.equal(Template.contactForm.__helpers.get('contactFormSchema')(), Schema.contactForm); }); }
pchomphoosang/meteor-traning-
packages/meteor-contact-form/contact-form-tests.js
JavaScript
mit
2,050
define([ 'jquery', 'underscore', 'backbone', 'views/LoginView', 'authentication', ], function ($, _, Backbone, LoginView, Authentication) { var LoginRouter = Backbone.Router.extend({ routes: { 'login' : 'login', 'logout' : 'logout' }, login: function () { var loginView = new LoginView(); $('#content').html(loginView.el); }, logout: function () { Authentication.logout(); }, }); return LoginRouter; });
alex-driedger/Nurdles
clients/web/js/routers/LoginRouter.js
JavaScript
mit
624
'use strict'; // Flags: --experimental-vm-modules const common = require('../common'); const assert = require('assert'); const { types } = require('util'); const { SourceTextModule } = require('vm'); (async () => { const m = new SourceTextModule('globalThis.importResult = import("");', { importModuleDynamically: common.mustCall(async (specifier, wrap) => { const m = new SourceTextModule(''); await m.link(() => 0); await m.evaluate(); return m.namespace; }), }); await m.link(() => 0); await m.evaluate(); const ns = await globalThis.importResult; delete globalThis.importResult; assert.ok(types.isModuleNamespaceObject(ns)); })().then(common.mustCall());
enclose-io/compiler
current/test/parallel/test-vm-module-dynamic-namespace.js
JavaScript
mit
710
var env = require('../env.js'); var gulp = require('gulp'); var tar = require('gulp-tar'); var gzip = require('gulp-gzip'); var dateFormat = require('dateformat'); // var revision = require('git-rev-sync') module.exports = function () { return gulp.src(env.folder.dist + '/**/*') // .pipe(tar(revision.short() + '-build.tar')) .pipe(tar(dateFormat(new Date(), "yyyymmdd-HHMM") + '-build.tar')) .pipe(gzip()) .pipe(gulp.dest('./')); };
ekfuhrmann/super-gigi
gulp/tasks/compress.js
JavaScript
mit
456
'use strict'; var common = require('../common'); var assert = require('assert'); var Transform = require('../../').Transform; var _transformCalled = false; function _transform(d, e, n) { _transformCalled = true; n(); } var _flushCalled = false; function _flush(n) { _flushCalled = true; n(); } var t = new Transform({ transform: _transform, flush: _flush }); t.end(new Buffer('blerg')); t.resume(); process.on('exit', function() { assert.equal(t._transform, _transform); assert.equal(t._flush, _flush); assert(_transformCalled); assert(_flushCalled); });
devlato/readable-stream
test/parallel/test-stream-transform-constructor-set-methods.js
JavaScript
mit
581
(function (window, $, undefined) { 'use strict'; var Samba; Samba = function (dashboard) { var viewModel = new ProcessModel(); viewModel.requestStatus = function () { dashboard.socket.emit('status-samba'); }; viewModel.start = function () { dashboard.socket.emit('start-samba'); }; viewModel.stop = function () { dashboard.socket.emit('stop-samba'); }; viewModel.hostName = ko.observable(window.location.hostname); dashboard.socket.on('status-samba', function (status) { viewModel.status(status); }); // Add required UI elements $('#services').append('<div id="samba"></div>'); $('#samba').load('plugin/13_samba/plugin.html', function () { ko.applyBindings({samba: viewModel}, $('#samba')[0]); }); dashboard.socket.on('services.refresh', viewModel.requestStatus); dashboard.socket.emit('services.register', 'services.samba'); viewModel.requestStatus(); }; window.Dashboard.plugins.push(Samba); }(window, jQuery));
BrianAdams/openrov-dashboard
src/plugins/13_samba/public/js/samba.js
JavaScript
mit
1,024
var nodemailer = require('nodemailer'); var config = require('../config/global').get('email'); var transpoter = nodemailer.createTransport({ service: config.service, auth: { user: config.username, pass: config.password } }); function Mail(toEmail) { this.toEmail = toEmail; } Mail.prototype.send = function (msg) { var mailOptions = { from: config.username, to: this.toEmail, subject: msg, text: msg, html: '<b>' + msg + '</b>' }; transpoter.sendMail(mailOptions, function (err, info) { if (err) { console.log(err); return; } console.log('message sent: ' + info.response); }); } module.exports = exports = Mail;
xuxingfan/task-board
library/mail.js
JavaScript
mit
683
/* * Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com> * MIT License. See mit-license.txt for more info. */ import assert from 'assert' import getMegaSource from './lib/megabyte-stream' import send from './lib/send' import wait from '../lib/wait' import streams from '../lib/streams' import hoxy from '../src/main' describe('Round trips', function() { it('should round trip synchronously', () => { let steps = '' return send({}) .through('request', function() { steps += '1' }) .through('request-sent', function() { steps += '2' }) .to(function*(req, resp) { steps += '3'; resp.end('') }) .through('response', function() { steps += '4' }) .through('response-sent', function() { steps += '5' }) .receiving(function*() { assert.strictEqual(steps, '12345') }).promise() }) it('should round trip asynchronously', () => { let steps = '' return send({}) .through('request', function*() { yield wait(); steps += '1' }) .through('request-sent', function*() { yield wait(); steps += '2' }) .to(function*(req, resp) { yield wait(); steps += '3'; resp.end('') }) .through('response', function*() { yield wait(); steps += '4' }) .through('response-sent', function*() { yield wait(); steps += '5' }) .receiving(function*() { assert.strictEqual(steps, '12345') }).promise() }) it('should handle a synchronous request intercept error', () => { return send({}).through('request', function() { throw new Error('fake') }).promise() .then(() => { throw new Error('should have failed') }, () => {}) }) it('should handle a synchronous request intercept error gracefully', () => { return send({}, true).through('request', function() { throw new Error('fake') }).promise() }) it('should handle a synchronous request-sent intercept error gracefully', () => { return send({}, true).through('request-sent', function() { throw new Error('fake') }).promise() }) it('should handle a synchronous response intercept error gracefully', () => { return send({}, true).through('response', function() { throw new Error('fake') }).promise() }) it('should handle a synchronous response-sent intercept error gracefully', () => { return send({}, true).through('response-sent', function() { throw new Error('fake') }).promise() }) it('should handle an asynchronous request intercept error gracefully', () => { return send({}, true).through('request', function*() { yield Promise.reject(new Error('fake')) }).promise() }) it('should handle an asynchronous request-sent intercept error gracefully', () => { return send({}, true).through('request-sent', function*() { yield Promise.reject(new Error('fake')) }).promise() }) it('should handle an asynchronous response intercept error gracefully', () => { return send({}, true).through('response', function*() { yield Promise.reject(new Error('fake')) }).promise() }) it('should handle an asynchronous response-sent intercept error gracefully', () => { return send({}, true).through('response-sent', function*() { yield Promise.reject(new Error('fake')) }).promise() }) it('should send body data to the server', () => { return send({ method: 'POST', path: 'http://example.com/foobar', body: 'abc', headers: { 'x-foo': 'bar' }, }).to(function*(req, resp) { let body = yield streams.collect(req, 'utf8') assert.strictEqual(req.url, '/foobar') assert.strictEqual(req.headers['x-foo'], 'bar') assert.strictEqual(body, 'abc') resp.end('') }).promise() }) it('should send body data to the client', () => { return send({}).to({ statusCode: 404, body: 'abc', headers: { 'x-foo': 'bar' }, }).receiving(function*(resp) { assert.strictEqual(resp.statusCode, 404) assert.strictEqual(resp.headers['x-foo'], 'bar') assert.strictEqual(resp.body, 'abc') }).promise() }) it('should modify body data sent to the server', () => { return send({ method: 'POST', path: 'http://example.com/foobar', body: 'abc', headers: { 'x-foo': 'bar' }, }).through('request', function(req) { req.url = '/bazqux' req.headers['x-foo'] = 'baz' req.string = 'def' }).to(function*(req, resp) { let body = yield streams.collect(req, 'utf8') assert.strictEqual(req.url, '/bazqux') assert.strictEqual(req.headers['x-foo'], 'baz') assert.strictEqual(body, 'def') resp.end('') }).promise() }) it('should modify body data sent to the client', () => { return send({}).to({ statusCode: 404, body: 'abc', headers: { 'x-foo': 'bar' }, }).through('response', function(req, resp) { resp.statusCode = 200 resp.string = 'def' }).receiving(function*(resp) { assert.strictEqual(resp.statusCode, 200) assert.strictEqual(resp.headers['x-foo'], 'bar') assert.strictEqual(resp.body, 'def') }).promise() }) it('should behave asynchronously in the request phase', () => { let start = Date.now() return send({}).through('request', function*() { yield wait(50) }).promise().then(() => { assert.ok(Date.now() - start >= 50) }) }) it('should behave asynchronously in the response phase', () => { let start = Date.now() return send({}).through('response', function*() { yield wait(50) }).promise().then(() => { assert.ok(Date.now() - start >= 50) }) }) it('should skip the server hit if the response statusCode is populated', () => { return send({}).through('request', function* (req, resp) { resp.statusCode = 404 }).to(function*() { throw new Error('server hit was not skipped') }).promise() }) it('should skip the server hit if the response body is populated', () => { return send({}).through('request', function* (req, resp) { resp.string = '123' }).to(function*() { throw new Error('server hit was not skipped') }).promise() }) it('should simulate latency upload', () => { let start = Date.now() return send({}).through('request', function*(req) { req.slow({ latency: 100 }) }).promise().then(() => { assert.ok(Date.now() - start >= 100) }) }) it('should simulate latency download', () => { let start = Date.now() return send({}).through('response', function*(req, resp) { resp.slow({ latency: 100 }) }).promise().then(() => { assert.ok(Date.now() - start >= 100) }) }) // TODO: I can't figure out why this is failing. it.skip('should handle large uploads', () => { return send({ method: 'POST', body: getMegaSource(), }).promise() }) it('should handle large downloads', () => { return send({}).to({ body: getMegaSource(), }).promise() }) // TODO: I can't figure out why this is failing. it.skip('should simulate slow upload', () => { let start = Date.now() return send({ method: 'POST', body: getMegaSource(), }).through('request', function*(req) { req.slow({ rate: 1024000 }) }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 50, `took ${diff}ms`) }) }) it('should simulate slow download', () => { let start = Date.now() return send({}).to({ body: getMegaSource(), }).through('response', function*(req, resp) { resp.slow({ rate: 1024000 }) }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 1000, `took ${diff}ms`) }) }) it('should get and set data', () => { return send({}).through('request', function*() { this.data('foo', 123) }).through('request-sent', function*() { this.data('foo', 123) }).through('response', function*() { assert.strictEqual(this.data('foo'), 123) }).through('response-sent', function*() { assert.strictEqual(this.data('foo'), 123) }).promise() }) it('should preserve content length sent if body unchanged', () => { return send({ body: 'abcdefg', method: 'POST', headers: { 'content-length': 7 }, }).to(function*(req, resp) { let body = yield streams.collect(req, 'utf8') assert.strictEqual(body, 'abcdefg') assert.equal(req.headers['content-length'], 7) resp.end('') }).promise() }) it('should preserve content length sent if body changed', () => { return send({ body: 'abcdefg', method: 'POST', headers: { 'content-length': 7 }, }).through('request', function(req) { req.string = 'qwert' }).to(function*(req, resp) { let body = yield streams.collect(req, 'utf8') assert.strictEqual(body, 'qwert') assert.equal(req.headers['content-length'], 5) resp.end('') }).promise() }) it('should simulate proxy-level slow download (1)', () => { let start = Date.now() let slow = { rate: 1024000 } return send({}, false, { slow }).to({ body: getMegaSource(), }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 1000, `took ${diff}ms`) }) }) it('should simulate proxy-level slow download (2)', () => { let start = Date.now() let slow = { down: 1024000 } return send({}, false, { slow }).to({ body: getMegaSource(), }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 1000, `took ${diff}ms`) }) }) it('should simulate proxy-level slow download with a setter', () => { let start = Date.now() let slow = { rate: 1024000 } return send({}, false).tweak(proxy => { proxy.slow(slow) }).to({ body: getMegaSource(), }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 1000, `took ${diff}ms`) }) }) it('should get proxy-level slow opts (1)', () => { let slow = { rate: 1024000 } var proxy = hoxy.createServer({ slow }) assert.deepEqual(proxy.slow(), slow) }) it('should get proxy-level slow opts (2)', () => { let slow = { rate: 1024000 } var proxy = hoxy.createServer() proxy.slow(slow) assert.deepEqual(proxy.slow(), slow) }) it('proxy-level rate and down should work together', () => { let start = Date.now() let slow = { rate: 1024000, down: 512000 } return send({}, false, { slow }).to({ body: getMegaSource(), }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 2000, `took ${diff}ms`) }) }) it('proxy-level rate and down should work together (2)', () => { let start = Date.now() let slow = { rate: 512000, down: 1024000 } return send({}, false, { slow }).to({ body: getMegaSource(), }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 2000, `took ${diff}ms`) }) }) it('should simulate proxy-level latency download', () => { let start = Date.now() let slow = { latency: 1000 } return send({}, false, { slow }).to({ body: getMegaSource(), }).promise().then(() => { let end = Date.now() , diff = end - start assert.ok(diff >= 1000, `took ${diff}ms`) }) }) })
tobli/hoxy
test/round.test.js
JavaScript
mit
11,505
var rurl = require('relative-url') var map = {http:'ws', https:'wss'} var def = 'ws' module.exports = function (url, location) { return rurl(url, location, map, def) }
ssbc/pull-ws-server
ws-url.js
JavaScript
mit
172
/* eslint-env jest */ import path from 'path' import fs from 'fs-extra' import { nextBuild } from 'next-test-utils' const appDir = path.join(__dirname, '..') const nextConfig = path.join(appDir, 'next.config.js') describe('Building Firebase', () => { // TODO: investigate re-enabling this test in node 12 environment it.skip('Throws an error when building with firebase dependency with worker_threads', async () => { await fs.writeFile( nextConfig, `module.exports = { experimental: { workerThreads: true } }` ) const results = await nextBuild(appDir, [], { stdout: true, stderr: true }) expect(results.stdout + results.stderr).toMatch(/Build error occurred/) expect(results.stdout + results.stderr).toMatch( /grpc_node\.node\. Module did not self-register\./ ) }) it('Throws no error when building with firebase dependency without worker_threads', async () => { await fs.remove(nextConfig) const results = await nextBuild(appDir, [], { stdout: true, stderr: true }) expect(results.stdout + results.stderr).not.toMatch(/Build error occurred/) expect(results.stdout + results.stderr).not.toMatch( /grpc_node\.node\. Module did not self-register\./ ) }) })
azukaru/next.js
test/integration/firebase-grpc/test/index.test.js
JavaScript
mit
1,237
require( 'babel-core/register' ); // var s = require( '../src/core/regex' ); var C = require( '../src' ); window.C = C; var StrClause = C.cat( 'foos', C.oneOrMore( C.scat( 'foo' ) ), 'wee', C.zeroOrMore( C.scat( 'weeeeeeee' ) ), 'bars', C.oneOrMore( C.scat( 'bar' ) ) ); var r = C.conform( StrClause, 'foofoofoobarbar' ); console.log( r ); // var PropagatedAndClause = C.and( // C.isArray, // C.cat( // 'firstPart', C.oneOrMore( C.isNum ), // 'secondPart', C.isBool, // 'thirdPart', C.oneOrMore( C.isNum ) ), // function firstThirdPartEqualLen( cargs ) { // const { firstPart, thirdPart } = cargs; // console.log( cargs ); // return firstPart.length === thirdPart.length; // } // ); // // var conformed1 = [ 1, 2, 3, 4, true, 5, 6, 7, 8 ]; // console.log( PropagatedAndClause.conform( conformed1 ) ); // var NumOrStr = C.or( C.isNum, C.isStr, C.isObj, C.isDate, C.isNatInt ); // var r = NumOrStr.conform( 's' ); // console.log( NumOrStr ); // C( 'xyz.superapp.item/title', s.isStr ); // console.log( s ); // var AdderFnClause = s.fclause({ // args: s.cat('x', s.isNum), // ret: s.fclause({ // args: s.cat('y', s.isNum), // ret: s.isNum // }), // }); // // var adderFn = AdderFnClause.instrument(function (x) { // return function (y) { // console.log(x, y); // return x + y; // }; // }); // var brokenAdderFn = AdderFnClause.instrument(() => (y) => 'z'); // console.log(adderFn(1)(2)) // var NamedGroupedClause = C.cat( // ['z', 'it\'s a fuuuunction', C.isFn], // ['b', C.isObj], // ['c', 'another fuuuunction', C.isFn], // ['a', C.isObj] // ); // // var conformed = NamedGroupedClause.conform(conformist); // function startWithOo(key) { // return key.indexOf('oo') === 0; // } // // var ObjClause = C.shape({ // req: { // 'title': s.isStr, // 'userId': s.isNum, // }, // opt: { // 'content': s.isStr, // 'ooShape': [startWithOo, C.shape({ // req: { // 'val': s.isNum, // }, // })], // }, // }); // // var conformed1 = { title: 'Do it', content: 'blah', userId: 2 }; // var conformed2 = { title: 'Do it', content: 'blah', userId: 2, ooA: {val: 1}, ooB: {val: 2}, ooC: {val: 3} }; // var unconformed1 = { content: false, userId: 2 }; // var unconformed2 = { title: 'Do it', content: false, userId: 'wrong' }; // var unconformed3 = { title: 1234, content: null, userId: 2 }; // var unconformed4 = { title: 'Do it', content: false, userId: 'wrong', unknownField: 2 }; // // ObjClause.conform(conformed1); // ObjClause.conform(unconformed1); // console.log(ObjClause.conform(conformed2)); // // ObjClause.conform(unconformed2); // ObjClause.conform(unconformed3); // ObjClause.conform(unconformed4); // var fnList = ['shape', 'isValid', 'conform', 'fclause', 'isObj', 'isFn']; // var ClauseObj = C.keys({req: fnList}); // var InsaneClauseObj = C.keys({req: fnList.concat(['voodooooooooo'])}); // console.log(C.isValid(ClauseObj, S)); // console.log(C.isValid(InsaneClauseObj, S)); // var NamedGroupedClause = C.cat( // ['z', 'it\'s a fuuuunction', C.isFn], // ['b', C.isObj], // ['c', 'another fuuuunction', C.isFn], // ['a', C.isObj] // ); // // var conformist = [function(){}, {}, function() {}, {}]; // // var conformed = NamedGroupedClause.conform(conformist); // // console.log(conformed); // var Clause = s.cat('a', s.isNum, 'b', s.isStr); // var Clause = s.or( // // s.zeroOrMore(s.cat(s.isStr, s.isNum)), // s.collOf(s.cat(s.isStr, s.isNum)) // ); // var r = Clause.conform([1, '2']); // console.log(r); // // var AdderFnClause = s.fclause({ // args: s.cat('x', s.isNum), // ret: s.fclause({ // args: s.cat('y', s.isNum), // ret: s.isNum, // }), // }); // // var adderFn = function(x) { // return function(y) { // return x + y; // } // }; // var adderFn = AdderFnClause.instrument(adderFn); // var brokenAdderFn = AdderFnClause.instrument((x) => (y) => 'z'); // var r = brokenAdderFn(1)(3); // console.log(r); // var sheepCounterClause = C.fclause({ // args: C.cat(C.isNum), // ret: s.isStr, // }); // // var sheepCounter = sheepCounterClause.instrument(function(c) { // return c + ' sheep and counting.'; // }); // // var r = sheepCounter('hello'); // console.log(r); // var ss = s.cat(s.isNum); // var r = ss.conform([2]); // console.log(r); // var NamedClause = s.cat('z', s.isFn, 'b', s.isObj, 'c', s.isFn, 'a', s.isObj); // // var UnnamedClause = C.cat(C.isFn, C.isObj,C.isFn, C.isObj); // // var EmptyClause = s.cat(); // // var conformed = EmptyClause.conform([]); // var unconformed = EmptyClause.conform([1]); // console.log('c', conformed, unconformed); // expect(conformed).to.deep.equal({ z: fn, b: {}, c: fn, a: { a: 1 } }); // var nonconformed = NamedClause.conform(nonconformist); // var AmpliferClause = s.fclause({ // args: s.cat(s.isNum), // ret: s.isNum, // }); // // var AdderFnClause = s.fclause({ // args: s.cat('amplifier', AmpliferClause, 'x', s.isNum), // ret: s.fclause({ // args: s.cat('y', s.isNum), // ret: s.isNum, // }), // }); // var adderFn = AdderFnClause.instrument((amp, x) => (y) => amp(x) + y); // var r = adderFn((x) => x * 2, 1)(2); // var SS = s.or('a', s.shape({ // req: { // normalKeys: [s.isStr, s.isNum], // }, // }), 'b', s.isNum); // // var r = SS.conform({ key1: 2 }); // s('xyz.superapp.item', s.isObj); // var r = s('xyz.superapp.item'); // console.log(r.conform({z:1})); // s('xyz.superapp.item', s.and(s.isObj, s.shape({req: ['title', 'content']}))); // s('xyz.superapp.item.title', s.isStr); // var r = s('xyz.superapp.item').conform({ title: 'a', content: 'b' }); // console.log(r); // // s('todoapp', // s('headline', s.and(s.isStr, s.notEmpty)), // { // 'list': s.shape({ // req: { // 'title': s('todoapp.headline'), // 'items': s.zeroOrMore(s('todoapp.item')), // }, // }), // 'item': [ // s.shape({ // req: { // title: s('./title'), // content: s('./content'), // isDone: s('./isDone'), // reminder: s('./reminder'), // }, // opt: { // reminder: s.isDate, // }, // }), // s('title', s('todoapp.headline')), // s('content', s.and(s.isStr, s.notEmpty)), // s('date', s.isDate), // s('isDone', s.isBool), // s('reminder', s.isDate)], // }); // // s('todoapp', () => { // s('list', s.isObj) // }); // // // var ListClause = s('todoapp.list'); // // var ItemClause = s('todoapp.item'); // // var contentClause = s('todoapp.item.content'); // // // var r = ListClause.conform({ title: 'hello', items: [] }); // console.log(r);
settinghead/specky
author_experiments/test.tmp.js
JavaScript
mit
6,673
"use strict"; var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function (req, res, next) { res.send('respond with a resource'); }); module.exports = router;
Elou44/Hyblab2016
presse_ocean/routes/users.js
JavaScript
mit
221
describe("form submission for reporting a problem", function () { var FORM_TEXT = '<form action="ajax-endpoint"><button class="button" name="button" type="submit">Send</button></form>'; var $form, reportAProblemForm; beforeEach(function() { setFixtures(FORM_TEXT); $form = $('form'); reportAProblemForm = new GOVUK.ReportAProblemForm($form); }); it("should append a hidden 'javascript_enabled' field to the form", function() { expect($form.find("[name=javascript_enabled]").val()).toBe("true"); }); it("should append a hidden 'referrer' field to the form", function() { expect($form.find("[name=referrer]").val()).toBe("unknown"); }); describe("while the request is being handled", function() { it("should disable the submit button to prevent multiple problem reports", function () { spyOn($, "ajax").and.callFake(function(options) {}); $form.triggerHandler('submit'); expect($('.button')).toBeDisabled(); }); }); describe("when the form is submitted", function() { it("should submit using ajax to the action specified by the form", function() { var args; spyOn($, "ajax"); $form.triggerHandler('submit'); expect($.ajax).toHaveBeenCalled(); args = $.ajax.calls.mostRecent().args; expect(args[0].url).toBe('ajax-endpoint'); }); }); describe("if the request succeeds", function() { it("should trigger a success event", function() { spyOn($form, "trigger"); spyOn($, "ajax").and.callFake(function(options) { options.success({message: 'great success!'}); }); $form.triggerHandler('submit'); expect($form.trigger).toHaveBeenCalledWith("reportAProblemForm.success", {message: 'great success!'}); }); }); describe("if the request is invalid", function() { it("should re-enable the submit button, in order to allow the user to resubmit", function () { spyOn($, "ajax").and.callFake(function(options) { options.error({status: 422}, 'error'); }); $form.triggerHandler('submit'); expect($form).toBeVisible(); expect($('.button')).not.toBeDisabled(); }); }); describe("if the request has failed with a status 500", function() { it("sshould trigger an error event", function() { spyOn($form, "trigger"); spyOn($, "ajax").and.callFake(function(options) { options.statusCode[500]({responseText: 'this might not even be JSON because nginx intercepts the error'}); }); $form.triggerHandler('submit'); expect($form.trigger).toHaveBeenCalledWith("reportAProblemForm.error"); }); }); });
kalleth/static
spec/javascripts/report-a-problem-form-spec.js
JavaScript
mit
2,649
/** * Socket.io configuration */ 'use strict'; var config = require('./environment'); // When the user disconnects.. perform this function onDisconnect(socket) { } // When the user connects.. perform this function onConnect(socket) { // When the client emits 'info', this listens and executes socket.on('info', function (data) { console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2)); }); // Insert sockets below require('../api/team/team.socket').register(socket); require('../api/player/player.socket').register(socket); require('../api/thing/thing.socket').register(socket); } module.exports = function (socketio) { // socket.io (v1.x.x) is powered by debug. // In order to see all the debug output, set DEBUG (in server/config/local.env.js) to including the desired scope. // // ex: DEBUG: "http*,socket.io:socket" // We can authenticate socket.io users and access their token through socket.handshake.decoded_token // // 1. You will need to send the token in `client/components/socket/socket.service.js` // // 2. Require authentication here: // socketio.use(require('socketio-jwt').authorize({ // secret: config.secrets.session, // handshake: true // })); socketio.on('connection', function (socket) { socket.address = socket.handshake.address !== null ? socket.handshake.address.address + ':' + socket.handshake.address.port : process.env.DOMAIN; socket.connectedAt = new Date(); // Call onDisconnect. socket.on('disconnect', function () { onDisconnect(socket); console.info('[%s] DISCONNECTED', socket.address); }); // Call onConnect. onConnect(socket); console.info('[%s] CONNECTED', socket.address); }); };
blundercode/logosApp
server/config/socketio.js
JavaScript
mit
1,764
var aleph = angular.module('aleph', ['ngRoute', 'ngAnimate', 'angular-loading-bar', 'ui.bootstrap', 'debounce', 'truncate', 'infinite-scroll']); aleph.config(['$routeProvider', '$locationProvider', 'cfpLoadingBarProvider', function($routeProvider, $locationProvider, cfpLoadingBarProvider) { cfpLoadingBarProvider.includeSpinner = false; $routeProvider.when('/search', { templateUrl: 'search_table.html', controller: 'SearchTableCtrl', reloadOnSearch: false, loginRequired: false, resolve: { 'result': loadSearchResult } }); $routeProvider.when('/search/export', { templateUrl: 'search_export.html', controller: 'SearchExportCtrl', reloadOnSearch: false, loginRequired: false, resolve: { 'result': loadSearchResult, 'attributes': loadSearchAttributes } }); $routeProvider.when('/search/graph', { templateUrl: 'search_graph.html', controller: 'SearchGraphCtrl', reloadOnSearch: false, loginRequired: false, resolve: { 'result': loadSearchResult, 'graph': loadSearchGraph } }); $routeProvider.when('/sources', { templateUrl: 'sources_index.html', controller: 'SourcesIndexCtrl', loginRequired: true }); $routeProvider.when('/sources/new', { templateUrl: 'sources_new.html', controller: 'SourcesNewCtrl', loginRequired: true, resolve: { 'crawlers': loadCrawlers } }); $routeProvider.when('/sources/:slug', { templateUrl: 'sources_edit.html', controller: 'SourcesEditCtrl', loginRequired: true, resolve: { 'crawlers': loadCrawlers, 'users': loadUsers, 'source': loadSource } }); $routeProvider.when('/lists/new', { templateUrl: 'lists_new.html', controller: 'ListsNewCtrl', loginRequired: true }); $routeProvider.when('/lists/:id', { templateUrl: 'lists_edit.html', controller: 'ListsEditCtrl', loginRequired: true }); $routeProvider.when('/lists/:id/entities', { templateUrl: 'lists_entities.html', controller: 'ListsEntitiesCtrl', reloadOnSearch: false, loginRequired: true }); $routeProvider.otherwise({ redirectTo: '/search', loginRequired: false }); $locationProvider.html5Mode(true); }]); aleph.directive('entityIcon', ['$http', function($http) { return { restrict: 'E', transclude: true, scope: { 'category': '=' }, templateUrl: 'entity_icon.html', link: function (scope, element, attrs, model) { } }; }]);
Luthien123/aleph
aleph/static/js/app.js
JavaScript
mit
2,576
import React from 'react'; import MouseEventTable from './mouse-event-table'; import TableInTabs from './table-in-tabs'; import GetPageNumByKeyTable from './expose-api-table'; import { Col, Panel } from 'react-bootstrap'; class Demo extends React.Component { render() { return ( <Col md={ 8 } mdOffset={ 1 }> <Panel header={ 'Mouse Event Table Example)' }> <h5>Source in /examples/js/others/mouse-event-table.js</h5> <h5>See event ouput in browser console</h5> <MouseEventTable/> </Panel> <Panel header={ 'Table in Tabs Example)' }> <h5>Source in /examples/js/others/table-in-tabs.js</h5> <h5>react-bootstrap-table in tabs</h5> <TableInTabs/> </Panel> <Panel header={ 'Get Page by Rowkey Example)' }> <h5>Source in /examples/js/others/expose-api-table.js</h5> <h5>Use expose API by BootstrapTable to get page number by rowkey</h5> <GetPageNumByKeyTable/> </Panel> </Col> ); } } export default Demo;
neelvadgama-hailo/react-bootstrap-table
examples/js/others/demo.js
JavaScript
mit
1,063
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v20.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var expressionService_1 = require("./expressionService"); var columnController_1 = require("../columnController/columnController"); var context_1 = require("../context/context"); var events_1 = require("../events"); var eventService_1 = require("../eventService"); var valueCache_1 = require("./valueCache"); var utils_1 = require("../utils"); var ValueService = /** @class */ (function () { function ValueService() { this.initialised = false; } ValueService.prototype.init = function () { this.cellExpressions = this.gridOptionsWrapper.isEnableCellExpressions(); this.initialised = true; }; ValueService.prototype.getValue = function (column, rowNode, forFilter, ignoreAggData) { // console.log(`turnActive = ${this.turnActive}`); if (forFilter === void 0) { forFilter = false; } if (ignoreAggData === void 0) { ignoreAggData = false; } // hack - the grid is getting refreshed before this bean gets initialised, race condition. // really should have a way so they get initialised in the right order??? if (!this.initialised) { this.init(); } if (!rowNode) { return undefined; } // pull these out to make code below easier to read var colDef = column.getColDef(); var field = colDef.field; var colId = column.getId(); var data = rowNode.data; var result; // if there is a value getter, this gets precedence over a field var groupDataExists = rowNode.groupData && rowNode.groupData[colId] !== undefined; var aggDataExists = !ignoreAggData && rowNode.aggData && rowNode.aggData[colId] !== undefined; if (forFilter && colDef.filterValueGetter) { result = this.executeValueGetter(colDef.filterValueGetter, data, column, rowNode); } else if (this.gridOptionsWrapper.isTreeData() && aggDataExists) { result = rowNode.aggData[colId]; } else if (this.gridOptionsWrapper.isTreeData() && colDef.valueGetter) { result = this.executeValueGetter(colDef.valueGetter, data, column, rowNode); } else if (this.gridOptionsWrapper.isTreeData() && (field && data)) { result = utils_1._.getValueUsingField(data, field, column.isFieldContainsDots()); } else if (groupDataExists) { result = rowNode.groupData[colId]; } else if (aggDataExists) { result = rowNode.aggData[colId]; } else if (colDef.valueGetter) { result = this.executeValueGetter(colDef.valueGetter, data, column, rowNode); } else if (field && data) { result = utils_1._.getValueUsingField(data, field, column.isFieldContainsDots()); } else { result = undefined; } // the result could be an expression itself, if we are allowing cell values to be expressions if (this.cellExpressions && (typeof result === 'string') && result.indexOf('=') === 0) { var cellValueGetter = result.substring(1); result = this.executeValueGetter(cellValueGetter, data, column, rowNode); } return result; }; ValueService.prototype.setValue = function (rowNode, colKey, newValue) { var column = this.columnController.getPrimaryColumn(colKey); if (!rowNode || !column) { return; } // this will only happen if user is trying to paste into a group row, which doesn't make sense // the user should not be trying to paste into group rows var data = rowNode.data; if (utils_1._.missing(data)) { rowNode.data = {}; } // for backwards compatibility we are also retrieving the newValueHandler as well as the valueSetter var _a = column.getColDef(), field = _a.field, newValueHandler = _a.newValueHandler, valueSetter = _a.valueSetter; // need either a field or a newValueHandler for this to work if (utils_1._.missing(field) && utils_1._.missing(newValueHandler) && utils_1._.missing(valueSetter)) { // we don't tell user about newValueHandler, as that is deprecated console.warn("ag-Grid: you need either field or valueSetter set on colDef for editing to work"); return; } var params = { node: rowNode, data: rowNode.data, oldValue: this.getValue(column, rowNode), newValue: newValue, colDef: column.getColDef(), column: column, api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi(), context: this.gridOptionsWrapper.getContext() }; params.newValue = newValue; var valueWasDifferent; if (newValueHandler && utils_1._.exists(newValueHandler)) { valueWasDifferent = newValueHandler(params); } else if (utils_1._.exists(valueSetter)) { valueWasDifferent = this.expressionService.evaluate(valueSetter, params); } else { valueWasDifferent = this.setValueUsingField(data, field, newValue, column.isFieldContainsDots()); } // in case user forgot to return something (possible if they are not using TypeScript // and just forgot, or using an old newValueHandler we didn't always expect a return // value here), we default the return value to true, so we always refresh. if (valueWasDifferent === undefined) { valueWasDifferent = true; } // if no change to the value, then no need to do the updating, or notifying via events. // otherwise the user could be tabbing around the grid, and cellValueChange would get called // all the time. if (!valueWasDifferent) { return; } // reset quick filter on this row rowNode.resetQuickFilterAggregateText(); this.valueCache.onDataChanged(); params.newValue = this.getValue(column, rowNode); var onCellValueChanged = column.getColDef().onCellValueChanged; if (typeof onCellValueChanged === 'function') { // to make callback async, do in a timeout setTimeout(function () { return onCellValueChanged(params); }, 0); } var event = { type: events_1.Events.EVENT_CELL_VALUE_CHANGED, event: null, rowIndex: rowNode.rowIndex, rowPinned: rowNode.rowPinned, column: params.column, api: params.api, colDef: params.colDef, columnApi: params.columnApi, context: params.context, data: rowNode.data, node: rowNode, oldValue: params.oldValue, newValue: params.newValue, value: params.newValue }; this.eventService.dispatchEvent(event); }; ValueService.prototype.setValueUsingField = function (data, field, newValue, isFieldContainsDots) { if (!field) { return false; } // if no '.', then it's not a deep value var valuesAreSame = false; if (!isFieldContainsDots) { data[field] = newValue; } else { // otherwise it is a deep value, so need to dig for it var fieldPieces = field.split('.'); var currentObject = data; while (fieldPieces.length > 0 && currentObject) { var fieldPiece = fieldPieces.shift(); if (fieldPieces.length === 0) { currentObject[fieldPiece] = newValue; } else { currentObject = currentObject[fieldPiece]; } } } return !valuesAreSame; }; ValueService.prototype.executeValueGetter = function (filterValueGetter, data, column, rowNode) { var colId = column.getId(); // if inside the same turn, just return back the value we got last time var valueFromCache = this.valueCache.getValue(rowNode, colId); if (valueFromCache !== undefined) { return valueFromCache; } var params = { data: data, node: rowNode, column: column, colDef: column.getColDef(), api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi(), context: this.gridOptionsWrapper.getContext(), getValue: this.getValueCallback.bind(this, rowNode) }; var result = this.expressionService.evaluate(filterValueGetter, params); // if a turn is active, store the value in case the grid asks for it again this.valueCache.setValue(rowNode, colId, result); return result; }; ValueService.prototype.getValueCallback = function (node, field) { var otherColumn = this.columnController.getPrimaryColumn(field); if (otherColumn) { return this.getValue(otherColumn, node); } else { return null; } }; // used by row grouping and pivot, to get key for a row. col can be a pivot col or a row grouping col ValueService.prototype.getKeyForNode = function (col, rowNode) { var value = this.getValue(col, rowNode); var result; var keyCreator = col.getColDef().keyCreator; if (keyCreator) { result = keyCreator({ value: value }); } else { result = value; } // if already a string, or missing, just return it if (typeof result === 'string' || result === null || result === undefined) { return result; } result = String(result); if (result === '[object Object]') { utils_1._.doOnce(function () { console.warn('ag-Grid: a column you are grouping or pivoting by has objects as values. If you want to group by complex objects then either a) use a colDef.keyCreator (se ag-Grid docs) or b) to toString() on the object to return a key'); }, 'getKeyForNode - warn about [object,object]'); } return result; }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], ValueService.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('expressionService'), __metadata("design:type", expressionService_1.ExpressionService) ], ValueService.prototype, "expressionService", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], ValueService.prototype, "columnController", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], ValueService.prototype, "eventService", void 0); __decorate([ context_1.Autowired('valueCache'), __metadata("design:type", valueCache_1.ValueCache) ], ValueService.prototype, "valueCache", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], ValueService.prototype, "init", null); ValueService = __decorate([ context_1.Bean('valueService') ], ValueService); return ValueService; }()); exports.ValueService = ValueService;
sufuf3/cdnjs
ajax/libs/ag-grid/20.0.0/lib/valueService/valueService.js
JavaScript
mit
12,729
// @flow import * as React from "react"; import { withPhenomicApi, query, BodyRenderer, } from "@phenomic/preset-react-app/lib/client"; import pkg from "../package.json"; import Layout from "./Layout"; import PageError from "./PageError"; import ActivityIndicator from "./ActivityIndicator"; import LatestPosts from "./LatestPosts"; const Page = ({ hasError, isLoading, page, posts }) => hasError ? ( <PageError error={page.error} /> ) : ( <React.Fragment> <style dangerouslySetInnerHTML={{ __html: ` .Page { position: relative; } .Page-content { margin-bottom: 40px; } `, }} /> <Layout title={(page && page.node && page.node.title) || pkg.title} image={page && page.node && page.node.image} > {isLoading && <ActivityIndicator />} {!isLoading && ( <React.Fragment> <div className="Page-content"> {page && page.node && page.node.body && <BodyRenderer>{page.node.body}</BodyRenderer>} </div> <hr /> <LatestPosts node={posts.node} error={posts.error} /> </React.Fragment> )} </Layout> </React.Fragment> ); export default withPhenomicApi(Page, props => ({ page: query({ path: "content/pages", id: props.params.splat || "", }), posts: query({ path: "content/posts", limit: 4, after: props.params.after, }), }));
MoOx/statinamic
examples/react-app-blog/src/Page.js
JavaScript
mit
1,535
var fast = require('../'), underscore = require('underscore'), lodash = require('lodash'), history = require('../test/history'), utils = require('./utils'); var fns = utils.fns('last', 'item', 'return last * item + Math.random()'); var input = [1,2,3,4,5,6,7,8,9,10]; exports['Array::reduce()'] = function () { return input.reduce(fns(), 0); }; exports['fast.reduce()'] = function () { return fast.reduce(input, fns(), 0); }; exports['fast.reduce() v0.0.2c'] = function () { return history.reduce_0_0_2c(input, fns(), 0); }; exports['fast.reduce() v0.0.2b'] = function () { return history.reduce_0_0_2b(input, fns(), 0); }; exports['fast.reduce() v0.0.2a'] = function () { return history.reduce_0_0_2a(input, fns(), 0); }; exports['fast.reduce() v0.0.1'] = function () { return history.reduce_0_0_1(input, fns(), 0); }; exports['fast.reduce() v0.0.0'] = function () { return history.reduce_0_0_0(input, fns(), 0); }; exports['underscore.reduce()'] = function () { return underscore.reduce(input, fns(), 0) }; exports['lodash.reduce()'] = function () { return lodash.reduce(input, fns(), 0) };
codemix/fast.js
bench/reduce-10.js
JavaScript
mit
1,140
import"redux";import"./turn-order-8cc4909b.js";import"immer";import"./plugin-random-087f861e.js";import"lodash.isplainobject";import"./reducer-9b2fe64d.js";import"rfc6902";import"./initialize-cd2104ba.js";import"./transport-ce07b771.js";import"./util-89055384.js";export{L as Local,S as SocketIO}from"./socketio-80abb602.js";import"./master-04a42192.js";import"./filter-player-view-43ed49b0.js";import"socket.io-client";
cdnjs/cdnjs
ajax/libs/boardgame-io/0.50.0-alpha.2/esm/multiplayer.min.js
JavaScript
mit
420
/* * @name 슬라이더 * @description 로컬 프로젝트에서 이 예제를 실행하려면, * <a href="http://p5js.org/reference/#/libraries/p5.dom">p5.dom 라이브러리</a> * 를 추가하면 됩니다.<br><br> * 슬라이더를 움직여 배경색의 R,G,B값을 조정해보세요. */ let rSlider, gSlider, bSlider; function setup() { // 캔버스 생성하기 createCanvas(710, 400); textSize(15); noStroke(); // 슬라이더 생성하기 rSlider = createSlider(0, 255, 100); rSlider.position(20, 20); gSlider = createSlider(0, 255, 0); gSlider.position(20, 50); bSlider = createSlider(0, 255, 255); bSlider.position(20, 80); } function draw() { const r = rSlider.value(); const g = gSlider.value(); const b = bSlider.value(); background(r, g, b); text('red', rSlider.x * 2 + rSlider.width, 35); text('green', gSlider.x * 2 + gSlider.width, 65); text('blue', bSlider.x * 2 + bSlider.width, 95); }
processing/p5.js-website
src/data/examples/ko/16_Dom/04_Slider.js
JavaScript
mit
953
var Marionette = require('backbone.marionette'); var constants = require('utils/constants'); var attachFastClick = require('fastclick'); // View Behaviors require('../behaviors/Navigator'); module.exports = Marionette.ItemView.extend({ el: 'body', events: { 'keyup': 'keyup' }, behaviors: { Navigator: {} }, initialize: function() { // Javascript is ready... go! this.$el.removeClass(constants.INITING_CLASS); // No click delay for iOS attachFastClick(document.body); // Force touch devices to respect :active styles in CSS document.addEventListener('touchstart', function() {}, true); // Page visibility detection this.listenForPageVisibility(); }, listenForPageVisibility: function() { var hidden, visibilityChange; if (typeof document.hidden !== 'undefined') { hidden = 'hidden'; visibilityChange = 'visibilitychange'; } else if (typeof document.mozHidden !== 'undefined') { hidden = 'mozHidden'; visibilityChange = 'mozvisibilitychange'; } else if (typeof document.msHidden !== 'undefined') { hidden = 'msHidden'; visibilityChange = 'msvisibilitychange'; } else if (typeof document.webkitHidden !== 'undefined') { hidden = 'webkitHidden'; visibilityChange = 'webkitvisibilitychange'; } function handleVisibilityChange() { // channels.globalChannel.trigger('app:visibility', !document[hidden]); } if (visibilityChange && typeof document.addEventListener !== 'undefined') { document.addEventListener(visibilityChange, handleVisibilityChange, false); } } });
remydragyn/remy-dragyn-portfolio
src/javascript/app/views/GlobalView.js
JavaScript
mit
1,794
export default "hi";
tivac/modular-css
packages/rollup/test/specimens/stripped-dynamic-imports/b.js
JavaScript
mit
21
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var CONSTANTS={q_dpr1:75,q_dpr2:50,q_dpr3:35,q_dpr4:23,q_dpr5:20},_default=CONSTANTS;exports.default=_default;
cdnjs/cdnjs
ajax/libs/react-imgix/8.6.3/constants.min.js
JavaScript
mit
201
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'htmlwriter', { init: function( editor ) { var writer = new CKEDITOR.htmlWriter(); writer.forceSimpleAmpersand = editor.config.forceSimpleAmpersand; writer.indentationChars = editor.config.dataIndentationChars || '\t'; // Overwrite default basicWriter initialized in hmtlDataProcessor constructor. editor.dataProcessor.writer = writer; } } ); /** * The class used to write HTML data. * * var writer = new CKEDITOR.htmlWriter(); * writer.openTag( 'p' ); * writer.attribute( 'class', 'MyClass' ); * writer.openTagClose( 'p' ); * writer.text( 'Hello' ); * writer.closeTag( 'p' ); * alert( writer.getHtml() ); // '<p class="MyClass">Hello</p>' * * @class * @extends CKEDITOR.htmlParser.basicWriter */ CKEDITOR.htmlWriter = CKEDITOR.tools.createClass( { base: CKEDITOR.htmlParser.basicWriter, /** * Creates an `htmlWriter` class instance. * * @constructor */ $: function() { // Call the base contructor. this.base(); /** * The characters to be used for each indentation step. * * // Use tab for indentation. * editorInstance.dataProcessor.writer.indentationChars = '\t'; */ this.indentationChars = '\t'; /** * The characters to be used to close "self-closing" elements, like `<br>` or `<img>`. * * // Use HTML4 notation for self-closing elements. * editorInstance.dataProcessor.writer.selfClosingEnd = '>'; */ this.selfClosingEnd = ' />'; /** * The characters to be used for line breaks. * * // Use CRLF for line breaks. * editorInstance.dataProcessor.writer.lineBreakChars = '\r\n'; */ this.lineBreakChars = '\n'; this.sortAttributes = 1; this._.indent = 0; this._.indentation = ''; // Indicate preformatted block context status. (#5789) this._.inPre = 0; this._.rules = {}; var dtd = CKEDITOR.dtd; for ( var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent ) ) { this.setRules( e, { indent: !dtd[ e ][ '#' ], breakBeforeOpen: 1, breakBeforeClose: !dtd[ e ][ '#' ], breakAfterClose: 1, needsSpace: ( e in dtd.$block ) && !( e in { li: 1, dt: 1, dd: 1 } ) } ); } this.setRules( 'br', { breakAfterOpen: 1 } ); this.setRules( 'title', { indent: 0, breakAfterOpen: 0 } ); this.setRules( 'style', { indent: 0, breakBeforeClose: 1 } ); this.setRules( 'pre', { breakAfterOpen: 1, // Keep line break after the opening tag indent: 0 // Disable indentation on <pre>. } ); }, proto: { /** * Writes the tag opening part for an opener tag. * * // Writes '<p'. * writer.openTag( 'p', { class : 'MyClass', id : 'MyId' } ); * * @param {String} tagName The element name for this tag. * @param {Object} attributes The attributes defined for this tag. The * attributes could be used to inspect the tag. */ openTag: function( tagName ) { var rules = this._.rules[ tagName ]; if ( this._.afterCloser && rules && rules.needsSpace && this._.needsSpace ) this._.output.push( '\n' ); if ( this._.indent ) this.indentation(); // Do not break if indenting. else if ( rules && rules.breakBeforeOpen ) { this.lineBreak(); this.indentation(); } this._.output.push( '<', tagName ); this._.afterCloser = 0; }, /** * Writes the tag closing part for an opener tag. * * // Writes '>'. * writer.openTagClose( 'p', false ); * * // Writes ' />'. * writer.openTagClose( 'br', true ); * * @param {String} tagName The element name for this tag. * @param {Boolean} isSelfClose Indicates that this is a self-closing tag, * like `<br>` or `<img>`. */ openTagClose: function( tagName, isSelfClose ) { var rules = this._.rules[ tagName ]; if ( isSelfClose ) { this._.output.push( this.selfClosingEnd ); if ( rules && rules.breakAfterClose ) this._.needsSpace = rules.needsSpace; } else { this._.output.push( '>' ); if ( rules && rules.indent ) this._.indentation += this.indentationChars; } if ( rules && rules.breakAfterOpen ) this.lineBreak(); tagName == 'pre' && ( this._.inPre = 1 ); }, /** * Writes an attribute. This function should be called after opening the * tag with {@link #openTagClose}. * * // Writes ' class="MyClass"'. * writer.attribute( 'class', 'MyClass' ); * * @param {String} attName The attribute name. * @param {String} attValue The attribute value. */ attribute: function( attName, attValue ) { if ( typeof attValue == 'string' ) { this.forceSimpleAmpersand && ( attValue = attValue.replace( /&amp;/g, '&' ) ); // Browsers don't always escape special character in attribute values. (#4683, #4719). attValue = CKEDITOR.tools.htmlEncodeAttr( attValue ); } this._.output.push( ' ', attName, '="', attValue, '"' ); }, /** * Writes a closer tag. * * // Writes '</p>'. * writer.closeTag( 'p' ); * * @param {String} tagName The element name for this tag. */ closeTag: function( tagName ) { var rules = this._.rules[ tagName ]; if ( rules && rules.indent ) this._.indentation = this._.indentation.substr( this.indentationChars.length ); if ( this._.indent ) this.indentation(); // Do not break if indenting. else if ( rules && rules.breakBeforeClose ) { this.lineBreak(); this.indentation(); } this._.output.push( '</', tagName, '>' ); tagName == 'pre' && ( this._.inPre = 0 ); if ( rules && rules.breakAfterClose ) { this.lineBreak(); this._.needsSpace = rules.needsSpace; } this._.afterCloser = 1; }, /** * Writes text. * * // Writes 'Hello Word'. * writer.text( 'Hello Word' ); * * @param {String} text The text value */ text: function( text ) { if ( this._.indent ) { this.indentation(); !this._.inPre && ( text = CKEDITOR.tools.ltrim( text ) ); } this._.output.push( text ); }, /** * Writes a comment. * * // Writes "<!-- My comment -->". * writer.comment( ' My comment ' ); * * @param {String} comment The comment text. */ comment: function( comment ) { if ( this._.indent ) this.indentation(); this._.output.push( '<!--', comment, '-->' ); }, /** * Writes a line break. It uses the {@link #lineBreakChars} property for it. * * // Writes '\n' (e.g.). * writer.lineBreak(); */ lineBreak: function() { if ( !this._.inPre && this._.output.length > 0 ) this._.output.push( this.lineBreakChars ); this._.indent = 1; }, /** * Writes the current indentation character. It uses the {@link #indentationChars} * property, repeating it for the current indentation steps. * * // Writes '\t' (e.g.). * writer.indentation(); */ indentation: function() { if ( !this._.inPre && this._.indentation ) this._.output.push( this._.indentation ); this._.indent = 0; }, /** * Empties the current output buffer. It also brings back the default * values of the writer flags. * * writer.reset(); */ reset: function() { this._.output = []; this._.indent = 0; this._.indentation = ''; this._.afterCloser = 0; this._.inPre = 0; this._.needsSpace = 0; }, /** * Sets formatting rules for a given element. Possible rules are: * * * `indent` &ndash; indent the element content. * * `breakBeforeOpen` &ndash; break line before the opener tag for this element. * * `breakAfterOpen` &ndash; break line after the opener tag for this element. * * `breakBeforeClose` &ndash; break line before the closer tag for this element. * * `breakAfterClose` &ndash; break line after the closer tag for this element. * * All rules default to `false`. Each function call overrides rules that are * already present, leaving the undefined ones untouched. * * By default, all elements available in the {@link CKEDITOR.dtd#$block}, * {@link CKEDITOR.dtd#$listItem}, and {@link CKEDITOR.dtd#$tableContent} * lists have all the above rules set to `true`. Additionaly, the `<br>` * element has the `breakAfterOpen` rule set to `true`. * * // Break line before and after "img" tags. * writer.setRules( 'img', { * breakBeforeOpen: true * breakAfterOpen: true * } ); * * // Reset the rules for the "h1" tag. * writer.setRules( 'h1', {} ); * * @param {String} tagName The name of the element for which the rules are set. * @param {Object} rules An object containing the element rules. */ setRules: function( tagName, rules ) { var currentRules = this._.rules[ tagName ]; if ( currentRules ) CKEDITOR.tools.extend( currentRules, rules, true ); else this._.rules[ tagName ] = rules; } } } ); /** * Whether to force using `'&'` instead of `'&amp;'` in element attributes * values. It is not recommended to change this setting for compliance with the * W3C XHTML 1.0 standards ([C.12, XHTML 1.0](http://www.w3.org/TR/xhtml1/#C_12)). * * // Use `'&'` instead of `'&amp;'` * CKEDITOR.config.forceSimpleAmpersand = true; * * @cfg {Boolean} [forceSimpleAmpersand=false] * @member CKEDITOR.config */ /** * The characters to be used for indenting HTML output produced by the editor. * Using characters different from `' '` (space) and `'\t'` (tab) is not recommended * as it will mess the code. * * // No indentation. * CKEDITOR.config.dataIndentationChars = ''; * * // Use two spaces for indentation. * CKEDITOR.config.dataIndentationChars = ' '; * * @cfg {String} [dataIndentationChars='\t'] * @member CKEDITOR.config */
SeeyaSia/www
web/libraries/ckeditor/plugins/htmlwriter/plugin.js
JavaScript
gpl-2.0
9,840
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is httpd.js code. * * The Initial Developer of the Original Code is * Jeff Walden <jwalden+code@mit.edu>. * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // exercise nsIHttpResponse.setStatusLine, ensure its atomicity, and ensure the // specified behavior occurs if it's not called var srv; function run_test() { srv = createServer(); srv.registerPathHandler("/no/setstatusline", noSetstatusline); srv.registerPathHandler("/http1_0", http1_0); srv.registerPathHandler("/http1_1", http1_1); srv.registerPathHandler("/invalidVersion", invalidVersion); srv.registerPathHandler("/invalidStatus", invalidStatus); srv.registerPathHandler("/invalidDescription", invalidDescription); srv.registerPathHandler("/crazyCode", crazyCode); srv.registerPathHandler("/nullVersion", nullVersion); srv.start(4444); runHttpTests(tests, testComplete(srv)); } /************* * UTILITIES * *************/ function checkStatusLine(channel, httpMaxVer, httpMinVer, httpCode, statusText) { do_check_eq(channel.responseStatus, httpCode); do_check_eq(channel.responseStatusText, statusText); var respMaj = {}, respMin = {}; channel.getResponseVersion(respMaj, respMin); do_check_eq(respMaj.value, httpMaxVer); do_check_eq(respMin.value, httpMinVer); } /********* * TESTS * *********/ var tests = []; var test; // /no/setstatusline function noSetstatusline(metadata, response) { } test = new Test("http://localhost:4444/no/setstatusline", null, startNoSetStatusLine, stop); tests.push(test); function startNoSetStatusLine(ch, cx) { checkStatusLine(ch, 1, 1, 200, "OK"); } function stop(ch, cx, status, data) { do_check_true(Components.isSuccessCode(status)); } // /http1_0 function http1_0(metadata, response) { response.setStatusLine("1.0", 200, "OK"); } test = new Test("http://localhost:4444/http1_0", null, startHttp1_0, stop); tests.push(test); function startHttp1_0(ch, cx) { checkStatusLine(ch, 1, 0, 200, "OK"); } // /http1_1 function http1_1(metadata, response) { response.setStatusLine("1.1", 200, "OK"); } test = new Test("http://localhost:4444/http1_1", null, startHttp1_1, stop); tests.push(test); function startHttp1_1(ch, cx) { checkStatusLine(ch, 1, 1, 200, "OK"); } // /invalidVersion function invalidVersion(metadata, response) { try { response.setStatusLine(" 1.0", 200, "FAILED"); } catch (e) { response.setHeader("Passed", "true", false); } } test = new Test("http://localhost:4444/invalidVersion", null, startPassedTrue, stop); tests.push(test); function startPassedTrue(ch, cx) { checkStatusLine(ch, 1, 1, 200, "OK"); do_check_eq(ch.getResponseHeader("Passed"), "true"); } // /invalidStatus function invalidStatus(metadata, response) { try { response.setStatusLine("1.0", 1000, "FAILED"); } catch (e) { response.setHeader("Passed", "true", false); } } test = new Test("http://localhost:4444/invalidStatus", null, startPassedTrue, stop); tests.push(test); // /invalidDescription function invalidDescription(metadata, response) { try { response.setStatusLine("1.0", 200, "FAILED\x01"); } catch (e) { response.setHeader("Passed", "true", false); } } test = new Test("http://localhost:4444/invalidDescription", null, startPassedTrue, stop); tests.push(test); // /crazyCode function crazyCode(metadata, response) { response.setStatusLine("1.1", 617, "Crazy"); } test = new Test("http://localhost:4444/crazyCode", null, startCrazy, stop); tests.push(test); function startCrazy(ch, cx) { checkStatusLine(ch, 1, 1, 617, "Crazy"); } // /nullVersion function nullVersion(metadata, response) { response.setStatusLine(null, 255, "NULL"); } test = new Test("http://localhost:4444/nullVersion", null, startNullVersion, stop); tests.push(test); function startNullVersion(ch, cx) { // currently, this server implementation defaults to 1.1 checkStatusLine(ch, 1, 1, 255, "NULL"); }
freaktechnik/nightingale-hacking
dependencies/vendor/mozjshttpd/test/test_setstatusline.js
JavaScript
gpl-2.0
5,696
var usuariosData = require('./data/usuariosData.js') var sesiones = []; module.exports.seguridad = function (app) { app.use('/api/priv/', function (req, res, next) { var sessionId = req.get('sessionId'); var sesion = getSesion(sessionId); if (sesion) { if (esSesionValida(sesion)) { sesion.timeStamp = new Date(); req.usuario = sesion.email; next(); } else { console.log('Sesión caducada:' + JSON.stringify(sesion)); res.status(419).send('Sesión caducada'); } } else { res.status(401).send('Credencial inválida'); } }); // API - REST // SECURITY app.route('/api/usuarios') .post(function (req, res, next) { var usuario = req.body; usuariosData.findingByEmail(usuario.email) .then(function (data) { if (data[0]) { console.log('email ya registrado:' + usuario.email); res.status(409).send('email ' + usuario.email + ' ya registrado'); } else { console.log('registrando:' + usuario.email); usuariosData.inserting(usuario) .then(function (data) { res.json(newSession(usuario.email)); }); }; }) .fail(function (err) { res.status(500).send(err); }); }); app.route('/api/sesiones') .post(function (req, res, next) { var usuario = req.body; usuariosData.findingByEmailPassword(usuario.email, usuario.password) .then(function (data) { if (data) { console.log('aceptado:' + usuario.email); res.json(newSession(usuario.email)); } else { console.log('Credencial inválida:' + usuario.email); res.status(401).send('Credencial inválida'); } }) .fail(function (err) { res.status(500).send(err); }); }); function getSesion(sessionId) { return sesiones.filter(function (s) { return s.sessionId == sessionId; })[0] } function esSesionValida(sesion) { return (new Date() - sesion.timeStamp) < 20 * 60 * 1000; } function newSession(email) { var sessionId = Math.random() * (88888) + 11111; var timeStamp = new Date(); sesiones.push({ sessionId: sessionId, email: email, timeStamp: timeStamp }); return sessionId; } }
EscuelaIt/Curso-angularjs-FS-2015
25-socket-io/server/seguridad.js
JavaScript
gpl-2.0
2,152
/* *=BEGIN SONGBIRD GPL * * This file is part of the Songbird web player. * * Copyright(c) 2005-2009 POTI, Inc. * http://www.songbirdnest.com * * This file may be licensed under the terms of of the * GNU General Public License Version 2 (the ``GPL''). * * Software distributed under the License is distributed * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the GPL for the specific language * governing rights and limitations. * * You should have received a copy of the GPL along with this * program. If not, go to http://www.gnu.org/licenses/gpl.html * or write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * *=END SONGBIRD GPL */ /** * \brief test the directory service provider */ function runTest() { var dirService = Cc["@mozilla.org/file/directory_service;1"] .getService(Ci.nsIProperties); var dirProvider = Cc["@songbirdnest.com/moz/directory/provider;1"] .getService(Ci.nsIDirectoryServiceProvider); // Test that our directory service provider returns valid directories // in all cases - both directly and through directory service. var testDirs = ["CmDocs", "CmPics", "CmMusic", "CmVideo", "CmPics", "Docs", "Pics", "Music", "Video", "DiscBurning"]; for each (let dir in testDirs) { // We cannot know whether the result is correct but test at least that // it is a directory. let file1 = dirService.get(dir, Ci.nsIFile); assertTrue(file1, "Non-null file returned by directory service"); assertTrue(file1.exists(), "Existing file returned"); assertTrue(file1.isDirectory(), "Directory returned"); // Make sure that directory service uses our provider to resolve the // directories (or at least produces identical results) let file2 = dirProvider.getFile(dir, {}); assertTrue(file2, "Non-null file returned by directory provider"); assertTrue(file2.equals(file1), "Our provider returns the same file as directory service"); } let hadException = false; try { dirProvider.getFile("FooBarDummy", {}); } catch (e) { hadException = true; } assertTrue(hadException, "Exception thrown when trying to request unknown file"); }
freaktechnik/nightingale-hacking
components/moz/dirprovider/test/test_dirprovider.js
JavaScript
gpl-2.0
2,436
/* Highcharts JS v9.3.2 (2021-11-29) Solid angular gauge module (c) 2010-2021 Torstein Honsi License: www.highcharts.com/license */ 'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/solid-gauge",["highcharts","highcharts/highcharts-more"],function(f){a(f);a.Highcharts=f;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function f(a,k,l,c){a.hasOwnProperty(k)||(a[k]=c.apply(null,l))}a=a?a._modules:{};f(a,"Core/Axis/SolidGaugeAxis.js",[a["Core/Color/Color.js"],a["Core/Utilities.js"]],function(a, k){var l=a.parse,c=k.extend,e=k.merge,m;(function(a){var b={initDataClasses:function(a){var c=this.chart,n,p=0,g=this.options;this.dataClasses=n=[];a.dataClasses.forEach(function(b,d){b=e(b);n.push(b);b.color||("category"===g.dataClassColor?(d=c.options.colors,b.color=d[p++],p===d.length&&(p=0)):b.color=l(g.minColor).tweenTo(l(g.maxColor),d/(a.dataClasses.length-1)))})},initStops:function(a){this.stops=a.stops||[[0,this.options.minColor],[1,this.options.maxColor]];this.stops.forEach(function(a){a.color= l(a[1])})},toColor:function(a,c){var b=this.stops,l=this.dataClasses,g;if(l)for(g=l.length;g--;){var e=l[g];var d=e.from;b=e.to;if(("undefined"===typeof d||a>=d)&&("undefined"===typeof b||a<=b)){var k=e.color;c&&(c.dataClass=g);break}}else{this.logarithmic&&(a=this.val2lin(a));a=1-(this.max-a)/(this.max-this.min);for(g=b.length;g--&&!(a>b[g][0]););d=b[g]||b[g+1];b=b[g+1]||d;a=1-(b[0]-a)/(b[0]-d[0]||1);k=d.color.tweenTo(b.color,a)}return k}};a.init=function(a){c(a,b)}})(m||(m={}));return m});f(a,"Series/SolidGauge/SolidGaugeComposition.js", [a["Core/Renderer/SVG/SVGRenderer.js"]],function(a){a=a.prototype;var k=a.symbols.arc;a.symbols.arc=function(a,c,e,m,b){a=k(a,c,e,m,b);b&&b.rounded&&(e=((b.r||e)-(b.innerR||0))/2,c=a[0],b=a[2],"M"===c[0]&&"L"===b[0]&&(c=["A",e,e,0,1,1,c[1],c[2]],a[2]=["A",e,e,0,1,1,b[1],b[2]],a[4]=c));return a}});f(a,"Series/SolidGauge/SolidGaugeSeries.js",[a["Core/Legend/LegendSymbol.js"],a["Core/Series/SeriesRegistry.js"],a["Core/Axis/SolidGaugeAxis.js"],a["Core/Utilities.js"]],function(a,k,l,c){var e=this&&this.__extends|| function(){var a=function(b,h){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,b){a.__proto__=b}||function(a,b){for(var h in b)b.hasOwnProperty(h)&&(a[h]=b[h])};return a(b,h)};return function(b,h){function c(){this.constructor=b}a(b,h);b.prototype=null===h?Object.create(h):(c.prototype=h.prototype,new c)}}(),m=k.seriesTypes,b=m.gauge,f=m.pie.prototype,p=c.clamp,u=c.extend,n=c.isNumber,w=c.merge,g=c.pick,v=c.pInt,d={colorByPoint:!0,dataLabels:{y:0}};c=function(a){function c(){var b= null!==a&&a.apply(this,arguments)||this;b.data=void 0;b.points=void 0;b.options=void 0;b.axis=void 0;b.yAxis=void 0;b.startAngleRad=void 0;b.thresholdAngleRad=void 0;return b}e(c,a);c.prototype.translate=function(){var a=this.yAxis;l.init(a);!a.dataClasses&&a.options.dataClasses&&a.initDataClasses(a.options);a.initStops(a.options);b.prototype.translate.call(this)};c.prototype.drawPoints=function(){var a=this,b=a.yAxis,c=b.center,e=a.options,k=a.chart.renderer,d=e.overshoot,l=n(d)?d/180*Math.PI:0, f;n(e.threshold)&&(f=b.startAngleRad+b.translate(e.threshold,null,null,null,!0));this.thresholdAngleRad=g(f,b.startAngleRad);a.points.forEach(function(d){if(!d.isNull){var h=d.graphic,f=b.startAngleRad+b.translate(d.y,null,null,null,!0),m=v(g(d.options.radius,e.radius,100))*c[2]/200,q=v(g(d.options.innerRadius,e.innerRadius,60))*c[2]/200,r=b.toColor(d.y,d),t=Math.min(b.startAngleRad,b.endAngleRad),n=Math.max(b.startAngleRad,b.endAngleRad);"none"===r&&(r=d.color||a.color||"none");"none"!==r&&(d.color= r);f=p(f,t-l,n+l);!1===e.wrap&&(f=p(f,t,n));t=Math.min(f,a.thresholdAngleRad);f=Math.max(f,a.thresholdAngleRad);f-t>2*Math.PI&&(f=t+2*Math.PI);d.shapeArgs=q={x:c[0],y:c[1],r:m,innerR:q,start:t,end:f,rounded:e.rounded};d.startR=m;h?(m=q.d,h.animate(u({fill:r},q)),m&&(q.d=m)):d.graphic=h=k.arc(q).attr({fill:r,"sweep-flag":0}).add(a.group);a.chart.styledMode||("square"!==e.linecap&&h.attr({"stroke-linecap":"round","stroke-linejoin":"round"}),h.attr({stroke:e.borderColor||"none","stroke-width":e.borderWidth|| 0}));h&&h.addClass(d.getClassName(),!0)}})};c.prototype.animate=function(a){a||(this.startAngleRad=this.thresholdAngleRad,f.animate.call(this,a))};c.defaultOptions=w(b.defaultOptions,d);return c}(b);u(c.prototype,{drawLegendSymbol:a.drawRectangle});k.registerSeriesType("solidgauge",c);"";return c});f(a,"masters/modules/solid-gauge.src.js",[],function(){})}); //# sourceMappingURL=solid-gauge.js.map
OHSU-FM/reindeer
vendor/assets/javascripts/highcharts/modules/solid-gauge.js
JavaScript
gpl-2.0
4,647
var webpack = require('webpack'); var path = require('path'); // workaround for old node version shipping w/ ubuntu var es6_promise = require('es6-promise').polyfill() var BUILD_DIR = path.resolve(__dirname, 'dist'); var APP_DIR = path.resolve(__dirname, 'src'); var config = { entry: { entry: APP_DIR + '/index.jsx', vendor: ['react', 'react-dom', 'jquery', 'react-bootstrap'] }, output: { path: BUILD_DIR, filename: 'bundle.js' }, module : { loaders : [ { test : /\.jsx?/, include : APP_DIR, loader : 'babel', query: { presets: ['es2015', 'react'] } }, { test : /\.css?/, loader : 'style-loader!css-loader' }, { test: /\.png$/, loader: "url-loader?limit=100000" }, { test: /\.jpg$/, loader: "file-loader" }, { test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml' } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js") ] }; module.exports = config;
flathat/IS4C
fannie/modules/plugins2.0/MobileLane/webpack.config.js
JavaScript
gpl-2.0
1,480