code
stringlengths
2
1.05M
/** * @fileoverview client模式,serve时js文件处理 * @author liweitao */ 'use strict'; module.exports = function ($, appConf, moduleConf, args) { return function (mod, modulePath, appPath) { return new Promise(function (resolve, reject) { var vfs = require('vinyl-fs'); var path = require('path'); var athenaMate = require('../athena_mate'); var useBabel = moduleConf.support.useBabel || { enable: false }; var enableBabel = useBabel.enable; var jsxPragma = useBabel.jsxPragma || 'Nerv.createElement' athenaMate.concat({ cwd: appPath, pageFiles: args.pageFiles, module: moduleConf.module, map: path.join('dist', 'map.json'), dest: 'dist', end: function () { vfs.src(path.join(modulePath, 'dist', '_static', 'js', '**', '*.js')) .pipe($.if(enableBabel, athenaMate.babel({ config: { presets: [ require('babel-preset-es2015'), require('babel-preset-stage-0') ], plugins: [ require('babel-plugin-transform-es3-member-expression-literals'), require('babel-plugin-transform-es3-property-literals'), [require('babel-plugin-transform-react-jsx'), { pragma: jsxPragma }] ] }, fileTest: useBabel.test || /\.js/, exclude: useBabel.exclude || [] }))) .pipe(athenaMate.replace({ cwd: appPath, module: moduleConf.module, serve: true })) .pipe(vfs.dest(path.join(appPath, '.temp', appConf.app, moduleConf.module, 'js'))) .on('end', function () { resolve(); }) .on('error', function (err) { reject(err); }); } }); }); }; };
/* * Routes handlers */ var exec = require('child_process').exec, child_process = require('child_process'), fs = require('fs'), child_processes = []; // Basic routing module.exports = function(app) { app.get("/", getHomePage); app.post("/add", postAddScraper); } function getHomePage(req, res) { var port = res.app.settings.config.server.port; res.render('index', { port: port }); } function postAddScraper(req, res) { var url = req.body.url, auth_user = req.body.auth_user, auth_pass = req.body.auth_pass, depth = parseInt(req.body.create_crawler_depth), create_sitemap = req.body.create_crawler_sitemap == 1, clean = req.body.clean_crawl == 1, config = res.app.settings.config; var child = child_process.fork("crawling-daemon.js"); // setup config child.send({ action: "setConfig", config: config }); if (auth_user!="" && auth_pass!="") { child.send({ action: "setAuth", auth_user: auth_user, auth_pass: auth_pass }); } child.send({ action: "start", url: url, clean: clean, depth: depth }); child.on("message", function(data) { switch (data.message) { case "auth-required": data.row_id = data.host.replace(/\./g,""); res.render("partials/scraper-stats-row", {data: data, layout: false}, function(err, html) { if (err != null) { return; } data.html = html; io.sockets.emit('auth-required', data); }); break; case "general-stats": data.row_id = data.host.replace(/\./g,""); res.render("partials/scraper-stats-row", {data: data, layout: false}, function(err, html) { if (err != null) { return; } data.html = html; io.sockets.emit('general-stats', data); }); break; case "done-crawling": case "stop-crawling": if (create_sitemap) { child.send({ action: "createSitemap" }); } else { child.kill(); // Terminate crawling daemon } io.sockets.emit(data.message, data); // done-crawling | stop-crawling break; // @TODO: Implement case "recrawl": break; case "sitemap-created": var sitemap_path = "public/sitemaps/"; fs.exists(sitemap_path, function(exists) { if (!exists) { fs.mkdir(sitemap_path, writeSitemap); } else { writeSitemap(); } // Terminate crawling daemon child.kill(); }); function writeSitemap() { sitemap_path += "sitemap_"+ data.host +".xml"; fs.writeFile(sitemap_path, data.content, function(err) { if(err) { console.log(err); } else { io.sockets.emit('sitemap-ready', { host: data.host, path: sitemap_path.replace("public/", "") }) } }); } break; default: io.sockets.emit(data.message, data); break; } }) res.redirect("/"); }
MSG.title = "Webduino Blockly 課程 1-3:控制兩顆 LED 燈"; MSG.subTitle = "課程 1-3:控制兩顆 LED 燈"; MSG.demoDescription = "點選下圖左右兩顆燈泡,分別控制兩顆 LED 的開或關";
/*global require*/ require({ baseUrl : '.', paths : { domReady : '../../ThirdParty/requirejs-2.1.20/domReady', Cesium : '../../Source' } }, [ 'CesiumViewer' ], function() { });
import requestAnimationFrame from 'requestanimationframe' import { DistributeHeight } from './DistributeHeight' export class Resize { constructor () { this.ticking = false // Create an instance of DistributeHeight for each element $('[data-distribute-height]').each((index, element) => { element.distributeHeight = new DistributeHeight($(element)) }) this.calculate = () => { $('[data-distribute-height]').each((index, element) => { element.distributeHeight.setHeights() }) this.ticking = false } } resize () { $(window).on('load resize', () => { this.tick() }) } tick () { if (!this.ticking) { requestAnimationFrame(this.calculate) this.ticking = true } } }
/*! * froala_editor v3.0.6 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2019 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) : typeof define === 'function' && define.amd ? define(['froala-editor'], factory) : (factory(global.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; /** * Arabic */ FE.LANGUAGE['ar'] = { translation: { // Place holder 'Type something': "\u0627\u0643\u062A\u0628 \u0634\u064A\u0626\u0627", // Basic formatting 'Bold': "\u063A\u0627\u0645\u0642", 'Italic': "\u0645\u0627\u0626\u0644", 'Underline': "\u062A\u0633\u0637\u064A\u0631", 'Strikethrough': "\u064A\u062A\u0648\u0633\u0637 \u062E\u0637", // Main buttons 'Insert': "\u0625\u062F\u0631\u0627\u062C", 'Delete': "\u062D\u0630\u0641", 'Cancel': "\u0625\u0644\u063A\u0627\u0621", 'OK': "\u0645\u0648\u0627\u0641\u0642", 'Back': "\u0638\u0647\u0631", 'Remove': "\u0625\u0632\u0627\u0644\u0629", 'More': "\u0623\u0643\u062B\u0631", 'Update': "\u0627\u0644\u062A\u062D\u062F\u064A\u062B", 'Style': "\u0623\u0633\u0644\u0648\u0628", // Font 'Font Family': "\u0639\u0627\u0626\u0644\u0629 \u0627\u0644\u062E\u0637", 'Font Size': "\u062D\u062C\u0645 \u0627\u0644\u062E\u0637", // Colors 'Colors': "\u0627\u0644\u0623\u0644\u0648\u0627\u0646", 'Background': "\u0627\u0644\u062E\u0644\u0641\u064A\u0629", 'Text': "\u0627\u0644\u0646\u0635", 'HEX Color': 'عرافة اللون', // Paragraphs 'Paragraph Format': "\u062A\u0646\u0633\u064A\u0642 \u0627\u0644\u0641\u0642\u0631\u0629", 'Normal': "\u0637\u0628\u064A\u0639\u064A", 'Code': "\u0643\u0648\u062F", 'Heading 1': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 1", 'Heading 2': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 2", 'Heading 3': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 3", 'Heading 4': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 4", // Style 'Paragraph Style': "\u0646\u0645\u0637 \u0627\u0644\u0641\u0642\u0631\u0629", 'Inline Style': "\u0627\u0644\u0646\u0645\u0637 \u0627\u0644\u0645\u0636\u0645\u0646", // Alignment 'Align': "\u0645\u062D\u0627\u0630\u0627\u0629", 'Align Left': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0646\u0635 \u0644\u0644\u064A\u0633\u0627\u0631", 'Align Center': "\u062A\u0648\u0633\u064A\u0637", 'Align Right': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0646\u0635 \u0644\u0644\u064A\u0645\u064A\u0646", 'Align Justify': "\u0636\u0628\u0637", 'None': "\u0644\u0627 \u0634\u064A\u0621", // Lists 'Ordered List': "\u0642\u0627\u0626\u0645\u0629 \u0645\u0631\u062A\u0628\u0629", 'Default': 'الافتراضي', 'Lower Alpha': 'أقل ألفا', 'Lower Greek': 'أقل اليونانية', 'Lower Roman': 'انخفاض الروماني', 'Upper Alpha': 'العلوي ألفا', 'Upper Roman': 'الروماني العلوي', 'Unordered List': "\u0642\u0627\u0626\u0645\u0629 \u063A\u064A\u0631 \u0645\u0631\u062A\u0628\u0629", 'Circle': 'دائرة', 'Disc': 'القرص', 'Square': 'ميدان', // Line height 'Line Height': 'ارتفاع خط', 'Single': 'غير مرتبطة', 'Double': 'مزدوج', // Indent 'Decrease Indent': "\u0627\u0646\u062E\u0641\u0627\u0636 \u0627\u0644\u0645\u0633\u0627\u0641\u0629 \u0627\u0644\u0628\u0627\u062F\u0626\u0629", 'Increase Indent': "\u0632\u064A\u0627\u062F\u0629 \u0627\u0644\u0645\u0633\u0627\u0641\u0629 \u0627\u0644\u0628\u0627\u062F\u0626\u0629", // Links 'Insert Link': "\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637", 'Open in new tab': "\u0641\u062A\u062D \u0641\u064A \u0639\u0644\u0627\u0645\u0629 \u062A\u0628\u0648\u064A\u0628 \u062C\u062F\u064A\u062F\u0629", 'Open Link': "\u0627\u0641\u062A\u062D \u0627\u0644\u0631\u0627\u0628\u0637", 'Edit Link': "\u0627\u0631\u062A\u0628\u0627\u0637 \u062A\u062D\u0631\u064A\u0631", 'Unlink': "\u062D\u0630\u0641 \u0627\u0644\u0631\u0627\u0628\u0637", 'Choose Link': "\u0627\u062E\u062A\u064A\u0627\u0631 \u0635\u0644\u0629", // Images 'Insert Image': "\u0625\u062F\u0631\u0627\u062C \u0635\u0648\u0631\u0629", 'Upload Image': "\u062A\u062D\u0645\u064A\u0644 \u0635\u0648\u0631\u0629", 'By URL': "\u0628\u0648\u0627\u0633\u0637\u0629 URL", 'Browse': "\u062A\u0635\u0641\u062D", 'Drop image': "\u0625\u0633\u0642\u0627\u0637 \u0635\u0648\u0631\u0629", 'or click': "\u0623\u0648 \u0627\u0646\u0642\u0631 \u0641\u0648\u0642", 'Manage Images': "\u0625\u062F\u0627\u0631\u0629 \u0627\u0644\u0635\u0648\u0631", 'Loading': "\u062A\u062D\u0645\u064A\u0644", 'Deleting': "\u062D\u0630\u0641", 'Tags': "\u0627\u0644\u0643\u0644\u0645\u0627\u062A", 'Are you sure? Image will be deleted.': "\u0647\u0644 \u0623\u0646\u062A \u0645\u062A\u0623\u0643\u062F\u061F \u0633\u064A\u062A\u0645 \u062D\u0630\u0641 \u0627\u0644\u0635\u0648\u0631\u0629.", 'Replace': "\u0627\u0633\u062A\u0628\u062F\u0627\u0644", 'Uploading': "\u062A\u062D\u0645\u064A\u0644", 'Loading image': "\u0635\u0648\u0631\u0629 \u062A\u062D\u0645\u064A\u0644", 'Display': "\u0639\u0631\u0636", 'Inline': "\u0641\u064A \u062E\u0637", 'Break Text': "\u0646\u0635 \u0627\u0633\u062A\u0631\u0627\u062D\u0629", 'Alternative Text': "\u0646\u0635 \u0628\u062F\u064A\u0644", 'Change Size': "\u062A\u063A\u064A\u064A\u0631 \u062D\u062C\u0645", 'Width': "\u0639\u0631\u0636", 'Height': "\u0627\u0631\u062A\u0641\u0627\u0639", 'Something went wrong. Please try again.': ".\u062D\u062F\u062B \u062E\u0637\u0623 \u0645\u0627. \u062D\u0627\u0648\u0644 \u0645\u0631\u0629 \u0627\u062E\u0631\u0649", 'Image Caption': 'تعليق على الصورة', 'Advanced Edit': 'تعديل متقدم', // Video 'Insert Video': "\u0625\u062F\u0631\u0627\u062C \u0641\u064A\u062F\u064A\u0648", 'Embedded Code': "\u0627\u0644\u062A\u0639\u0644\u064A\u0645\u0627\u062A \u0627\u0644\u0628\u0631\u0645\u062C\u064A\u0629 \u0627\u0644\u0645\u0636\u0645\u0646\u0629", 'Paste in a video URL': 'لصق في عنوان ورل للفيديو', 'Drop video': 'انخفاض الفيديو', 'Your browser does not support HTML5 video.': 'متصفحك لا يدعم فيديو HTML5.', 'Upload Video': 'رفع فيديو', // Tables 'Insert Table': "\u0625\u062F\u0631\u0627\u062C \u062C\u062F\u0648\u0644", 'Table Header': "\u0631\u0623\u0633 \u0627\u0644\u062C\u062F\u0648\u0644", 'Remove Table': "\u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u062C\u062F\u0648\u0644", 'Table Style': "\u0646\u0645\u0637 \u0627\u0644\u062C\u062F\u0648\u0644", 'Horizontal Align': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0623\u0641\u0642\u064A\u0629", 'Row': "\u0635\u0641", 'Insert row above': "\u0625\u062F\u0631\u0627\u062C \u0635\u0641 \u0644\u0644\u0623\u0639\u0644\u0649", 'Insert row below': "\u0625\u062F\u0631\u0627\u062C \u0635\u0641 \u0644\u0644\u0623\u0633\u0641\u0644", 'Delete row': "\u062D\u0630\u0641 \u0635\u0641", 'Column': "\u0639\u0645\u0648\u062F", 'Insert column before': "\u0625\u062F\u0631\u0627\u062C \u0639\u0645\u0648\u062F \u0644\u0644\u064A\u0633\u0627\u0631", 'Insert column after': "\u0625\u062F\u0631\u0627\u062C \u0639\u0645\u0648\u062F \u0644\u0644\u064A\u0645\u064A\u0646", 'Delete column': "\u062D\u0630\u0641 \u0639\u0645\u0648\u062F", 'Cell': "\u062E\u0644\u064A\u0629", 'Merge cells': "\u062F\u0645\u062C \u062E\u0644\u0627\u064A\u0627", 'Horizontal split': "\u0627\u0646\u0642\u0633\u0627\u0645 \u0623\u0641\u0642\u064A", 'Vertical split': "\u0627\u0644\u0627\u0646\u0642\u0633\u0627\u0645 \u0627\u0644\u0639\u0645\u0648\u062F\u064A", 'Cell Background': "\u062E\u0644\u0641\u064A\u0629 \u0627\u0644\u062E\u0644\u064A\u0629", 'Vertical Align': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0639\u0645\u0648\u062F\u064A\u0629", 'Top': "\u0623\u0639\u0644\u0649", 'Middle': "\u0648\u0633\u0637", 'Bottom': "\u0623\u0633\u0641\u0644", 'Align Top': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0623\u0639\u0644\u0649", 'Align Middle': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0648\u0633\u0637", 'Align Bottom': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0623\u0633\u0641\u0644", 'Cell Style': "\u0646\u0645\u0637 \u0627\u0644\u062E\u0644\u064A\u0629", // Files 'Upload File': "\u062A\u062D\u0645\u064A\u0644 \u0627\u0644\u0645\u0644\u0641", 'Drop file': "\u0627\u0646\u062E\u0641\u0627\u0636 \u0627\u0644\u0645\u0644\u0641", // Emoticons 'Emoticons': "\u0627\u0644\u0645\u0634\u0627\u0639\u0631", 'Grinning face': "\u064A\u0643\u0634\u0631 \u0648\u062C\u0647\u0647", 'Grinning face with smiling eyes': "\u0645\u0628\u062A\u0633\u0645\u0627 \u0648\u062C\u0647 \u0645\u0639 \u064A\u0628\u062A\u0633\u0645 \u0627\u0644\u0639\u064A\u0646", 'Face with tears of joy': "\u0648\u062C\u0647 \u0645\u0639 \u062F\u0645\u0648\u0639 \u0627\u0644\u0641\u0631\u062D", 'Smiling face with open mouth': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645", 'Smiling face with open mouth and smiling eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u064A\u0646\u064A\u0646 \u064A\u0628\u062A\u0633\u0645", 'Smiling face with open mouth and cold sweat': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u0631\u0642 \u0627\u0644\u0628\u0627\u0631\u062F", 'Smiling face with open mouth and tightly-closed eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u064A\u0646\u064A\u0646 \u0645\u063A\u0644\u0642\u0629 \u0628\u0625\u062D\u0643\u0627\u0645", 'Smiling face with halo': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0647\u0627\u0644\u0629", 'Smiling face with horns': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0628\u0642\u0631\u0648\u0646", 'Winking face': "\u0627\u0644\u063A\u0645\u0632 \u0648\u062C\u0647", 'Smiling face with smiling eyes': "\u064A\u0628\u062A\u0633\u0645 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u062A\u0628\u062A\u0633\u0645", 'Face savoring delicious food': "\u064A\u0648\u0627\u062C\u0647 \u0644\u0630\u064A\u0630 \u0627\u0644\u0645\u0630\u0627\u0642 \u0644\u0630\u064A\u0630 \u0627\u0644\u0637\u0639\u0627\u0645", 'Relieved face': "\u0648\u062C\u0647 \u0628\u0627\u0644\u0627\u0631\u062A\u064A\u0627\u062D", 'Smiling face with heart-shaped eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0628\u0639\u064A\u0646\u064A\u0646 \u0639\u0644\u0649 \u0634\u0643\u0644 \u0642\u0644\u0628", 'Smiling face with sunglasses': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0627\u0644\u0646\u0638\u0627\u0631\u0627\u062A \u0627\u0644\u0634\u0645\u0633\u064A\u0629", 'Smirking face': "\u0633\u0645\u064A\u0631\u0643\u064A\u0646\u062C \u0627\u0644\u0648\u062C\u0647", 'Neutral face': "\u0645\u062D\u0627\u064A\u062F \u0627\u0644\u0648\u062C\u0647", 'Expressionless face': "\u0648\u062C\u0647 \u0627\u0644\u062A\u0639\u0627\u0628\u064A\u0631", 'Unamused face': "\u0644\u0627 \u0645\u0633\u0644\u064A\u0627 \u0627\u0644\u0648\u062C\u0647", 'Face with cold sweat': "\u0648\u062C\u0647 \u0645\u0639 \u0639\u0631\u0642 \u0628\u0627\u0631\u062F", 'Pensive face': "\u0648\u062C\u0647 \u0645\u062A\u0623\u0645\u0644", 'Confused face': "\u0648\u062C\u0647 \u0627\u0644\u062E\u0644\u0637", 'Confounded face': "\u0648\u062C\u0647 \u0645\u0631\u062A\u0628\u0643", 'Kissing face': "\u062A\u0642\u0628\u064A\u0644 \u0627\u0644\u0648\u062C\u0647", 'Face throwing a kiss': "\u0645\u0648\u0627\u062C\u0647\u0629 \u0631\u0645\u064A \u0642\u0628\u0644\u0629", 'Kissing face with smiling eyes': "\u062A\u0642\u0628\u064A\u0644 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u062A\u0628\u062A\u0633\u0645", 'Kissing face with closed eyes': "\u062A\u0642\u0628\u064A\u0644 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u0645\u063A\u0644\u0642\u0629", 'Face with stuck out tongue': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646", 'Face with stuck out tongue and winking eye': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646 \u0648\u0627\u0644\u0639\u064A\u0646 \u0627\u0644\u062A\u063A\u0627\u0636\u064A", 'Face with stuck out tongue and tightly-closed eyes': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646 \u0648\u0627\u0644\u0639\u064A\u0648\u0646 \u0645\u063A\u0644\u0642\u0629 \u0628\u0623\u062D\u0643\u0627\u0645-", 'Disappointed face': "\u0648\u062C\u0647\u0627 \u062E\u064A\u0628\u0629 \u0623\u0645\u0644", 'Worried face': "\u0648\u062C\u0647\u0627 \u0627\u0644\u0642\u0644\u0642\u0648\u0646", 'Angry face': "\u0648\u062C\u0647 \u063A\u0627\u0636\u0628", 'Pouting face': "\u0627\u0644\u0639\u0628\u0648\u0633 \u0648\u062C\u0647", 'Crying face': "\u0627\u0644\u0628\u0643\u0627\u0621 \u0627\u0644\u0648\u062C\u0647", 'Persevering face': "\u0627\u0644\u0645\u062B\u0627\u0628\u0631\u0629 \u0648\u062C\u0647\u0647", 'Face with look of triumph': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0646\u0638\u0631\u0629 \u0627\u0646\u062A\u0635\u0627\u0631", 'Disappointed but relieved face': "\u0628\u062E\u064A\u0628\u0629 \u0623\u0645\u0644 \u0648\u0644\u0643\u0646 \u064A\u0639\u0641\u0649 \u0648\u062C\u0647", 'Frowning face with open mouth': "\u0645\u0642\u0637\u0628 \u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645", 'Anguished face': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0624\u0644\u0645", 'Fearful face': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u062E\u064A\u0641", 'Weary face': "\u0648\u062C\u0647\u0627 \u0628\u0627\u0644\u0636\u062C\u0631", 'Sleepy face': "\u0648\u062C\u0647 \u0646\u0639\u0633\u0627\u0646", 'Tired face': "\u0648\u062C\u0647 \u0645\u062A\u0639\u0628", 'Grimacing face': "\u0648\u062E\u0631\u062C \u0633\u064A\u0633 \u0627\u0644\u0648\u062C\u0647", 'Loudly crying face': "\u0627\u0644\u0628\u0643\u0627\u0621 \u0628\u0635\u0648\u062A \u0639\u0627\u0644 \u0648\u062C\u0647\u0647", 'Face with open mouth': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645", 'Hushed face': "\u0648\u062C\u0647\u0627 \u0627\u0644\u062A\u0643\u062A\u0645", 'Face with open mouth and cold sweat': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u0631\u0642 \u0627\u0644\u0628\u0627\u0631\u062F", 'Face screaming in fear': "\u0648\u0627\u062C\u0647 \u064A\u0635\u0631\u062E \u0641\u064A \u062E\u0648\u0641", 'Astonished face': "\u0648\u062C\u0647\u0627 \u062F\u0647\u0634", 'Flushed face': "\u0627\u062D\u0645\u0631\u0627\u0631 \u0627\u0644\u0648\u062C\u0647", 'Sleeping face': "\u0627\u0644\u0646\u0648\u0645 \u0627\u0644\u0648\u062C\u0647", 'Dizzy face': "\u0648\u062C\u0647\u0627 \u0628\u0627\u0644\u062F\u0648\u0627\u0631", 'Face without mouth': "\u0648\u0627\u062C\u0647 \u062F\u0648\u0646 \u0627\u0644\u0641\u0645", 'Face with medical mask': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0642\u0646\u0627\u0639 \u0627\u0644\u0637\u0628\u064A\u0629", // Line breaker 'Break': "\u0627\u0644\u0627\u0646\u0642\u0633\u0627\u0645", // Math 'Subscript': "\u0645\u0646\u062E\u0641\u0636", 'Superscript': "\u062D\u0631\u0641 \u0641\u0648\u0642\u064A", // Full screen 'Fullscreen': "\u0643\u0627\u0645\u0644 \u0627\u0644\u0634\u0627\u0634\u0629", // Horizontal line 'Insert Horizontal Line': "\u0625\u062F\u0631\u0627\u062C \u062E\u0637 \u0623\u0641\u0642\u064A", // Clear formatting 'Clear Formatting': "\u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u062A\u0646\u0633\u064A\u0642", // Save 'Save': "\u062D\u0641\u0638", // Undo, redo 'Undo': "\u062A\u0631\u0627\u062C\u0639", 'Redo': "\u0625\u0639\u0627\u062F\u0629", // Select all 'Select All': "\u062A\u062D\u062F\u064A\u062F \u0627\u0644\u0643\u0644", // Code view 'Code View': "\u0639\u0631\u0636 \u0627\u0644\u062A\u0639\u0644\u064A\u0645\u0627\u062A \u0627\u0644\u0628\u0631\u0645\u062C\u064A\u0629", // Quote 'Quote': "\u0627\u0642\u062A\u0628\u0633", 'Increase': "\u0632\u064A\u0627\u062F\u0629", 'Decrease': "\u0627\u0646\u062E\u0641\u0627\u0636", // Quick Insert 'Quick Insert': "\u0625\u062F\u0631\u0627\u062C \u0633\u0631\u064A\u0639", // Spcial Characters 'Special Characters': 'أحرف خاصة', 'Latin': 'لاتينية', 'Greek': 'الإغريقي', 'Cyrillic': 'السيريلية', 'Punctuation': 'علامات ترقيم', 'Currency': 'دقة', 'Arrows': 'السهام', 'Math': 'الرياضيات', 'Misc': 'متفرقات', // Print. 'Print': 'طباعة', // Spell Checker. 'Spell Checker': 'مدقق املائي', // Help 'Help': 'مساعدة', 'Shortcuts': 'اختصارات', 'Inline Editor': 'محرر مضمنة', 'Show the editor': 'عرض المحرر', 'Common actions': 'الإجراءات المشتركة', 'Copy': 'نسخ', 'Cut': 'يقطع', 'Paste': 'معجون', 'Basic Formatting': 'التنسيق الأساسي', 'Increase quote level': 'زيادة مستوى الاقتباس', 'Decrease quote level': 'انخفاض مستوى الاقتباس', 'Image / Video': 'صورة / فيديو', 'Resize larger': 'تغيير حجم أكبر', 'Resize smaller': 'تغيير حجم أصغر', 'Table': 'الطاولة', 'Select table cell': 'حدد خلية الجدول', 'Extend selection one cell': 'توسيع اختيار خلية واحدة', 'Extend selection one row': 'تمديد اختيار صف واحد', 'Navigation': 'التنقل', 'Focus popup / toolbar': 'التركيز المنبثقة / شريط الأدوات', 'Return focus to previous position': 'عودة التركيز إلى الموقف السابق', // Embed.ly 'Embed URL': 'تضمين عنوان ورل', 'Paste in a URL to embed': 'الصق في عنوان ورل لتضمينه', // Word Paste. 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'المحتوى الذي تم لصقه قادم من وثيقة كلمة ميكروسوفت. هل تريد الاحتفاظ بالتنسيق أو تنظيفه؟', 'Keep': 'احتفظ', 'Clean': 'نظيف', 'Word Paste Detected': 'تم اكتشاف معجون الكلمات', // Character Counter 'Characters': 'الشخصيات', // More Buttons 'More Text': 'المزيد من النص', 'More Paragraph': ' المزيد من الفقرة', 'More Rich': ' أكثر ثراء', 'More Misc': ' أكثر متفرقات' }, direction: 'rtl' }; }))); //# sourceMappingURL=ar.js.map
//copy codes from d3.js, add 4 functions: tickAttr, tickTextAttr, minorTickAttr and domainAttr; //axis() changes, need a raphael paper object param, return raphael set object. //examples in ../examples/axis/ to know the usage. //a basic part for other data visualization format /*global d3*/ /*! * Axis兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Axis', function (require) { /** * function from d3, get scaleRange of an ordinal scale * @param {Array} domain ordinal scale's range */ function d3_scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [start, stop] : [stop, start]; } /** * function from d3, get scaleRange of a scale */ function d3_scaleRange(scale) { return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); } /** * function from d3, get subticks * @param scale, scale * @param ticks, major ticks of scale * @param m, number of subdivide */ function d3_svg_axisSubdivide(scale, ticks, m) { var subticks = []; if (m && ticks.length > 1) { var extent = d3_scaleExtent(scale.domain()), i = -1, n = ticks.length, d = (ticks[1] - ticks[0]) / ++m, j, v; while (++i < n) { for (j = m; --j > 0;) { if ((v = +ticks[i] - j * d) >= extent[0]) { subticks.push(v); } } } for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1];) { subticks.push(v); } } return subticks; } var Axis = function () { var scale = d3.scale.linear(), orient = "bottom", tickMajorSize = 6, tickMinorSize = 6, tickEndSize = 6, tickPadding = 3, tickArguments_ = [10], tickFormat_, tickSubdivide = 0, tickAttr_ = {}, tickTextAttr_ = {}, minorTickAttr_ = {}, domainAttr_ = {}; /** * @param paper: raphael's paper object. * @return axisSet: raphael's set object. */ function axis(paper) { // Ticks for quantitative scale, or domain values for ordinal scale. var ticks = scale.ticks ? scale.ticks.apply(scale, tickArguments_) : scale.domain(), tickFormat = tickFormat_ === undefined ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments_) : String) : tickFormat_; var subticks = d3_svg_axisSubdivide(scale, ticks, tickSubdivide); var range = d3_scaleRange(scale); var axisSet = paper.set(); switch (orient) { case "bottom": subticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + tickMinorSize + "V0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + tickMajorSize + "V0") .attr(tickAttr_)); axisSet.push(paper .text(tickX, Math.max(tickMajorSize, 0) + tickPadding + 2, typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "middle"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize) .attr(domainAttr_)); break; case "top": subticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + -tickMinorSize + "V0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + -tickMajorSize + "V0") .attr(tickAttr_)); axisSet.push(paper .text(tickX, -(Math.max(tickMajorSize, 0) + tickPadding + 2), typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "middle"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize) .attr(domainAttr_)); break; case "left": subticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + -tickMinorSize + "," + tickY + "H0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + -tickMajorSize + "," + tickY + "H0") .attr(tickAttr_)); axisSet.push(paper .text(-(Math.max(tickMajorSize, 0) + tickPadding), tickY, typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "end"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize) .attr(domainAttr_)); break; case "right": subticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickMinorSize + "," + tickY + "H0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickMajorSize + "," + tickY + "H0") .attr(tickAttr_)); axisSet.push(paper .text(Math.max(tickMajorSize, 0) + tickPadding, tickY, typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "start"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize) .attr(domainAttr_)); break; } return axisSet; } /** * get or set axis' scale. */ axis.scale = function (x) { if (!arguments.length) { return scale; } scale = x; return axis; }; /** * get or set axis' orinet: "bottom", "top", "left", "right", default orient is bottom. */ axis.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return axis; }; /** * get or set axis' ticks number. */ axis.ticks = function () { if (!arguments.length) { return tickArguments_; } tickArguments_ = arguments; return axis; }; /** * get or set axis' ticks format function, it's a function change format style. * from one string format to another string format. */ axis.tickFormat = function (x) { if (!arguments.length) { return tickFormat_; } tickFormat_ = x; return axis; }; /** * get or set axis' tick size(length of tick line, unit: px). * @param arguments.length === 0, get axis' major tick size. * @param arguments.length === 1, set axis' all tick sizes as x. * @param arguments.length === 2, get axis' major tick size as x, minor and end size as y. * @param arguments.length === 3, get axis' major tick size as x, minor size as y, end size as z. */ axis.tickSize = function (x, y, z) { if (!arguments.length) { return tickMajorSize; } var n = arguments.length - 1; tickMajorSize = +x; tickMinorSize = n > 1 ? +y : tickMajorSize; tickEndSize = n > 0 ? +arguments[n] : tickMajorSize; return axis; }; /** * get or set axis' tick padding(the distance between tick text and axis). * @param x is a number, unit is px; */ axis.tickPadding = function (x) { if (!arguments.length) { return tickPadding; } tickPadding = +x; return axis; }; /** * get or set axis' sub tick divide number(divide number between two major ticks). */ axis.tickSubdivide = function (x) { if (!arguments.length) { return tickSubdivide; } tickSubdivide = +x; return axis; }; /** * get or set axis' tick attribute(Raphael format). */ axis.tickAttr = function (x) { if (!arguments.length) { return tickAttr_; } tickAttr_ = x; return axis; }; /** * get or set axis' tick text attribute(Raphael format). */ axis.tickTextAttr = function (x) { if (!arguments.length) { return tickTextAttr_; } tickTextAttr_ = x; return axis; }; /** * get or set axis' minor tick attribute(Raphael format). */ axis.minorTickAttr = function (x) { if (!arguments.length) { return minorTickAttr_; } minorTickAttr_ = x; return axis; }; /** * get or set axis' domain(axis line) attribute(Raphael format). */ axis.domainAttr = function (x) { if (!arguments.length) { return domainAttr_; } domainAttr_ = x; return axis; }; return axis; }; return Axis; }); /*global Raphael, d3, $, define, _ */ /*! * Stream的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('StreamAxis', function (require) { var DataV = require('DataV'); DataV.Axis = require('Axis'); var Axis = DataV.extend(DataV.Chart, { initialize: function (container) { this.node = $(container); /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; } }); Axis.prototype.setSource = function (source, map) { map = this.map(map); this.grouped = _.groupBy(source, map.x); this.axis = _.keys(this.grouped); this.range = [0, this.axis.length - 1]; }; Axis.prototype.init = function () { var conf = this.defaults; this.paper = new Raphael(this.node[0], conf.legendBesidesWidth, conf.axisHeight); this.node.css({ "margin-top": "0px", "border-top": "1px solid #ddd", "height": conf.axisHeight + "px" }); }; Axis.prototype.render = function () { this.init(); this.clear(); //all date strings' format are same, string length are same var conf = this.defaults, that = this; var getPopPath = function (El) { //down pop var x = 0, y = 0, size = 4, cw = 23, bb = {height: 8}; if (El) { bb = El.getBBox(); bb.height *= 0.6; cw = bb.width / 2 - size; } return [ 'M', x, y, 'l', size, size, cw, 0, 'a', size, size, 0, 0, 1, size, size, 'l', 0, bb.height, 'a', size, size, 0, 0, 1, -size, size, 'l', -(size * 2 + cw * 2), 0, 'a', size, size, 0, 0, 1, -size, -size, 'l', 0, -bb.height, 'a', size, size, 0, 0, 1, size, -size, 'l', cw, 0, 'z' ].join(','); }; var left = conf.percentageWidth, right = conf.legendBesidesWidth - conf.percentageWidth; var tempWord = this.paper.text(0, 0, this.axis[0]); var tickNumber = Math.floor((right - left) / tempWord.getBBox().width / 2) + 1; tempWord.remove(); this.dateScale = d3.scale.linear() .domain([0, this.axis.length - 1]) .range([left, right]); DataV.Axis().scale(this.dateScale) .ticks(tickNumber) .tickSize(6, 3, 3) .tickAttr({"stroke": "none"}) .minorTickAttr({"stroke": "none"}) .domainAttr({"stroke": "none"}) .tickFormat(function (d) { return that.axis[d] || ""; })(this.paper); this.axisPopText = this.paper.text(0, 11, this.axis[0]) .attr({ "text-anchor": "middle", "fill": "#fff", "transform": "t" + left + ",0" }).hide(); this.axisPopBubble = this.paper.path(getPopPath(this.axisPopText)) .attr({ "fill": "#000", "transform": "t" + (-10000) + ",0" }).toBack() .hide(); }; Axis.prototype.hideTab = function () { this.axisPopText.hide(); this.axisPopBubble.hide(); }; Axis.prototype.showTab = function () { this.axisPopText.show(); this.axisPopBubble.show(); }; Axis.prototype.refreshTab = function (index) { var conf = this.defaults; var x = conf.chartWidth * index / (this.axis.length - 1); var transX = x + this.defaults.percentageWidth; this.axisPopText.attr({ "text": this.axis[index + this.range[0]] }).transform("t" + transX + ",0"); this.axisPopBubble.transform("t" + transX + ",0"); }; Axis.prototype.clear = function () { this.paper.clear(); }; return Axis; }); /*global Raphael, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Legend', function (require) { var DataV = require('DataV'); var Legend = DataV.extend(DataV.Chart, { initialize: function (container) { this.legendIndent = 20; this.node = $(container); /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; this.defaults.highlightStyle = {"backgroundColor": "#dddddd"}; this.defaults.lowlightStyle = {"backgroundColor": "white"}; this.formatLabel = function (text) { return text; }; this.init(); } }); Legend.prototype.init = function () { var conf = this.defaults; this.legend = $("<div></div>"); this.legend.css({ "overflow": "hidden", "padding": "10px 0 10px 0", "width": conf.leftLegendWidth - this.legendIndent + "px" }); this.node.append(this.legend); this.initEvents(); }; Legend.prototype.setSource = function (source, map) { map = this.map(map); var groupedByType = _.groupBy(source, map.type); var sorted = _.sortBy(groupedByType, function (group) { return -DataV.sum(group, map.value); }); //this.list = _.keys(); this.list = sorted.map(function (d) { return d[0][map.type]; }); }; Legend.prototype.initEvents = function () { var that = this; that.on('hoverIn', function (index) { that.highlight(index); }).on('hoverOut', function (index) { that.lowlight(index); }).on('level_changed', function (start, end, needMore) { that.render(start, end, needMore); }); }; Legend.prototype.render = function (level) { var conf = this.defaults; conf.level = level || 0; var that = this; this.clear(); this.legends = []; var colorFunc = conf.colorFunc, hoverIn = function (e) { var index = e.data.index; that.fire('hoverIn', index); this.highlight(index); }, hoverOut = function (e) { var index = e.data.index; that.fire('hoverOut', index); this.lowlight(index); }; var ul = $("<ul></ul>").css({ "margin": "0 0 0 10px", "paddingLeft": 0 }); var selected; if (!conf.more) { selected = this.list.slice(0); } else { selected = DataV.more(this.list, conf.level, conf.max, function () { return conf.moreLabel; }); } var formatLabel = conf.formatLabel || this.formatLabel; for (var i = 0, l = selected.length; i < l; i++) { var color = colorFunc(i); var li = $('<li style="color: ' + color + '"><span style="color: black" title="' + selected[i] + '">' + formatLabel(selected[i]) + '</span></li>'); li.mouseenter({"index": i}, $.proxy(hoverIn, this)).mouseleave({"index": i}, $.proxy(hoverOut, this)); ul.append(li); this.legends.push(li); } ul.find("li").css({ "list-style-type": "square", "list-style-position": "inside", "white-space": "nowrap", "padding-left": 5 }); this.legend.append(ul); }; Legend.prototype.highlight = function (index) { if (typeof index !== 'undefined') { this.legends[index].css(this.defaults.highlightStyle); } }; Legend.prototype.lowlight = function (index) { if (typeof index !== 'undefined') { this.legends[index].css(this.defaults.lowlightStyle); } }; Legend.prototype.clear = function () { this.legend.empty(); }; var TopLegend = DataV.extend(DataV.Widget, { initialize: function (container) { this.node = $(container); this.defaults.r0 = 5; this.defaults.r1 = 7; } }); TopLegend.prototype.init = function () { var conf = this.owner.defaults; this.legend = $("<div></div>").css({ "width": conf.width, "backgroundColor": "#f4f4f4" }); this.node.append(this.legend); }; TopLegend.prototype.render = function () { this.init(); var that = this; var owner = this.owner, conf = owner.defaults; var r0 = this.defaults.r0; this.legends = []; this.paper = new Raphael(this.legend[0], conf.width, 50); var paper = this.paper; var m = [10, 20, 10, 20], left = m[3], top = m[0], lineHeight = 25, legendInterval = 10, lineWidth = conf.width, circleW = 18, colorFunc = owner.getColor(); var hoverIn = function () { var index = this.data("index"); that.owner.fire('hoverIn', index); that.highlight(index); }; var hoverOut = function () { var index = this.data("index"); that.owner.fire('hoverOut', index); that.lowlight(index); }; that.on('hoverIn', function (index) { that.highlight(index); }).on('hoverOut', function (index) { that.lowlight(index); }); var colorArray = owner.displayData.allInfos.map(function (item, index) { return colorFunc(index); }); for (var i = 0, l = owner.displayData.allInfos.length; i < l; i++) { var text = paper.text(0, 0, owner.getDisplayRowInfo(i).rowName).attr({ "font-size": conf.fontSize, "text-anchor": "start", "font-family": "微软雅黑" }); var box = text.getBBox(); if (left + circleW + box.width >= lineWidth - m[1]) { //new line left = m[3]; top += lineHeight; } var color = colorArray[owner.displayData.rowIndex[i].slicedData]; var circle = paper.circle(left + circleW / 2, top + lineHeight / 2, r0) .attr({ "stroke": "none", "fill": color }) .data("index", i) .hover(hoverIn, hoverOut); text.transform("t" + (left + circleW) + "," + (top + lineHeight / 2)); paper.rect(left + circleW, top, box.width, lineHeight).attr({ "stroke": "none", "fill": "#000", "opacity": 0 }) .data("index", i) .hover(hoverIn, hoverOut); that.legends.push({"text": text, "circle": circle}); left += legendInterval + circleW + box.width; } paper.setSize(lineWidth, top + lineHeight + m[2]); }; TopLegend.prototype.highlight = function (index) { this.legends[index].circle.animate({"r": this.defaults.r1, "opacity": 0.5}, 300); }; TopLegend.prototype.lowlight = function (index) { this.legends[index].circle.animate({"r": this.defaults.r0, "opacity": 1}, 300); }; return { Legend: Legend, TopLegend: TopLegend }; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Navi', function (require) { var DataV = require('DataV'); var Navi = DataV.extend(DataV.Chart, { initialize: function (container) { this.node = $(container); } }); Navi.prototype.init = function () { this.naviBackWidth = 80; var conf = this.defaults; this.node.css({ "borderTop": "1px solid #ddd", "borderBottom": "1px solid #ddd", "padding": "5px 10px 10px 10px", "fontSize": conf.fontSize + 1, "fontFamily": "宋体" }); this.naviTrace = $("<div></div>").css({ "width": conf.legendBesidesWidth - this.naviBackWidth - 50, "margin-top": "5px" }); this.naviBack = $("<div></div>"); this.naviBack.html("返回上层").css({ "width": this.naviBackWidth + "px", "float": "right", "background-color": "#f4f4f4", "padding-top": "4px", "padding-bottom": "4px", "border": "1px solid #ddd", "border-radius": "2px", "cursor": "pointer", "text-align": "center", "visibility": "hidden" }); this.node.append(this.naviBack).append(this.naviTrace); var that = this; this.naviTrace.on("click", ".navi", function (e) { that.owner.fire('changeLevelTo', e.target.data('level')); }); this.naviBack.on("back", function () { that.owner.fire('changeLevel'); }); }; Navi.prototype.render = function () { this.init(); var level = this.defaults.level; this.clear(); for (var i = 0; i <= level; i++) { this.naviTrace.append($("<span> &gt; </span>")); var span = $("<span></span>").data("level", i).html("第" + (i + 1) + "层"); this.naviTrace.append(span); if (i !== level) { span.css({ "cursor": "pointer", "color": "#1E90FF" }).addClass("navi"); } } this.naviBack.css('visibility', level > 0 ? "visible" : "hidden"); }; Navi.prototype.clear = function () { this.naviTrace.empty(); }; return Navi; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Tip', function (require) { var DataV = require('DataV'); //floatTag var Tip = DataV.extend(DataV.Chart, { initialize: function (container) { this.container = container; this.node = DataV.FloatTag()(this.container); /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; }, getContent: function (obj) { return obj[this.mapping.x]; } }); Tip.prototype.setSource = function (source, map) { var that = this; this.map(map); this.rawData = source; this.groupedByX = _.groupBy(source, this.mapping.x); this.groupedByType = _.groupBy(source, this.mapping.type); var sorted = _.sortBy(this.groupedByType, function (group) { return -DataV.sum(group, that.mapping.value); }); this.sorted = sorted; _.each(sorted, function (list, index) { that.groupedByType[list[0][that.mapping.type]].finalRank = index + 1; }); this.axis = _.keys(this.groupedByX); }; Tip.prototype.render = function () { this.hidden(); this.node.css(this.defaults.tipStyle); }; Tip.prototype.setContent = function (rowIndex, columnIndex) { var that = this; var conf = this.defaults; var getContent = conf.getContent || this.getContent; var column = this.groupedByX[this.axis[columnIndex]]; var values = this.sorted;//_.values(this.groupedByType); var types; if (!conf.more) { types = values; } else { types = DataV.more(values, conf.level, conf.max, function (remains) { var row = []; for (var i = 0; i < that.axis.length; i++) { var col = {}; col[that.mapping.type] = conf.moreLabel; col[that.mapping.x] = that.axis[i]; col[that.mapping.value] = NaN;// DataV.sum(_.pluck(remains, i), that.mapping.value); col.rate = DataV.sum(_.pluck(remains, i), "rate"); row.push(col); } return row; }); } var row = types[rowIndex]; var obj = row[columnIndex]; var index = _.indexOf(_.map(column, function (item) { return item[that.mapping.value]; }).sort(function (a, b) { return a > b ? -1 : 1; }), obj[that.mapping.value]); obj.rank = index === -1 ? NaN : index + 1; var html = getContent.call(this, obj); this.node.html(html); }; return Tip; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Percentage', function (require) { var DataV = require('DataV'); var Percentage = DataV.extend(DataV.Chart, { initialize: function (container) { this.node = $(container); this.limit = 20; this.from = 0; this.to = 0; /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; } }); Percentage.prototype.init = function () { var conf = this.defaults; this.paper = new Raphael(this.node[0], conf.percentageWidth, conf.chartHeight); this.node.css({ "width": conf.percentageWidth, "height": conf.chartHeight, "float": "left", "margin-bottom": "0px", "border-bottom": "0px", "padding-bottom": "0px" }); }; Percentage.prototype.setSource = function (source, map) { map = this.map(map); this.grouped = _.groupBy(source, map.type); this.types = _.keys(this.grouped); if (this.types.length > this.limit) { this.to = this.limit; } }; Percentage.prototype.render = function () { this.init(); var conf = this.defaults; var y = conf.fontSize * 2 / 3; if (!this.rect) {//init this.rect = this.paper.rect(0, 0, conf.percentageWidth, conf.chartHeight) .attr({ "fill": "#f4f4f4", "stroke": "#aaa", "stroke-width": 0.5 }); this.text = this.paper.text(conf.percentageWidth / 2, y, Math.round(100) + "%") .attr({"text-anchor": "middle"}); } // this.rect.animate({"y": (1 - maxY) * conf.chartHeight, "height": maxY * conf.chartHeight}, 750); // this.text.attr({ // "text": Math.round(maxY * 100) + "%" // }).animate({"y": y}, 300); }; return Percentage; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('HoverLine', function (require) { var DataV = require('DataV'); var HoverLine = DataV.extend(DataV.Chart, { initialize: function () { } }); HoverLine.prototype.render = function () { this.clear(); var paper = this.owner.paper; var conf = this.defaults; this.indicatorLine = paper.path("M0 0V" + conf.chartHeight).attr({ stroke: "none", "stroke-width": 1, "stroke-dasharray": "- " }); this.highlightLine = paper.path("M0 0V" + conf.chartHeight).attr({ stroke: "none", "stroke-width": 2 }); }; HoverLine.prototype.hidden = function () { this.indicatorLine.attr({"stroke": "none"}); this.highlightLine.attr({"stroke": "none"}); }; HoverLine.prototype.show = function () { this.indicatorLine.attr({"stroke": "#000"}); this.highlightLine.attr({"stroke": "white"}); }; HoverLine.prototype.refresh = function (columnIndex, rowIndex) { //refresh lines' position var owner = this.owner; var pathSource = owner.pathSource; var lineX = this.defaults.chartWidth * columnIndex / (owner.columnCount - 1); var pathSourceCell = pathSource[pathSource.length - 1][columnIndex]; this.indicatorLine.attr({ path: "M" + lineX + " " + (pathSourceCell.y0 - pathSourceCell.y) + "V" + pathSource[0][columnIndex].y0 }); if (typeof rowIndex !== 'undefined') { pathSourceCell = pathSource[rowIndex][columnIndex]; this.highlightLine.attr({ path: "M" + lineX + " " + (pathSourceCell.y0 - pathSourceCell.y) + "V" + pathSourceCell.y0 }); if (rowIndex === 0) { this.highlightLine.attr({"cursor": "pointer"}); } else { this.highlightLine.attr({"cursor": "auto"}); } } }; HoverLine.prototype.clear = function () { this.indicatorLine && this.indicatorLine.remove(); this.highlightLine && this.highlightLine.remove(); }; return HoverLine; }); /*global Raphael, d3, $, define, _ */ /*! * PathLabel的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('PathLabel', function (require) { var DataV = require('DataV'); //pathLabel var PathLabel = DataV.extend(DataV.Chart, { initialize: function () { /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; } }); PathLabel.prototype.render = function () { this.clear(); var that = this; var owner = this.owner; var paths = owner.paths; var conf = this.defaults; var pathSource = owner.pathSource; var labels = []; var getLabelLocation = function (locArray, el) { var x = 0, y = 0, i; var ratioMargin = 0.15; var index = 0; var max = 0; var box = el.getBBox(); var xInterval; var minTop, maxBottom; var showLabel = true; var loc; var height; xInterval = Math.ceil(box.width / (locArray[1].x - locArray[0].x) / 2); if (xInterval === 0) { xInterval = 1; } locArray.forEach(function (d, i, array) { var m = Math.max(ratioMargin * array.length, xInterval); if (i >= m && i <= array.length - m) { if (d.y > max) { minTop = d.y0 - d.y; maxBottom = d.y0; max = d.y; index = i; } } }); for (i = index - xInterval; i <= index + xInterval; i++) { if (i < 0 || i >= locArray.length) { height = 0; showLabel = false; break; } loc = locArray[i]; //top's y is small if (loc.y0 - loc.y > minTop) { minTop = loc.y0 - loc.y; } if (loc.y0 < maxBottom) { maxBottom = loc.y0; } } if (showLabel && maxBottom - minTop >= box.height * 0.8) { x = locArray[index].x; y = (minTop + maxBottom) / 2; } else { showLabel = false; } return { x: x, y: y, showLabel: showLabel }; }; var getPathLabel = this.defaults.getPathLabel || this.getPathLabel; var selected; //var values = _.values(this.groupedByType); var values = _.values(this.sorted); if (!conf.more) { selected = values.slice(0); } else { selected = DataV.more(values, conf.level, conf.max, function (remains) { var obj = {}; obj.type = conf.moreLabel; obj.rank = remains[0].rank; obj.sum = DataV.sum(remains, "sum"); return obj; }); } for (var i = 0, l = paths.length; i < l; i++) { var path = paths[i]; var row = selected[i]; var obj = { type: row.type, rank: row.rank, sum: row.sum, total: this.total }; var text = getPathLabel.call(this, obj); var label = owner.paper.text(0, 0, text).attr({ "textAnchor": "middle", "fill": "white", "fontSize": conf.fontSize, "fontFamily": "微软雅黑" }); label.labelLoc = getLabelLocation(pathSource[i], label); if (label.labelLoc.showLabel) { label.attr({ "x": label.labelLoc.x, "y": label.labelLoc.y }); } else { label.attr({"opacity": 0}); } path.attr({"cursor": "auto"}); label.attr({"cursor": "auto"}); labels.push(label); } this.labels = labels; }; /** * 生成标签的默认方法,可以通过`setOption({getPathLable: function});`覆盖。 * Properties: * - `type`, 条带类型 * - `rank`, 条带排名 * - `sum`, 当前条带总值 * - `total`, 所有条带总值 * @param {Object} obj 当前条带的对象 */ PathLabel.prototype.getPathLabel = function (obj) { return obj.type + " " + "排名: 第" + obj.rank; }; PathLabel.prototype.hidden = function () { this.labels.forEach(function (d) { d.hide(); }); }; PathLabel.prototype.show = function () { this.labels.forEach(function (d) { if (d.labelLoc.showLabel) { d.show(); } }); }; PathLabel.prototype.clear = function () { if (this.labels) { this.labels.forEach(function (d) { d.remove(); }); } }; PathLabel.prototype.setSource = function (source, map) { var that = this; this.map(map); this.groupedByType = _.groupBy(source, this.mapping.type); var sorted = _.sortBy(this.groupedByType, function (group, type) { var sum = DataV.sum(group, that.mapping.value); that.groupedByType[type].sum = sum; that.groupedByType[type].type = type; return -sum; }); this.sorted = sorted; this.types = _.keys(this.groupedByType); _.each(sorted, function (list, index) { that.groupedByType[list[0][that.mapping.type]].rank = index + 1; }); this.total = DataV.sum(_.map(that.groupedByType, function (group) { return group.sum; })); }; return PathLabel; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Cover', function (require) { var DataV = require('DataV'); //cover var Cover = DataV.extend(DataV.Chart, { initialize: function (container) { var conf = this.defaults; this.node = $(container); this.node.css({ "position": "absolute", "left": 0, "top": 0, "width": conf.chartWidth, "height": conf.chartHeight, "zIndex": 100, "visibility": "hidden" }).bind("mousemove", $.proxy(function (e) { this.mouse = {x: e.pageX, y: e.pageY}; e.stopPropagation(); }, this)).bind("mouseleave", $.proxy(function () { this.mouse = undefined; }, this)); } }); return Cover; }); /*global Raphael, d3, $, define, _ */ /*! * Stream的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Stream', function (require) { var DataV = require('DataV'); var HoverLine = require('HoverLine'); var PathLabel = require('PathLabel'); //streamChart var Stream = DataV.extend(DataV.Chart, { initialize: function (node, options) { this.node = this.checkContainer(node); /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; this.defaults.width = 500; this.defaults.height = 300; this.defaults.offset = "expand";//zero, expand, silhou-ette, wiggle; this.defaults.order = "default";//default, reverse, inside-out //in this Stream application, it will always be default, the real order is adjusted in Stream's data-process. this.defaults.animateDuration = 750; this.defaults.animateOrder = undefined; this.paths = undefined; this.source = undefined; this.layoutData = undefined; this.pathSource = undefined; this.setOptions(options); this.createPaper(); } }); Stream.prototype.createPaper = function () { var conf = this.defaults; this.paper = new Raphael(this.node, conf.width, conf.height); }; Stream.prototype.setSource = function (source, map) { this.map(map); this.rawData = source; this.rawMap = map; var that = this; // 按类型分组 var grouped = _.groupBy(source, this.mapping.type); this.rowCount = _.keys(grouped).length; this.columnCount = _.keys(_.groupBy(source, this.mapping.x)).length; // 组内按横轴排序 _.forEach(grouped, function (group, type) { grouped[type] = _.sortBy(group, that.mapping.x); }); this.sorted = _.sortBy(grouped, function (group) { return 0 - DataV.sum(group, that.mapping.value); }); this.remaped = this.remapSource(); this.layoutData = this.getLayoutData(); }; Stream.prototype.remapSource = function () { var sorted = this.sorted; var remap = []; for (var j = 0; j < this.columnCount; j++) { var plucked = _.pluck(sorted, j); var sum = DataV.sum(plucked, this.mapping.value); for (var i = 0; i < this.rowCount; i++) { remap[i] = remap[i] || []; remap[i][j] = {}; remap[i][j].x = j; var rate = sorted[i][j][this.mapping.value] / sum; remap[i][j].y = rate; sorted[i][j].rate = rate; } } return remap; }; /*! * 获取等级数据 */ Stream.prototype.getLayoutData = function () { var conf = this.defaults; var remaped = this.remaped; var that = this; if (!conf.more) { return remaped; } else { return DataV.more(remaped, conf.level, conf.max, function (remains) { var obj = []; for (var i = 0; i < that.columnCount; i++) { obj.push({ x: i, y: DataV.sum(_.pluck(remains, i), 'y') }); } return obj; }); } }; Stream.prototype.layout = function () { var conf = this.defaults; d3.layout.stack().offset(conf.offset).order(conf.order)(this.layoutData); }; Stream.prototype.generateChartElements = function () { var conf = this.defaults; var paper = this.paper, paths = []; var area = this.generateArea(); var colorFunc = this.getColor(); // set div's background instread; paper.rect(0, 0, conf.chartWidth, conf.chartHeight).attr({ "stroke": "none", "fill": "#e0e0e0" }); for (var i = 0, l = this.layoutData.length; i < l; i++) { var areaString = area(this.pathSource[i]); var color = colorFunc(i); var path = paper.path(areaString).attr({ fill: color, stroke: color, "stroke-width": 1 }); paths[i] = path; } this.paths = paths; }; Stream.prototype.render = function (animate) { if (animate !== "animate") { this.clear(); this.layout(); this.generateChartElements(); } else { this.layout(); this.animate(); } //hoverLine this.hoverLine = this.own(new HoverLine()); this.hoverLine.render();//lines should be to front, so at last //pathLabel if (this.defaults.pathLabel) { this.pathLabel = this.own(new PathLabel()); this.pathLabel.setSource(this.rawData, this.rawMap); this.pathLabel.render(); } this.createInteractive(); }; Stream.prototype.animate = function () { var time = 0, area, colorFunc, color, i, l, _area, paths = [], order, anim, count = this.paths.length; var that = this; var animateCallback = function () { count -= 1; if (count > 0) { return; } that.animateCallback(); }; if (typeof this.defaults.animateDuration !== 'undefined') { time = this.defaults.animateDuration; } // if paths have not been created if (typeof this.paths === 'undefined') { this.generateChartElements(); } area = this.generateArea(); colorFunc = this.getColor(); if (typeof this.defaults.animateOrder !== 'undefined') { order = this.defaults.animateOrder; } else { order = d3.range(this.pathSource.length); } for (i = 0, l = this.pathSource.length; i < l; i++) { _area = area(this.pathSource[i]); paths.push(_area); } for (i = 0, l = this.pathSource.length; i < l; i++) { color = colorFunc(i); anim = Raphael.animation({"path": paths[i]}, time, animateCallback); this.paths[order[i]].animate(anim); } }; Stream.prototype.animateCallback = function () { var newOrderPaths = []; var that = this; if (typeof this.defaults.animateOrder !== 'undefined') { this.defaults.animateOrder.forEach(function (d, i) { newOrderPaths[i] = that.paths[d]; }); this.paths = newOrderPaths; } }; Stream.prototype.clear = function () { this.paper.clear(); }; Stream.prototype.getColor = function (colorJson) { var colorMatrix = DataV.getColor(); var color; var colorStyle = colorJson || {}; var colorMode = colorStyle.mode || 'default'; var i, l; switch (colorMode) { case "gradient": l = this.source.length; // 最大为 colorMatrix.length - 1 var colorL = Math.min(Math.round(l / 5), colorMatrix.length - 1); var testColor = [colorMatrix[0][0], colorMatrix[colorL][0]]; var test1 = DataV.gradientColor(testColor, "special"); var testColorMatrix = []; var testColorMatrix1 = []; for (i = 0; i < l; i++) { testColorMatrix.push([test1(i / (l - 1)), test1(i / (l - 1))]); } for (i = l - 1; i >= 0; i--) { testColorMatrix1.push(testColorMatrix[i]); } colorMatrix = testColorMatrix; break; case "random": case "default": break; } var ratio = colorStyle.ratio || 0; ratio = Math.max(ratio, 0); ratio = Math.min(ratio, 1); var colorArray = colorMatrix.map(function () { return d3.interpolateRgb.apply(null, [colorMatrix[i][0], colorMatrix[i][1]])(ratio); }); color = d3.scale.ordinal().range(colorArray); return color; }; /* */ Stream.prototype.getColor = function () { var count = this.layoutData.length; var color = this.defaults.gradientColor || ["#8be62f", "#1F4FD8"]; var gradientColor = DataV.gradientColor(color, "special"); var percent = 1 / count; var gotColors = []; for (var i = 0; i < count; i++) { gotColors.push(gradientColor(i * percent)); } var midderNum = Math.floor(count / 2); return function (num) { return num % 2 === 0 ? gotColors[midderNum + num / 2] : gotColors[midderNum - (num + 1) / 2]; }; }; Stream.prototype.getMaxY = function () { return d3.max(this.layoutData, function (d) { return d3.max(d, function (d) { return d.y0 + d.y; }); }); }; Stream.prototype.mapPathSource = function () { var conf = this.defaults, maxX = this.layoutData[0].length - 1, maxY = this.getMaxY(), width = conf.chartWidth, height = conf.chartHeight; this.pathSource = []; for (var i = 0, l = this.layoutData.length; i < l; i++) { this.pathSource[i] = []; for (var j = 0, l2 = this.layoutData[0].length; j < l2; j++) { var s = this.layoutData[i][j]; var ps = this.pathSource[i][j] = {}; ps.x = s.x * width / maxX; ps.y0 = height - s.y0 * height / maxY; ps.y = s.y * height / maxY; } } }; Stream.prototype.generateArea = function () { this.mapPathSource(); var area = d3.svg.area().x(function (d) { return d.x; }).y0(function (d) { return d.y0; }).y1(function (d) { return d.y0 - d.y; }); return area; }; Stream.prototype.highlight = function (index) { if (typeof index !== 'undefined') { this.paths[index].attr({"opacity": 0.5, "stroke-width": 0}); } }; Stream.prototype.lowlight = function (index) { if (typeof index !== 'undefined') { this.paths[index].attr({"opacity": 1, "stroke-width": 1}); } }; Stream.prototype.createInteractive = function () { $(this.paper.canvas).unbind();//prevent event rebind. //refactor stream chart's animate function, especially change the callback var stream = this; this.animateCallback = function () { var newOrderPaths = []; var that = this; if (typeof this.defaults.animateOrder !== 'undefined') { this.defaults.animateOrder.forEach(function (d, i) { newOrderPaths[i] = that.paths[d]; }); this.paths = newOrderPaths; } stream.cover.hidden(); if (typeof stream.cover.mouse !== 'undefined') { stream.hoverLine.show(); stream.floatTag.show(); var mouse = stream.cover.mouse; $(stream.paper.canvas).trigger("mousemove", [mouse.x, mouse.y]); $(stream.floatTag).trigger("mousemove", [mouse.x, mouse.y]); stream.cover.mouse = undefined; } stream.pathLabel.show(); }; //chart mouseenter var mouseenter = function () { stream.hoverLine.show(); stream.fire('enter'); }; //chart mouseleave var mouseleave = function () { stream.hoverLine.hidden(); //recover prepath; if (typeof stream.preIndex !== 'undefined') { stream.lowlight(stream.preIndex); } stream.fire('leave', stream.preIndex); stream.preIndex = undefined; }; //chart click var click = function () {}; //chart mousemove var mousemove = function (e, pageX, pageY) { var offset = $(this).parent().offset(); var x = (e.pageX || pageX) - offset.left, y = (e.pageY || pageY) - offset.top; var pathSource = stream.pathSource, rowIndex; var columnIndex = Math.floor((x / (stream.defaults.chartWidth / (stream.columnCount - 1) / 2) + 1) / 2); //get path and pathIndex for (var i = 0, l = pathSource.length; i < l; i++) { if (y >= pathSource[i][columnIndex].y0 - pathSource[i][columnIndex].y && y <= pathSource[i][columnIndex].y0) { rowIndex = i; break; } } //recover prepath; if (typeof stream.preIndex !== 'undefined') { stream.lowlight(stream.preIndex); } stream.highlight(rowIndex); stream.fire('move', stream.preIndex, rowIndex, columnIndex); //set indicator and highlight line new position stream.hoverLine.refresh(columnIndex, rowIndex); //customevent; if (stream.defaults.customEventHandle.mousemove) { stream.defaults.customEventHandle.mousemove.call(stream, {"timeIndex": columnIndex, "rowIndex": rowIndex}); } //change new path; stream.preIndex = rowIndex; }; $(this.paper.canvas).bind("mouseenter", mouseenter) .bind("mouseleave", mouseleave) .bind("click", click) .bind("mousemove", mousemove); }; return Stream; }); /*global $, define */ /*! * Stream的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('StreamComponent', function (require) { var DataV = require('DataV'); var Legend = require('Legend'); var Navi = require('Navi'); var Percentage = require('Percentage'); var Axis = require('StreamAxis'); var Tip = require('Tip'); var Stream = require('Stream'); var Cover = require('Cover'); /* * constructor * @param node the dom node or dom node Id * options options json object for determin stream style. * @example * create stream in a dom node with id "chart", width is 500; height is 600px; * "chart", {"width": 500, "height": 600} */ var StreamComponent = DataV.extend(DataV.Chart, { initialize: function (node, options) { this.type = "Stream"; this.node = this.checkContainer(node); this.defaults = {}; // Properties this.defaults.offset = "zero";//zero, expand, silhou-ette, wiggle;(d3 stack offset) this.defaults.order = "default";//default, reverse, descending, ascending, inside-out(d3 stack order, sort by index of maximum value, then use balanced weighting.), inside-out-reverse(inside-out like, sort by index of maximum value, not descending but ascending); this.defaults.normalized = false;//false, true; //ratio data or not; //this.defaults.rowDataOrder = "default"; //default, descending, ascending(according to digitdata row sum value); this.defaults.columnNameUsed = "auto"; this.defaults.rowNameUsed = "auto"; this.defaults.pathLabel = true; this.defaults.fontSize = 12; this.defaults.colorCount = 20; //this.defaults.axisTickNumber = 8; // axis ticks number this.defaults.indexMargin = 3; // if dates.length < indexMargin * 2 + 1, do not show label this.timeRange = []; // paper this.defaults.width = 800; this.defaults.height = 560;//if only width has value and autoHeight is true, then height will be width * heightWidthRatio. this.defaults.autoHeight = true; this.defaults.heightWidthRatio = 0.6; this.defaults.legendPosition = "top";//"top", "left" this.defaults.topLegendHeight = 50; this.defaults.leftLegendWidth = 150; this.defaults.showLegend = true; this.defaults.legendBesidesWidth = undefined; this.defaults.legendBesidesHeight = undefined; this.defaults.more = false; this.defaults.moreLabel = "more"; this.defaults.max = 20; this.defaults.level = 0; this.defaults.chartWidth = undefined;//depends on width, do not recommend to change this.defaults.chartHeight = undefined;// depends on height, do not recommend to change this.defaults.naviHeight = 20;//do not recommend to change this.defaults.showNavi = undefined;//ture if moreConfig.more == true, else false; this.defaults.axisHeight = 30;//do not recommend to change this.defaults.showAxis = true; this.defaults.showPercentage = undefined;//true if moreConfig.more == true, else false; this.defaults.percentageWidth = 40; this.defaults.customEventHandle = {"mousemove": null}; this.defaults.tipStyle = {}; this.setOptions(options); } }); StreamComponent.prototype.init = function () { var that = this; var getBack = function () { var naviCallBack = function () { that.cover.hidden(); if (typeof that.cover.mouse !== 'undefined') { that.hoverLine.show(); that.tip.show(); $(that.paper.canvas).trigger("mousemove",[that.cover.mouse.x, that.cover.mouse.y]); that.cover.mouse = undefined; } that.pathLabel.show(); }; that.cover.show(); that.cover.mouse = undefined; that.processData("slicedData"); that.render("renderComponents"); //hidden that.hoverLine.hidden(); that.tip.hidden(); that.pathLabel.hidden(); that.paths.forEach(function (d) { d.attr({transform: "s1,0.001,0,0"}); d.animate({transform: "t0,0"}, 750, "linear", naviCallBack); }); }; that.on('changeLevelTo', function (level) { that.defaults.level = level; getBack(that.defaults.moreConfig.level); }); that.on('back', function () { that.defaults.level = that.defaults.level - 1; getBack(that.defaults.level); }); that.legend.on('hoverIn', function (index) { that.stream.highlight(index); }).on('hoverOut', function (index) { that.stream.lowlight(index); }); that.stream.on('enter', function () { that.axis.showTab(); that.tip.show(); }).on('leave', function (index) { that.axis.hideTab(); that.tip.hidden(); if (index !== undefined) { that.legend.lowlight(index); } }).on('move', function (pre, rowIndex, columnIndex) { if (pre !== undefined) { that.legend.lowlight(pre); } if (typeof rowIndex === "undefined" || typeof columnIndex === "undefined") { return; } that.legend.highlight(rowIndex); that.tip.setContent(rowIndex, columnIndex); //axis pop bubble that.axis.refreshTab(columnIndex); }).on('level_changed', function (start, end, needMore) { that.legend.fire('level_changed', start, end, needMore); }); }; StreamComponent.prototype.setSource = function (source, map) { this.source = source; this.map = map; }; StreamComponent.prototype.layout = function () { var conf = this.defaults; if (!conf.showLegend) { conf.legendBesidesWidth = conf.width; conf.legendBesidesHeight = conf.height; } else { if (conf.legendPosition === "left") { conf.legendBesidesWidth = conf.width - conf.leftLegendWidth; conf.legendBesidesHeight = conf.height; } else { conf.legendBesidesWidth = conf.width; conf.legendBesidesHeight = conf.height - conf.topLegendHeight; } } conf.chartWidth = conf.legendBesidesWidth - 2 * conf.percentageWidth; conf.chartHeight = conf.legendBesidesHeight - (conf.showNavi ? conf.naviHeight : 0) - (conf.showAxis ? conf.axisHeight : 0); var node = $(this.node).css({ position: "relative", width: conf.width }); // 创建DOM节点 this.streamBox = $("<div></div>").addClass("stream"); this.legendBox = $("<div></div>").addClass("legend"); this.axisBox = $("<div></div>").addClass("axis"); this.naviBox = $("<div></div>").addClass("navi"); this.percentageBox = $("<div></div>").addClass("percentage"); this.container = $("<div></div>").addClass("container"); this.rightBox = $("<div></div>").addClass("right"); // cover can block stream paper when animating to prevent some default mouse event this.coverBox = $("<div></div>").addClass("cover"); // 插入DOM this.streamBox.append(this.coverBox); this.container.append(this.percentageBox).append(this.streamBox); this.rightBox.append(this.naviBox).append(this.container).append(this.axisBox); node.append(this.legendBox).append(this.rightBox); // 设置各个节点大小 this.streamBox.css({ "position": "relative", "float": "left", "width": conf.chartWidth, "height": conf.chartHeight }); this.percentageBox.css({ }); this.container.css({ "height": conf.chartHeight }); this.rightBox.css({ "float": "right", "width": conf.legendBesidesWidth }); this.legendBox.css({ "width": conf.leftLegendWidth - 4, "float": "left", "overflowX": "hidden" }); }; StreamComponent.prototype.draw = function () { var conf = this.defaults; //chart and paper this.stream = this.own(new Stream(this.streamBox, {"width": conf.chartWidth, "height": conf.chartHeight})); this.stream.setSource(this.source, this.map); this.stream.render(); this.legend = this.own(new Legend.Legend(this.legendBox)); this.legend.setOptions({ "colorFunc": this.stream.getColor() }); this.legend.setSource(this.source, this.map); this.legend.render(); this.percentage = this.own(new Percentage(this.percentageBox)); this.percentage.setSource(this.source, this.map); this.percentage.render(); this.axis = this.own(new Axis(this.axisBox)); this.axis.setSource(this.source, this.map); this.axis.render(); this.navi = this.own(new Navi(this.naviBox)); this.navi.render(); // cover can block stream paper when animating to prevent some default mouse event this.cover = this.own(new Cover(this.coverBox)); //floatTag this.tip = this.own(new Tip(this.streamBox)); this.tip.setSource(this.source, this.map); this.tip.render(); }; StreamComponent.prototype.render = function () { this.layout(); this.draw(); this.init(); }; StreamComponent.prototype.setCustomEvent = function (eventName, callback) { this.defaults.customEventHandle[eventName] = callback; }; /*! * 导出StreamComponent */ return StreamComponent; });
var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var content; function readFileIfRequired(cb) { if (!content) { //<co id="callout-globals-nexttick-3-1" /> fs.readFile(__filename, 'utf8', function(err, data) { content = data; console.log('readFileIfRequired: readFile'); cb(err, content); }); } else { process.nextTick(function() { //<co id="callout-globals-nexttick-3-2" /> console.log('readFileIfRequired: cached'); cb(null, content); }); } } readFileIfRequired(function(err, data) { //<co id="callout-globals-nexttick-3-3" /> console.log('1. Length:', data.length); readFileIfRequired(function(err, data2) { console.log('2. Length:', data2.length); }); console.log('Reading file again...'); }); console.log('Reading file...');
function* f1() { a = (yield) ? 1 : 1; a = yield 1 ? 1 : 1; a = (yield 1) ? 1 : 1; a = 1 ? yield : yield; a = 1 ? yield 1 : yield 1; } function* f2() { a = yield* 1 ? 1 : 1; a = (yield* 1) ? 1 : 1; a = 1 ? yield* 1 : yield* 1; } async function f3() { a = await 1 ? 1 : 1; a = (await 1) ? 1 : 1; a = 1 ? await 1 : await 1; }
import React from 'react'; import PropTypes from 'prop-types'; const Soon = () => ( <div> <article className="glitch"> <span>ALWAYS Ɐ WIP</span> </article> </div> ); export default Soon;
module.exports = { rules: { 'max-nested-callbacks': 0 } };
function setup() { createCanvas(600, 400); noLoop(); noStroke(); textSize(20); loadJSON("data.json", drawData); } function draw() { background(255, 0, 0); console.log(int(random(0, 2))); } function drawData(data) { background(120, 180, 200); // person 1 bubble fill(155, 30, 180, 180); ellipse(250, 200, data.person1.age * 5, data.person1.age * 5); // person1.age = 30 fill(255); text(data.person1.name, 210, 200); // person1.name = Morgan // person 2 bubble fill(180, 180, 34, 180); ellipse(350, 200, data.person2.age * 5, data.person2.age * 5); // person2.age = 32 fill(255); text(data.person2.name, 330, 200); // person2.name = Joss }
version https://git-lfs.github.com/spec/v1 oid sha256:c2c3856c7f168c79af5e259afd0648e280f99384ba53df89f67814f2bafd5c74 size 18348
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;e.define("select2/i18n/hu",[],function(){return{errorLoading:function(){return"Az eredmények betöltése nem sikerült."},inputTooLong:function(e){return"Túl hosszú. "+(e.input.length-e.maximum)+" karakterrel több, mint kellene."},inputTooShort:function(e){return"Túl rövid. Még "+(e.minimum-e.input.length)+" karakter hiányzik."},loadingMore:function(){return"Töltés…"},maximumSelected:function(e){return"Csak "+e.maximum+" elemet lehet kiválasztani."},noResults:function(){return"Nincs találat."},searching:function(){return"Keresés…"}}}),e.define,e.require}();
'use strict'; /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive or negative) of `limit`. * * @param {Array|string} input Source array or string to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.numLimit = 3; $scope.letterLimit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="integer" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> </div> </doc:source> <doc:protractor> var numLimitInput = element(by.model('numLimit')); var letterLimitInput = element(by.model('letterLimit')); var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); it('should limit the number array to first three items', function() { expect(numLimitInput.getAttribute('value')).toBe('3'); expect(letterLimitInput.getAttribute('value')).toBe('3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); expect(limitedLetters.getText()).toEqual('Output letters: abc'); }); it('should update the output when -3 is entered', function() { numLimitInput.clear(); numLimitInput.sendKeys('-3'); letterLimitInput.clear(); letterLimitInput.sendKeys('-3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: ghi'); }); it('should not exceed the maximum size of input array', function() { numLimitInput.clear(); numLimitInput.sendKeys('100'); letterLimitInput.clear(); letterLimitInput.sendKeys('100'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); }); </doc:protractor> </doc:example> */ function limitToFilter(){ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; limit = int(limit); if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; } } var out = [], i, n; // if abs(limit) exceeds maximum length, trim it if (limit > input.length) limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i<n; i++) { out.push(input[i]); } return out; }; }
'use strict'; const expect = require('chai').expect; const LiveReloadServer = require('../../../../lib/tasks/server/livereload-server'); const MockUI = require('console-ui/mock'); const MockExpressServer = require('../../../helpers/mock-express-server'); const net = require('net'); const EOL = require('os').EOL; const path = require('path'); const MockWatcher = require('../../../helpers/mock-watcher'); const express = require('express'); const FSTree = require('fs-tree-diff'); const http = require('http'); describe('livereload-server', function() { let subject; let ui; let watcher; let httpServer; let app; beforeEach(function() { ui = new MockUI(); watcher = new MockWatcher(); httpServer = new MockExpressServer(); app = express(); subject = new LiveReloadServer({ app, ui, watcher, httpServer, analytics: { trackError() {} }, project: { liveReloadFilterPatterns: [], root: '/home/user/my-project', }, }); }); afterEach(function() { try { if (subject.liveReloadServer) { subject.liveReloadServer.close(); } } catch (err) { /* ignore */ } }); describe('start', function() { it('does not start the server if `liveReload` option is not true', function() { return subject .setupMiddleware({ liveReload: false, liveReloadPort: 4200, liveReloadPrefix: '/', }) .then(function() { expect(ui.output).to.contains('WARNING: Livereload server manually disabled.'); expect(!!subject.liveReloadServer).to.equal(false); }); }); it('informs of error during startup with custom port', function(done) { let preexistingServer = net.createServer(); preexistingServer.listen(1337); subject .setupMiddleware({ liveReload: true, liveReloadPort: 1337, liveReloadPrefix: '/', port: 4200, }) .catch(function(reason) { expect(reason).to.equal( `Livereload failed on http://localhost:1337. It is either in use or you do not have permission.` ); }) .finally(function() { preexistingServer.close(done); }); }); it('starts with custom host, custom port', function() { return subject .setupMiddleware({ liveReloadHost: '127.0.0.1', liveReload: true, liveReloadPort: 1377, liveReloadPrefix: '/', port: 4200, }) .then(function() { expect(subject.liveReloadServer.options.port).to.equal(1377); expect(subject.liveReloadServer.options.host).to.equal('127.0.0.1'); }); }); it('Livereload responds to livereload requests and returns livereload file', function(done) { let server = app.listen(4200); subject .setupMiddleware({ liveReload: true, liveReloadPrefix: '_lr', port: 4200, }) .then(function() { http.get('http://localhost:4200/_lr/livereload.js', function(response) { expect(response.statusCode).to.equal(200); server.close(done); }); }); }); }); describe('start with https', function() { it('correctly runs in https mode', function() { return subject .setupMiddleware({ liveReload: true, liveReloadPort: 4200, liveReloadPrefix: '/', ssl: true, sslKey: 'tests/fixtures/ssl/server.key', sslCert: 'tests/fixtures/ssl/server.crt', port: 4200, }) .then(function() { expect(subject.liveReloadServer.options.key).to.be.an.instanceof(Buffer); expect(subject.liveReloadServer.options.cert).to.be.an.instanceof(Buffer); }); }); it('informs of error during startup', function(done) { let preexistingServer = net.createServer(); preexistingServer.listen(1337); subject .setupMiddleware({ liveReloadPort: 1337, liveReload: true, ssl: true, sslKey: 'tests/fixtures/ssl/server.key', sslCert: 'tests/fixtures/ssl/server.crt', port: 4200, }) .catch(function(reason) { expect(reason).to.equal( `Livereload failed on https://localhost:1337. It is either in use or you do not have permission.` ); }) .finally(function() { preexistingServer.close(done); }); }); it('correctly runs in https mode with custom port', function() { return subject .setupMiddleware({ liveReload: true, liveReloadPort: 1337, liveReloadPrefix: '/', ssl: true, sslKey: 'tests/fixtures/ssl/server.key', sslCert: 'tests/fixtures/ssl/server.crt', port: 4200, }) .then(function() { expect(subject.liveReloadServer.options.key).to.be.an.instanceof(Buffer); expect(subject.liveReloadServer.options.cert).to.be.an.instanceof(Buffer); }); }); }); describe('express server restart', function() { it('triggers when the express server restarts', function() { let calls = 0; subject.didRestart = function() { calls++; }; return subject .setupMiddleware({ liveReload: true, liveReloadPrefix: '/', port: 4200, }) .then(function() { subject.app.emit('restart'); expect(calls).to.equal(1); }); }); it('triggers when the express server restarts with custom port', function() { let calls = 0; subject.didRestart = function() { calls++; }; return subject .setupMiddleware({ liveReload: true, liveReloadPrefix: '/', liveReloadPort: 1337, port: 4200, }) .then(function() { subject.app.emit('restart'); expect(calls).to.equal(1); }); }); }); describe('livereload changes', function() { let liveReloadServer; let changedCount; let oldChanged; let stubbedChanged = function() { changedCount += 1; }; let trackCount; let oldTrack; let stubbedTrack = function() { trackCount += 1; }; let createStubbedGetDirectoryEntries = function(files) { return function() { return files.map(function(file) { return { relativePath: file, isDirectory() { return false; }, }; }); }; }; beforeEach(function() { subject.setupMiddleware({ liveReload: true, liveReloadPort: 4200, liveReloadPrefix: '/', port: 4200, }); liveReloadServer = subject.liveReloadServer; changedCount = 0; oldChanged = liveReloadServer.changed; liveReloadServer.changed = stubbedChanged; trackCount = 0; oldTrack = subject.analytics.track; subject.analytics.track = stubbedTrack; subject.tree = FSTree.fromEntries([]); }); afterEach(function() { liveReloadServer.changed = oldChanged; subject.analytics.track = oldTrack; subject.project.liveReloadFilterPatterns = []; }); describe('watcher events', function() { function watcherEventTest(eventName, expectedCount) { subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); subject.project.liveReloadFilterPatterns = []; watcher.emit(eventName, { directory: '/home/user/projects/my-project/tmp/something.tmp', }); return expect(changedCount).to.equal(expectedCount); } it('triggers a livereload change on a watcher change event', function() { return watcherEventTest('change', 1); }); it('triggers a livereload change on a watcher error event', function() { return watcherEventTest('error', 1); }); it('does not trigger a livereload change on other watcher events', function() { return watcherEventTest('not-an-event', 0); }); it('recovers from error when file is already cached in previous cache step', function() { let compileError = function() { try { throw new Error('Compile time error'); } catch (error) { return error; } }.apply(); subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); watcher.emit('error', compileError); expect(subject._hasCompileError).to.be.true; expect(changedCount).to.equal(1); watcher.emit('change', { directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(subject._hasCompileError).to.be.false; expect(changedCount).to.equal(2); }); describe('filter pattern', function() { it('shouldTriggerReload must be true if there are no liveReloadFilterPatterns', function() { subject.project.liveReloadFilterPatterns = []; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is true when no liveReloadFilterPatterns matches the filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is false when one or more of the liveReloadFilterPatterns matches filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(result).to.be.false; }); it('shouldTriggerReload writes a banner after skipping reload for a file', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(ui.output).to.equal( `Skipping livereload for: ${path.join('test', 'fixtures', 'proxy', 'file-a.js')}${EOL}` ); }); it('triggers the livereload server of a change when no pattern matches', function() { subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(1); expect(trackCount).to.equal(1); }); it('does not trigger livereload server of a change when there is a pattern match', function() { // normalize test regex for windows // path.normalize with change forward slashes to back slashes if test is running on windows // we then replace backslashes with double backslahes to escape the backslash in the regex let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(0); expect(trackCount).to.equal(0); }); }); }); describe('specific files', function() { let reloadedFiles; let stubbedChanged = function(options) { reloadedFiles = options.body.files; }; beforeEach(function() { liveReloadServer.changed = stubbedChanged; }); afterEach(function() { reloadedFiles = undefined; }); it('triggers livereload with modified files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); }); it('triggers livereload with deleted directories', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); // Pretend every files were removed from the tree. subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal([]); }); it('triggers livereload ignoring source map files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.css.map']; let expectedResult = ['assets/my-project.css']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(expectedResult); }); it('triggers livereload with "LiveReload files" if no results.directory was provided', function() { let changedOptions; subject.liveReloadServer = { changed(options) { changedOptions = options; }, }; subject.didChange({}); expect(changedOptions).to.deep.equal({ body: { files: ['LiveReload files'], }, }); }); }); }); describe('livereload changes with custom port', function() { let liveReloadServer; let changedCount; let oldChanged; let stubbedChanged = function() { changedCount += 1; }; let trackCount; let oldTrack; let stubbedTrack = function() { trackCount += 1; }; let createStubbedGetDirectoryEntries = function(files) { return function() { return files.map(function(file) { return { relativePath: file, isDirectory() { return false; }, }; }); }; }; beforeEach(function() { subject.setupMiddleware({ liveReload: true, liveReloadPort: 1337, liveReloadPrefix: '/', port: 4200, }); liveReloadServer = subject.liveReloadServer; changedCount = 0; oldChanged = liveReloadServer.changed; liveReloadServer.changed = stubbedChanged; trackCount = 0; oldTrack = subject.analytics.track; subject.analytics.track = stubbedTrack; subject.tree = FSTree.fromEntries([]); }); afterEach(function() { liveReloadServer.changed = oldChanged; subject.analytics.track = oldTrack; subject.project.liveReloadFilterPatterns = []; }); describe('watcher events', function() { function watcherEventTest(eventName, expectedCount) { subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); subject.project.liveReloadFilterPatterns = []; watcher.emit(eventName, { directory: '/home/user/projects/my-project/tmp/something.tmp', }); return expect(changedCount).to.equal(expectedCount); } it('triggers a livereload change on a watcher change event', function() { return watcherEventTest('change', 1); }); it('triggers a livereload change on a watcher error event', function() { return watcherEventTest('error', 1); }); it('does not trigger a livereload change on other watcher events', function() { return watcherEventTest('not-an-event', 0); }); it('recovers from error when file is already cached in previous cache step', function() { let compileError = function() { try { throw new Error('Compile time error'); } catch (error) { return error; } }.apply(); subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); watcher.emit('error', compileError); expect(subject._hasCompileError).to.be.true; expect(changedCount).to.equal(1); watcher.emit('change', { directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(subject._hasCompileError).to.be.false; expect(changedCount).to.equal(2); }); describe('filter pattern', function() { it('shouldTriggerReload must be true if there are no liveReloadFilterPatterns', function() { subject.project.liveReloadFilterPatterns = []; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is true when no liveReloadFilterPatterns matches the filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is false when one or more of the liveReloadFilterPatterns matches filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(result).to.be.false; }); it('shouldTriggerReload writes a banner after skipping reload for a file', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(ui.output).to.equal( `Skipping livereload for: ${path.join('test', 'fixtures', 'proxy', 'file-a.js')}${EOL}` ); }); it('triggers the livereload server of a change when no pattern matches', function() { subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(1); expect(trackCount).to.equal(1); }); it('does not trigger livereload server of a change when there is a pattern match', function() { // normalize test regex for windows // path.normalize with change forward slashes to back slashes if test is running on windows // we then replace backslashes with double backslahes to escape the backslash in the regex let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(0); expect(trackCount).to.equal(0); }); }); }); describe('specific files', function() { let reloadedFiles; let changedOptions; let stubbedChanged = function(options) { reloadedFiles = options.body.files; changedOptions = options; }; beforeEach(function() { liveReloadServer.changed = stubbedChanged; }); afterEach(function() { reloadedFiles = undefined; }); it('triggers livereload with modified files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); }); it('triggers livereload with deleted directories', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); // Pretend every files were removed from the tree. subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal([]); }); it('triggers livereload ignoring source map files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.css.map']; let expectedResult = ['assets/my-project.css']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(expectedResult); }); it('triggers livereload with "LiveReload files" if no results.directory was provided', function() { subject.didChange({}); expect(changedOptions).to.deep.equal({ body: { files: ['LiveReload files'], }, }); }); }); }); });
"use strict"; var chokidar = require("chokidar"), shell = require("shelljs"), files = { "./src/pages/schema-edit/parse-schema.js" : "./gen/parse-schema.js" }; exports.watch = function() { // Make sure files stay up to date in the /gen folder chokidar.watch(Object.keys(files)).on("all", function(event, file) { if(event !== "add" && event !== "change") { return; } file = "./" + file; shell.cp(file, files[file]); }); }; exports.copy = function() { Object.keys(files).forEach(function(file) { shell.cp(file, files[file]); }); };
// Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self == 'object' && self.self === self && self || typeof global == 'object' && global.global === global && global || this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeCreate = Object.create; // Naked function reference for surrogate-prototype-swapping. var Ctor = function(){}; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for their old module API. If we're in // the browser, add `_` as a global object. // (`nodeType` is checked to ensure that `module` // and `exports` are not HTML elements.) if (typeof exports != 'undefined' && !exports.nodeType) { if (typeof module != 'undefined' && !module.nodeType && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.8.3'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var optimizeCb = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; // The 2-parameter case has been omitted only because no current consumers // made use of it. case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // An internal function to generate callbacks that can be applied to each // element in a collection, returning the desired result — either `identity`, // an arbitrary callback, a property matcher, or a property accessor. var cb = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value)) return _.matcher(value); return _.property(value); }; // An external wrapper for the internal callback generator _.iteratee = function(value, context) { return cb(value, context, Infinity); }; // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. var restArgs = function(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); case 2: return func.call(this, arguments[0], arguments[1], rest); } var args = Array(startIndex + 1); for (index = 0; index < startIndex; index++) { args[index] = arguments[index]; } args[startIndex] = rest; return func.apply(this, args); }; }; // An internal function for creating a new object that inherits from another. var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; }; var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; // Helper for collection methods to determine whether a collection // should be iterated as an array or as an object. // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; var getLength = property('length'); var isArrayLike = function(collection) { var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Create a reducing function iterating left or right. var createReduce = function(dir) { // Wrap code that reassigns argument variables in a separate function than // the one that accesses `arguments.length` to avoid a perf hit. (#1991) var reducer = function(obj, iteratee, memo, initial) { var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; if (!initial) { memo = obj[keys ? keys[index] : index]; index += dir; } for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; return function(obj, iteratee, memo, context) { var initial = arguments.length >= 3; return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); }; }; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = createReduce(1); // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = createReduce(-1); // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var key; if (isArrayLike(obj)) { key = _.findIndex(obj, predicate, context); } else { key = _.findKey(obj, predicate, context); } if (key !== void 0 && key !== -1) return obj[key]; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; predicate = cb(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given item (using `===`). // Aliased as `includes` and `include`. _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { if (!isArrayLike(obj)) obj = _.values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return _.indexOf(obj, item, fromIndex) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = restArgs(function(obj, method, args) { var isFunc = _.isFunction(method); return _.map(obj, function(value) { var func = isFunc ? method : value[method]; return func == null ? func : func.apply(value, args); }); }); // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value > result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = v; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value < result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = v; lastComputed = computed; } }); } return result; }; // Shuffle a collection. _.shuffle = function(obj) { return _.sample(obj, Infinity); }; // Sample **n** random values from a collection using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj); var length = getLength(sample); n = Math.max(Math.min(n, length), 0); var last = length - 1; for (var index = 0; index < n; index++) { var rand = _.random(index, last); var temp = sample[index]; sample[index] = sample[rand]; sample[rand] = temp; } return sample.slice(0, n); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { var index = 0; iteratee = cb(iteratee, context); return _.pluck(_.map(obj, function(value, key, list) { return { value: value, index: index++, criteria: iteratee(value, key, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior, partition) { return function(obj, iteratee, context) { var result = partition ? [[], []] : {}; iteratee = cb(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (_.isString(obj)) { // Keep surrogate pair characters together return obj.match(reStrSymbol); } if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = group(function(result, value, pass) { result[pass ? 0 : 1].push(value); }, true); // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; return _.initial(array, array.length - n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return _.rest(array, Math.max(0, array.length - n)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { output = output || []; var idx = output.length; for (var i = 0, length = getLength(input); i < length; i++) { var value = input[i]; if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { // Flatten current level of array or arguments object if (shallow) { var j = 0, len = value.length; while (j < len) output[idx++] = value[j++]; } else { flatten(value, shallow, strict, output); idx = output.length; } } else if (!strict) { output[idx++] = value; } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false); }; // Return a version of the array that does not contain the specified value(s). _.without = restArgs(function(array, otherArrays) { return _.difference(array, otherArrays); }); // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!_.contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!_.contains(result, value)) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = restArgs(function(arrays) { return _.uniq(flatten(arrays, true, true)); }); // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; var j; for (j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = restArgs(function(array, rest) { rest = flatten(rest, true, true); return _.filter(array, function(value){ return !_.contains(rest, value); }); }); // Complement of _.zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices _.unzip = function(array) { var length = array && _.max(array, getLength).length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = restArgs(_.unzip); // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Generator function to create the findIndex and findLastIndex functions var createPredicateIndexFinder = function(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; }; // Returns the first index on an array-like that passes a predicate test _.findIndex = createPredicateIndexFinder(1); _.findLastIndex = createPredicateIndexFinder(-1); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Generator function to create the indexOf and lastIndexOf functions var createIndexFinder = function(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), _.isNaN); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } if (!step) { step = stop < start ? -1 : 1; } var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Split an **array** into several arrays containing **count** or less elements // of initial array _.chunk = function(array, count) { if (count == null || count < 1) return []; var result = []; var i = 0, length = array.length; while (i < length) { result.push(slice.call(array, i, i += count)); } return result; }; // Function (ahem) Functions // ------------------ // Determines whether to execute a function as a constructor // or a normal function with the provided arguments var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (_.isObject(result)) return result; return self; }; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = restArgs(function(func, context, args) { if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); var bound = restArgs(function(callArgs) { return executeBound(func, bound, context, this, args.concat(callArgs)); }); return bound; }); // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder by default, allowing any combination of arguments to be // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. _.partial = restArgs(function(func, boundArgs) { var placeholder = _.partial.placeholder; var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }); _.partial.placeholder = _; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = restArgs(function(obj, keys) { keys = flatten(keys, false, false); var index = keys.length; if (index < 1) throw new Error('bindAll must be passed function names'); while (index--) { var key = keys[index]; obj[key] = _.bind(obj[key], obj); } }); // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = restArgs(function(func, wait, args) { return setTimeout(function() { return func.apply(null, args); }, wait); }); // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = _.partial(_.delay, _, 1); // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var timeout, context, args, result; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; var throttled = function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; throttled.cancel = function() { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; return throttled; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, result; var later = function(context, args) { timeout = null; if (args) result = func.apply(context, args); }; var debounced = restArgs(function(args) { var callNow = immediate && !timeout; if (timeout) clearTimeout(timeout); if (callNow) { timeout = setTimeout(later, wait); result = func.apply(this, args); } else if (!immediate) { timeout = _.delay(later, wait, this, args); } return result; }); debounced.cancel = function() { clearTimeout(timeout); timeout = null; }; return debounced; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed on and after the Nth call. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed up to (but not including) the Nth call. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); _.restArgs = restArgs; // Object Functions // ---------------- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; var collectNonEnumProps = function(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = _.isFunction(constructor) && constructor.prototype || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { keys.push(prop); } } }; // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve all the property names of an object. _.allKeys = function(obj) { if (!_.isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Returns the results of applying the iteratee to each element of the object // In contrast to _.map it returns an object _.mapObject = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = _.keys(obj), length = keys.length, results = {}; for (var index = 0; index < length; index++) { var currentKey = keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // An internal function for creating assigner functions. var createAssigner = function(keysFunc, defaults) { return function(obj) { var length = arguments.length; if (defaults) obj = Object(obj); if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!defaults || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; }; // Extend a given object with all the properties in passed-in object(s). _.extend = createAssigner(_.allKeys); // Assigns a given object with all the own properties in the passed-in object(s) // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) _.extendOwn = _.assign = createAssigner(_.keys); // Returns the first key on an object that passes a predicate test _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = _.keys(obj), key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (predicate(obj[key], key, obj)) return key; } }; // Internal pick helper function to determine if `obj` has key `key`. var keyInObj = function(value, key, obj) { return key in obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = restArgs(function(obj, keys) { var result = {}, iteratee = keys[0]; if (obj == null) return result; if (_.isFunction(iteratee)) { if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); keys = _.allKeys(obj); } else { iteratee = keyInObj; keys = flatten(keys, false, false); obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }); // Return a copy of the object without the blacklisted properties. _.omit = restArgs(function(obj, keys) { var iteratee = keys[0], context; if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); if (keys.length > 1) context = keys[1]; } else { keys = _.map(flatten(keys, false, false), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }); // Fill in a given object with default properties. _.defaults = createAssigner(_.allKeys, true); // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. _.create = function(prototype, props) { var result = baseCreate(prototype); if (props) _.extendOwn(result, props); return result; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Returns whether an object has a given set of `key:value` pairs. _.isMatch = function(object, attrs) { var keys = _.keys(attrs), length = keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; }; // Internal recursive comparison function for `isEqual`. var eq, deepEq; eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // `NaN`s are equivalent, but non-reflexive. if (a !== a) return b !== b; // Exhaust primitive checks var type = typeof a; if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; return deepEq(a, b, aStack, bStack); }; // Internal recursive comparison function for `isEqual`. deepEq = function(a, b, aStack, bStack) { // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } var areArrays = className === '[object Array]'; if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // Deep compare objects. var keys = _.keys(a), key; length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (_.keys(b).length !== length) return false; while (length--) { // Deep compare each member key = keys[length]; if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). var nodelist = root.document && root.document.childNodes; if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? _.isNaN = function(obj) { return _.isNumber(obj) && isNaN(obj); }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; // Predicate-generating functions. Often useful outside of Underscore. _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = property; // Generates a function for a given object that returns a given property. _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. _.matcher = _.matches = function(attrs) { attrs = _.extendOwn({}, attrs); return function(obj) { return _.isMatch(obj, attrs); }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, prop, fallback) { var value = object == null ? void 0 : object[prop]; if (value === void 0) { value = fallback; } return _.isFunction(value) ? value.call(object) : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escapeRegExp, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offset. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; var render; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var chainResult = function(instance, obj) { return instance._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return chainResult(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return chainResult(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return chainResult(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxy for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return '' + this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define == 'function' && define.amd) { define('underscore', [], function() { return _; }); } }());
// moment.js locale configuration // locale : Marathi (mr) // author : Harshad Kale : https://github.com/kalehv (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.defineLocale('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'), weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), longDateFormat : { LT : 'A h:mm वाजता', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, LT', LLLL : 'dddd, D MMMM YYYY, LT' }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s नंतर', past : '%s पूर्वी', s : 'सेकंद', m: 'एक मिनिट', mm: '%d मिनिटे', h : 'एक तास', hh : '%d तास', d : 'एक दिवस', dd : '%d दिवस', M : 'एक महिना', MM : '%d महिने', y : 'एक वर्ष', yy : '%d वर्षे' }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'रात्री'; } else if (hour < 10) { return 'सकाळी'; } else if (hour < 17) { return 'दुपारी'; } else if (hour < 20) { return 'सायंकाळी'; } else { return 'रात्री'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); }));
// Call spamassassin via spamd var sock = require('./line_socket'); var prettySize = require('./utils').prettySize; var defaults = { spamd_socket: 'localhost:783', max_size: 500000, old_headers_action: "rename", subject_prefix: "*** SPAM ***", }; exports.hook_data_post = function (next, connection) { var plugin = this; var config = this.config.get('spamassassin.ini'); setup_defaults(config); if (msg_too_big(config, connection, plugin)) return next(); var username = get_spamd_username(config, connection); var headers = get_spamd_headers(connection, username); var socket = get_spamd_socket(config, next, connection, plugin); socket.is_connected = false; var results_timeout = parseInt(config.main.results_timeout) || 300; socket.on('connect', function () { this.is_connected = true; // Reset timeout this.setTimeout(results_timeout * 1000); socket.write(headers.join("\r\n")); connection.transaction.message_stream.pipe(socket); }); var spamd_response = { headers: {} }; var state = 'line0'; var last_header; socket.on('line', function (line) { connection.logprotocol(plugin, "Spamd C: " + line); line = line.replace(/\r?\n/, ''); if (state === 'line0') { spamd_response.line0 = line; state = 'response'; } else if (state === 'response') { if (line.match(/\S/)) { var matches; if (matches = line.match(/Spam: (True|False) ; (-?\d+\.\d) \/ (-?\d+\.\d)/)) { spamd_response.flag = matches[1]; spamd_response.score = matches[2]; spamd_response.hits = matches[2]; // backwards compat spamd_response.reqd = matches[3]; spamd_response.flag = spamd_response.flag === 'True' ? 'Yes' : 'No'; } } else { state = 'headers'; } } else if (state === 'headers') { var m; // printable ASCII: [ -~] if (m = line.match(/^X-Spam-([ -~]+):(.*)/)) { // connection.logdebug(plugin, "header: " + line); last_header = m[1]; spamd_response.headers[m[1]] = m[2]; return; } var fold; if (last_header && (fold = line.match(/^(\s+.*)/))) { spamd_response.headers[last_header] += "\r\n" + fold[1]; return; } last_header = ''; } }); socket.on('end', function () { // Abort if the transaction is gone if (!connection.transaction) return next(); if (spamd_response.headers['Tests']) { spamd_response.tests = spamd_response.headers['Tests']; } if (spamd_response.tests === undefined) { // strip the 'tests' from the X-Spam-Status header var tests; if (spamd_response.headers['Status'] && tests = /tests=([^ ]+)/.exec(spamd_response.headers['Status'].replace(/\r?\n\t/g,''))) { spamd_response.tests = tests[1]; } } // do stuff with the results... connection.transaction.notes.spamassassin = spamd_response; plugin.fixup_old_headers(config.main.old_headers_action, connection.transaction); plugin.do_header_updates(connection, spamd_response, config); log_results(connection, plugin, spamd_response, config); var exceeds_err = score_too_high(config, connection, spamd_response); if (exceeds_err) return next(DENY, exceeds_err); munge_subject(connection, config, spamd_response.score); return next(); }); }; exports.fixup_old_headers = function (action, transaction) { var plugin = this; var headers = transaction.notes.spamassassin.headers; switch (action) { case "keep": break; case "drop": for (var key in headers) { if (!key) continue; transaction.remove_header('X-Spam-' + key); } break; case "rename": default: for (var key in headers) { if (!key) continue; key = 'X-Spam-' + key; var old_val = transaction.header.get(key); transaction.remove_header(key); if (old_val) { // plugin.logdebug(plugin, "header: " + key + ', ' + old_val); transaction.add_header(key.replace(/^X-/, 'X-Old-'), old_val); } } break; } }; function munge_subject(connection, config, score) { var munge = config.main.munge_subject_threshold; if (!munge) return; if (parseFloat(score) < parseFloat(munge)) return; var subj = connection.transaction.header.get('Subject'); var subject_re = new RegExp('^' + config.main.subject_prefix); if (subject_re.test(subj)) return; // prevent double munge connection.transaction.remove_header('Subject'); connection.transaction.add_header('Subject', config.main.subject_prefix + " " + subj); }; function setup_defaults(config) { for (var key in defaults) { config.main[key] = config.main[key] || defaults[key]; } ['reject_threshold', 'relay_reject_threshold', 'munge_subject_threshold', 'max_size'].forEach(function (item) { if (!config.main[item]) return; config.main[item] = Number(config.main[item]); }); }; exports.do_header_updates = function (connection, spamd_response, config) { var plugin = this; if (spamd_response.flag === 'Yes') { // X-Spam-Flag is added by SpamAssassin connection.transaction.remove_header('precedence'); connection.transaction.add_header('Precedence', 'junk'); } var modern = config.main.modern_status_syntax; for (var key in spamd_response.headers) { if (!key || key === '' || key === undefined) continue; var val = spamd_response.headers[key]; if (val === undefined) { val = ''; } if (key === 'Status' && !modern) { var legacy = spamd_response.headers[key].replace(/ score=/,' hits='); connection.transaction.add_header('X-Spam-Status', legacy); continue; } connection.transaction.add_header('X-Spam-' + key, val); } }; function score_too_high(config, connection, spamd_response) { var score = spamd_response.score; if (connection.relaying) { var rmax = config.main.relay_reject_threshold; if (rmax && (score >= rmax)) { return "spam score exceeded relay threshold"; } }; var max = config.main.reject_threshold; if (max && (score >= max)) { return "spam score exceeded threshold"; } return; } function get_spamd_username(config, connection) { var user = connection.transaction.notes.spamd_user; // 1st priority if (user && user !== undefined) return user; if (!config.main.spamd_user) return 'default'; // when not defined user = config.main.spamd_user; // Enable per-user SA prefs if (user === 'first-recipient') { // special cases return connection.transaction.rcpt_to[0].address(); } if (user === 'all-recipients') { throw "Unimplemented"; // TODO: pass the message through SA for each recipient. Then apply // the least strict result to the connection. That is useful when // one user blacklists a sender that another user wants to get mail // from. If this is something you care about, this is the spot. } return user; } function get_spamd_headers(connection, username) { // http://svn.apache.org/repos/asf/spamassassin/trunk/spamd/PROTOCOL var headers = [ 'HEADERS SPAMC/1.3', 'User: ' + username, '', 'X-Envelope-From: ' + connection.transaction.mail_from.address(), 'X-Haraka-UUID: ' + connection.transaction.uuid, ]; if (connection.relaying) { headers.push('X-Haraka-Relay: true'); } return headers; } function get_spamd_socket(config, next, connection, plugin) { // TODO: support multiple spamd backends var socket = new sock.Socket(); if (config.main.spamd_socket.match(/\//)) { // assume unix socket socket.connect(config.main.spamd_socket); } else { var hostport = config.main.spamd_socket.split(/:/); socket.connect((hostport[1] || 783), hostport[0]); } var connect_timeout = parseInt(config.main.connect_timeout) || 30; socket.setTimeout(connect_timeout * 1000); socket.on('timeout', function () { if (!this.is_connected) { connection.logerror(plugin, 'connection timed out'); } else { connection.logerror(plugin, 'timeout waiting for results'); } socket.end(); return next(); }); socket.on('error', function (err) { connection.logerror(plugin, 'connection failed: ' + err); // TODO: optionally DENYSOFT // TODO: add a transaction note return next(); }); return socket; }; function msg_too_big(config, connection, plugin) { if (!config.main.max_size) return false; var size = connection.transaction.data_bytes; var max = config.main.max_size; if (size > max) { connection.loginfo(plugin, 'skipping, size ' + prettySize(size) + ' exceeds max: ' + prettySize(max)); return true; } return false; }; function log_results(connection, plugin, spamd_response, config) { connection.loginfo(plugin, "status=" + spamd_response.flag + ', score=' + spamd_response.score + ', required=' + spamd_response.reqd + ', reject=' + ((connection.relaying) ? (config.main.relay_reject_threshold || config.main.reject_threshold) : config.main.reject_threshold) + ', tests="' + spamd_response.tests + '"'); };
"use strict"; var _foob, _foob$test; var _toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); }; (_foob = foob).add.apply(_foob, [foo, bar].concat(_toArray(numbers))); (_foob$test = foob.test).add.apply(_foob$test, [foo, bar].concat(_toArray(numbers)));
import { useState } from 'react' import { useRouter } from 'next/router' import Link from 'next/link' import { gql, useMutation } from '@apollo/client' import { getErrorMessage } from '../lib/form' import Field from '../components/field' const SignUpMutation = gql` mutation SignUpMutation($email: String!, $password: String!) { signUp(input: { email: $email, password: $password }) { user { id email } } } ` function SignUp() { const [signUp] = useMutation(SignUpMutation) const [errorMsg, setErrorMsg] = useState() const router = useRouter() async function handleSubmit(event) { event.preventDefault() const emailElement = event.currentTarget.elements.email const passwordElement = event.currentTarget.elements.password try { await signUp({ variables: { email: emailElement.value, password: passwordElement.value, }, }) router.push('/signin') } catch (error) { setErrorMsg(getErrorMessage(error)) } } return ( <> <h1>Sign Up</h1> <form onSubmit={handleSubmit}> {errorMsg && <p>{errorMsg}</p>} <Field name="email" type="email" autoComplete="email" required label="Email" /> <Field name="password" type="password" autoComplete="password" required label="Password" /> <button type="submit">Sign up</button> or{' '} <Link href="/signin"> <a>Sign in</a> </Link> </form> </> ) } export default SignUp
const nest = require('depnest') const { h, Value } = require('mutant') exports.needs = nest({ 'app.sync.goTo': 'first', 'message.html.backlinks': 'first', 'message.html.author': 'first', 'message.html.meta': 'map', 'message.html.timestamp': 'first' }) exports.gives = nest('message.html.layout') exports.create = (api) => { return nest('message.html.layout', miniLayout) function miniLayout (msg, opts) { if (opts.layout !== 'mini') return var rawMessage = Value(null) return h('Message -mini', { attributes: { tabindex: '0' } }, [ h('section.timestamp', {}, api.message.html.timestamp(msg)), h('header.author', {}, api.message.html.author(msg, { size: 'mini' })), h('section.meta', {}, api.message.html.meta(msg, { rawMessage })), h('section.content', { 'ev-click': () => api.app.sync.goTo(msg) }, opts.content), h('section.raw-content', rawMessage) ]) } }
var gbxremote = require('gbxremote'), async = require('async'); module.exports = require('./core').extend({ init: function() { this._super(); this.options.port = 2350; this.options.port_query = 5000; this.gbxclient = false; }, reset: function() { this._super(); if(this.gbxclient) { this.gbxclient.terminate(); this.gbxclient = false; } }, run: function(state) { var self = this; var cmds = [ ['Connect'], ['Authenticate', this.options.login,this.options.password], ['GetStatus'], ['GetPlayerList',500,0], ['GetServerOptions'], ['GetCurrentChallengeInfo'], ['GetCurrentGameInfo'] ]; var results = []; async.eachSeries(cmds, function(cmdset,c) { var cmd = cmdset[0]; var params = cmdset.slice(1); if(cmd == 'Connect') { var client = self.gbxclient = gbxremote.createClient(self.options.port_query,self.options.host, function(err) { if(err) return self.fatal('GBX error '+JSON.stringify(err)); c(); }); client.on('error',function(){}); } else { self.gbxclient.methodCall(cmd, params, function(err, value) { if(err) return self.fatal('XMLRPC error '+JSON.stringify(err)); results.push(value); c(); }); } }, function() { var gamemode = ''; var igm = results[5].GameMode; if(igm == 0) gamemode="Rounds"; if(igm == 1) gamemode="Time Attack"; if(igm == 2) gamemode="Team"; if(igm == 3) gamemode="Laps"; if(igm == 4) gamemode="Stunts"; if(igm == 5) gamemode="Cup"; state.name = self.stripColors(results[3].Name); state.password = (results[3].Password != 'No password'); state.maxplayers = results[3].CurrentMaxPlayers; state.map = self.stripColors(results[4].Name); state.raw.gametype = gamemode; results[2].forEach(function(player) { state.players.push({name:self.stripColors(player.Name)}); }); self.finish(state); }); }, stripColors: function(str) { return str.replace(/\$([0-9a-f][^\$]?[^\$]?|[^\$]?)/g,''); } });
/** * Module dependencies. */ var http = require('http'); var read = require('fs').readFileSync; var parse = require('url').parse; var engine = require('engine.io'); var client = require('socket.io-client'); var clientVersion = require('socket.io-client/package').version; var Client = require('./client'); var Namespace = require('./namespace'); var Adapter = require('socket.io-adapter'); var debug = require('debug')('socket.io:server'); var url = require('url'); /** * Module exports. */ module.exports = Server; /** * Socket.IO client source. */ var clientSource = read(require.resolve('socket.io-client/socket.io.js'), 'utf-8'); /** * Server constructor. * * @param {http.Server|Number|Object} http server, port or options * @param {Object} options * @api public */ function Server(srv, opts){ if (!(this instanceof Server)) return new Server(srv, opts); if ('object' == typeof srv && !srv.listen) { opts = srv; srv = null; } opts = opts || {}; this.nsps = {}; this.path(opts.path || '/socket.io'); this.serveClient(false !== opts.serveClient); this.adapter(opts.adapter || Adapter); this.origins(opts.origins || '*:*'); this.sockets = this.of('/'); if (srv) this.attach(srv, opts); } /** * Server request verification function, that checks for allowed origins * * @param {http.IncomingMessage} request * @param {Function} callback to be called with the result: `fn(err, success)` */ Server.prototype.checkRequest = function(req, fn) { var origin = req.headers.origin || req.headers.referer; // file:// URLs produce a null Origin which can't be authorized via echo-back if ('null' == origin || null == origin) origin = '*'; if (!!origin && typeof(this._origins) == 'function') return this._origins(origin, fn); if (this._origins.indexOf('*:*') !== -1) return fn(null, true); if (origin) { try { var parts = url.parse(origin); parts.port = parts.port || 80; var ok = ~this._origins.indexOf(parts.hostname + ':' + parts.port) || ~this._origins.indexOf(parts.hostname + ':*') || ~this._origins.indexOf('*:' + parts.port); return fn(null, !!ok); } catch (ex) { } } fn(null, false); }; /** * Sets/gets whether client code is being served. * * @param {Boolean} whether to serve client code * @return {Server|Boolean} self when setting or value when getting * @api public */ Server.prototype.serveClient = function(v){ if (!arguments.length) return this._serveClient; this._serveClient = v; return this; }; /** * Old settings for backwards compatibility */ var oldSettings = { "transports": "transports", "heartbeat timeout": "pingTimeout", "heartbeat interval": "pingInterval", "destroy buffer size": "maxHttpBufferSize" }; /** * Backwards compatiblity. * * @api public */ Server.prototype.set = function(key, val){ if ('authorization' == key && val) { this.use(function(socket, next) { val(socket.request, function(err, authorized) { if (err) return next(new Error(err)); if (!authorized) return next(new Error('Not authorized')); next(); }); }); } else if ('origins' == key && val) { this.origins(val); } else if ('resource' == key) { this.path(val); } else if (oldSettings[key] && this.eio[oldSettings[key]]) { this.eio[oldSettings[key]] = val; } else { console.error('Option %s is not valid. Please refer to the README.', key); } return this; }; /** * Sets the client serving path. * * @param {String} pathname * @return {Server|String} self when setting or value when getting * @api public */ Server.prototype.path = function(v){ if (!arguments.length) return this._path; this._path = v.replace(/\/$/, ''); return this; }; /** * Sets the adapter for rooms. * * @param {Adapter} pathname * @return {Server|Adapter} self when setting or value when getting * @api public */ Server.prototype.adapter = function(v){ if (!arguments.length) return this._adapter; this._adapter = v; for (var i in this.nsps) { if (this.nsps.hasOwnProperty(i)) { this.nsps[i].initAdapter(); } } return this; }; /** * Sets the allowed origins for requests. * * @param {String} origins * @return {Server|Adapter} self when setting or value when getting * @api public */ Server.prototype.origins = function(v){ if (!arguments.length) return this._origins; this._origins = v; return this; }; /** * Attaches socket.io to a server or port. * * @param {http.Server|Number} server or port * @param {Object} options passed to engine.io * @return {Server} self * @api public */ Server.prototype.listen = Server.prototype.attach = function(srv, opts){ if ('function' == typeof srv) { var msg = 'You are trying to attach socket.io to an express' + 'request handler function. Please pass a http.Server instance.'; throw new Error(msg); } // handle a port as a string if (Number(srv) == srv) { srv = Number(srv); } if ('number' == typeof srv) { debug('creating http server and binding to %d', srv); var port = srv; srv = http.Server(function(req, res){ res.writeHead(404); res.end(); }); srv.listen(port); } // set engine.io path to `/socket.io` opts = opts || {}; opts.path = opts.path || this.path(); // set origins verification opts.allowRequest = this.checkRequest.bind(this); // initialize engine debug('creating engine.io instance with opts %j', opts); this.eio = engine.attach(srv, opts); // attach static file serving if (this._serveClient) this.attachServe(srv); // Export http server this.httpServer = srv; // bind to engine events this.bind(this.eio); return this; }; /** * Attaches the static file serving. * * @param {Function|http.Server} http server * @api private */ Server.prototype.attachServe = function(srv){ debug('attaching client serving req handler'); var url = this._path + '/socket.io.js'; var evs = srv.listeners('request').slice(0); var self = this; srv.removeAllListeners('request'); srv.on('request', function(req, res) { if (0 == req.url.indexOf(url)) { self.serve(req, res); } else { for (var i = 0; i < evs.length; i++) { evs[i].call(srv, req, res); } } }); }; /** * Handles a request serving `/socket.io.js` * * @param {http.Request} req * @param {http.Response} res * @api private */ Server.prototype.serve = function(req, res){ var etag = req.headers['if-none-match']; if (etag) { if (clientVersion == etag) { debug('serve client 304'); res.writeHead(304); res.end(); return; } } debug('serve client source'); res.setHeader('Content-Type', 'application/javascript'); res.setHeader('ETag', clientVersion); res.writeHead(200); res.end(clientSource); }; /** * Binds socket.io to an engine.io instance. * * @param {engine.Server} engine.io (or compatible) server * @return {Server} self * @api public */ Server.prototype.bind = function(engine){ this.engine = engine; this.engine.on('connection', this.onconnection.bind(this)); return this; }; /** * Called with each incoming transport connection. * * @param {engine.Socket} socket * @return {Server} self * @api public */ Server.prototype.onconnection = function(conn){ debug('incoming connection with id %s', conn.id); var client = new Client(this, conn); client.connect('/'); return this; }; /** * Looks up a namespace. * * @param {String} nsp name * @param {Function} optional, nsp `connection` ev handler * @api public */ Server.prototype.of = function(name, fn){ if (String(name)[0] !== '/') name = '/' + name; if (!this.nsps[name]) { debug('initializing namespace %s', name); var nsp = new Namespace(this, name); this.nsps[name] = nsp; } if (fn) this.nsps[name].on('connect', fn); return this.nsps[name]; }; /** * Closes server connection * * @api public */ Server.prototype.close = function(){ this.nsps['/'].sockets.forEach(function(socket){ socket.onclose(); }); this.engine.close(); if(this.httpServer){ this.httpServer.close(); } }; /** * Expose main namespace (/). */ ['on', 'to', 'in', 'use', 'emit', 'send', 'write'].forEach(function(fn){ Server.prototype[fn] = function(){ var nsp = this.sockets[fn]; return nsp.apply(this.sockets, arguments); }; }); Namespace.flags.forEach(function(flag){ Server.prototype.__defineGetter__(flag, function(name){ this.flags.push(name); return this; }); }); /** * BC with `io.listen` */ Server.listen = Server;
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../meta"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { var htmlMode = CodeMirror.getMode(cmCfg, "text/html"); var htmlModeMissing = htmlMode.name == "null" function getMode(name) { if (CodeMirror.findModeByName) { var found = CodeMirror.findModeByName(name); if (found) name = found.mime || found.mimes[0]; } var mode = CodeMirror.getMode(cmCfg, name); return mode.name == "null" ? null : mode; } // Should characters that affect highlighting be highlighted separate? // Does not include characters that will be output (such as `1.` and `-` for lists) if (modeCfg.highlightFormatting === undefined) modeCfg.highlightFormatting = false; // Maximum number of nested blockquotes. Set to 0 for infinite nesting. // Excess `>` will emit `error` token. if (modeCfg.maxBlockquoteDepth === undefined) modeCfg.maxBlockquoteDepth = 0; // Should underscores in words open/close em/strong? if (modeCfg.underscoresBreakWords === undefined) modeCfg.underscoresBreakWords = true; // Use `fencedCodeBlocks` to configure fenced code blocks. false to // disable, string to specify a precise regexp that the fence should // match, and true to allow three or more backticks or tildes (as // per CommonMark). // Turn on task lists? ("- [ ] " and "- [x] ") if (modeCfg.taskLists === undefined) modeCfg.taskLists = false; // Turn on strikethrough syntax if (modeCfg.strikethrough === undefined) modeCfg.strikethrough = false; // Allow token types to be overridden by user-provided token types. if (modeCfg.tokenTypeOverrides === undefined) modeCfg.tokenTypeOverrides = {}; var tokenTypes = { header: "header", code: "comment", quote: "quote", list1: "variable-2", list2: "variable-3", list3: "keyword", hr: "hr", image: "image", imageAltText: "image-alt-text", imageMarker: "image-marker", formatting: "formatting", linkInline: "link", linkEmail: "link", linkText: "link", linkHref: "string", em: "em", strong: "strong", strikethrough: "strikethrough" }; for (var tokenType in tokenTypes) { if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) { tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType]; } } var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/ , ulRE = /^[*\-+]\s+/ , olRE = /^[0-9]+([.)])\s+/ , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/ , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/ , textRE = /^[^#!\[\]*_\\<>` "'(~]+/ , fencedCodeRE = new RegExp("^(" + (modeCfg.fencedCodeBlocks === true ? "~~~+|```+" : modeCfg.fencedCodeBlocks) + ")[ \\t]*([\\w+#\-]*)"); function switchInline(stream, state, f) { state.f = state.inline = f; return f(stream, state); } function switchBlock(stream, state, f) { state.f = state.block = f; return f(stream, state); } function lineIsEmpty(line) { return !line || !/\S/.test(line.string) } // Blocks function blankLine(state) { // Reset linkTitle state state.linkTitle = false; // Reset EM state state.em = false; // Reset STRONG state state.strong = false; // Reset strikethrough state state.strikethrough = false; // Reset state.quote state.quote = 0; // Reset state.indentedCode state.indentedCode = false; if (htmlModeMissing && state.f == htmlBlock) { state.f = inlineNormal; state.block = blockNormal; } // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; // Mark this line as blank state.prevLine = state.thisLine state.thisLine = null return null; } function blockNormal(stream, state) { var sol = stream.sol(); var prevLineIsList = state.list !== false, prevLineIsIndentedCode = state.indentedCode; state.indentedCode = false; if (prevLineIsList) { if (state.indentationDiff >= 0) { // Continued list if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block state.indentation -= state.indentationDiff; } state.list = null; } else if (state.indentation > 0) { state.list = null; } else { // No longer a list state.list = false; } } var match = null; if (state.indentationDiff >= 4) { stream.skipToEnd(); if (prevLineIsIndentedCode || lineIsEmpty(state.prevLine)) { state.indentation -= 4; state.indentedCode = true; return tokenTypes.code; } else { return null; } } else if (stream.eatSpace()) { return null; } else if ((match = stream.match(atxHeaderRE)) && match[1].length <= 6) { state.header = match[1].length; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (!lineIsEmpty(state.prevLine) && !state.quote && !prevLineIsList && !prevLineIsIndentedCode && (match = stream.match(setextHeaderRE))) { state.header = match[0].charAt(0) == '=' ? 1 : 2; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (stream.eat('>')) { state.quote = sol ? 1 : state.quote + 1; if (modeCfg.highlightFormatting) state.formatting = "quote"; stream.eatSpace(); return getType(state); } else if (stream.peek() === '[') { return switchInline(stream, state, footnoteLink); } else if (stream.match(hrRE, true)) { state.hr = true; return tokenTypes.hr; } else if ((lineIsEmpty(state.prevLine) || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) { var listType = null; if (stream.match(ulRE, true)) { listType = 'ul'; } else { stream.match(olRE, true); listType = 'ol'; } state.indentation = stream.column() + stream.current().length; state.list = true; // While this list item's marker's indentation // is less than the deepest list item's content's indentation, // pop the deepest list item indentation off the stack. while (state.listStack && stream.column() < state.listStack[state.listStack.length - 1]) { state.listStack.pop(); } // Add this list item's content's indentation to the stack state.listStack.push(state.indentation); if (modeCfg.taskLists && stream.match(taskListRE, false)) { state.taskList = true; } state.f = state.inline; if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType]; return getType(state); } else if (modeCfg.fencedCodeBlocks && (match = stream.match(fencedCodeRE, true))) { state.fencedChars = match[1] // try switching mode state.localMode = getMode(match[2]); if (state.localMode) state.localState = CodeMirror.startState(state.localMode); state.f = state.block = local; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = -1 return getType(state); } return switchInline(stream, state, state.inline); } function htmlBlock(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (!htmlModeMissing) { var inner = CodeMirror.innerMode(htmlMode, state.htmlState) if ((inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText)) || (state.md_inside && stream.current().indexOf(">") > -1)) { state.f = inlineNormal; state.block = blockNormal; state.htmlState = null; } } return style; } function local(stream, state) { if (state.fencedChars && stream.match(state.fencedChars, false)) { state.localMode = state.localState = null; state.f = state.block = leavingLocal; return null; } else if (state.localMode) { return state.localMode.token(stream, state.localState); } else { stream.skipToEnd(); return tokenTypes.code; } } function leavingLocal(stream, state) { stream.match(state.fencedChars); state.block = blockNormal; state.f = inlineNormal; state.fencedChars = null; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = 1 var returnType = getType(state); state.code = 0 return returnType; } // Inline function getType(state) { var styles = []; if (state.formatting) { styles.push(tokenTypes.formatting); if (typeof state.formatting === "string") state.formatting = [state.formatting]; for (var i = 0; i < state.formatting.length; i++) { styles.push(tokenTypes.formatting + "-" + state.formatting[i]); if (state.formatting[i] === "header") { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header); } // Add `formatting-quote` and `formatting-quote-#` for blockquotes // Add `error` instead if the maximum blockquote nesting depth is passed if (state.formatting[i] === "quote") { if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote); } else { styles.push("error"); } } } } if (state.taskOpen) { styles.push("meta"); return styles.length ? styles.join(' ') : null; } if (state.taskClosed) { styles.push("property"); return styles.length ? styles.join(' ') : null; } if (state.linkHref) { styles.push(tokenTypes.linkHref, "url"); } else { // Only apply inline styles to non-url text if (state.strong) { styles.push(tokenTypes.strong); } if (state.em) { styles.push(tokenTypes.em); } if (state.strikethrough) { styles.push(tokenTypes.strikethrough); } if (state.linkText) { styles.push(tokenTypes.linkText); } if (state.code) { styles.push(tokenTypes.code); } if (state.image) { styles.push(tokenTypes.image); } if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); } if (state.imageMarker) { styles.push(tokenTypes.imageMarker); } } if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); } if (state.quote) { styles.push(tokenTypes.quote); // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.quote + "-" + state.quote); } else { styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth); } } if (state.list !== false) { var listMod = (state.listStack.length - 1) % 3; if (!listMod) { styles.push(tokenTypes.list1); } else if (listMod === 1) { styles.push(tokenTypes.list2); } else { styles.push(tokenTypes.list3); } } if (state.trailingSpaceNewLine) { styles.push("trailing-space-new-line"); } else if (state.trailingSpace) { styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); } return styles.length ? styles.join(' ') : null; } function handleText(stream, state) { if (stream.match(textRE, true)) { return getType(state); } return undefined; } function inlineNormal(stream, state) { var style = state.text(stream, state); if (typeof style !== 'undefined') return style; if (state.list) { // List marker (*, +, -, 1., etc) state.list = null; return getType(state); } if (state.taskList) { var taskOpen = stream.match(taskListRE, true)[1] !== "x"; if (taskOpen) state.taskOpen = true; else state.taskClosed = true; if (modeCfg.highlightFormatting) state.formatting = "task"; state.taskList = false; return getType(state); } state.taskOpen = false; state.taskClosed = false; if (state.header && stream.match(/^#+$/, true)) { if (modeCfg.highlightFormatting) state.formatting = "header"; return getType(state); } // Get sol() value now, before character is consumed var sol = stream.sol(); var ch = stream.next(); // Matches link titles present on next line if (state.linkTitle) { state.linkTitle = false; var matchCh = ch; if (ch === '(') { matchCh = ')'; } matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh; if (stream.match(new RegExp(regex), true)) { return tokenTypes.linkHref; } } // If this block is changed, it may need to be updated in GFM mode if (ch === '`') { var previousFormatting = state.formatting; if (modeCfg.highlightFormatting) state.formatting = "code"; stream.eatWhile('`'); var count = stream.current().length if (state.code == 0) { state.code = count return getType(state) } else if (count == state.code) { // Must be exact var t = getType(state) state.code = 0 return t } else { state.formatting = previousFormatting return getType(state) } } else if (state.code) { return getType(state); } if (ch === '\\') { stream.next(); if (modeCfg.highlightFormatting) { var type = getType(state); var formattingEscape = tokenTypes.formatting + "-escape"; return type ? type + " " + formattingEscape : formattingEscape; } } if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { state.imageMarker = true; state.image = true; if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === '[' && state.imageMarker) { state.imageMarker = false; state.imageAltText = true if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === ']' && state.imageAltText) { if (modeCfg.highlightFormatting) state.formatting = "image"; var type = getType(state); state.imageAltText = false; state.image = false; state.inline = state.f = linkHref; return type; } if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false) && !state.image) { state.linkText = true; if (modeCfg.highlightFormatting) state.formatting = "link"; return getType(state); } if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) { if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); state.linkText = false; state.inline = state.f = linkHref; return type; } if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkEmail; } if (ch === '<' && stream.match(/^(!--|\w)/, false)) { var end = stream.string.indexOf(">", stream.pos); if (end != -1) { var atts = stream.string.substring(stream.start, end); if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true; } stream.backUp(1); state.htmlState = CodeMirror.startState(htmlMode); return switchBlock(stream, state, htmlBlock); } if (ch === '<' && stream.match(/^\/\w*?>/)) { state.md_inside = false; return "tag"; } var ignoreUnderscore = false; if (!modeCfg.underscoresBreakWords) { if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) { var prevPos = stream.pos - 2; if (prevPos >= 0) { var prevCh = stream.string.charAt(prevPos); if (prevCh !== '_' && prevCh.match(/(\w)/, false)) { ignoreUnderscore = true; } } } } if (ch === '*' || (ch === '_' && !ignoreUnderscore)) { if (sol && stream.peek() === ' ') { // Do nothing, surrounded by newline and space } else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG if (modeCfg.highlightFormatting) state.formatting = "strong"; var t = getType(state); state.strong = false; return t; } else if (!state.strong && stream.eat(ch)) { // Add STRONG state.strong = ch; if (modeCfg.highlightFormatting) state.formatting = "strong"; return getType(state); } else if (state.em === ch) { // Remove EM if (modeCfg.highlightFormatting) state.formatting = "em"; var t = getType(state); state.em = false; return t; } else if (!state.em) { // Add EM state.em = ch; if (modeCfg.highlightFormatting) state.formatting = "em"; return getType(state); } } else if (ch === ' ') { if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(1); } } } if (modeCfg.strikethrough) { if (ch === '~' && stream.eatWhile(ch)) { if (state.strikethrough) {// Remove strikethrough if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; var t = getType(state); state.strikethrough = false; return t; } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough state.strikethrough = true; if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; return getType(state); } } else if (ch === ' ') { if (stream.match(/^~~/, true)) { // Probably surrounded by space if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(2); } } } } if (ch === ' ') { if (stream.match(/ +$/, false)) { state.trailingSpace++; } else if (state.trailingSpace) { state.trailingSpaceNewLine = true; } } return getType(state); } function linkInline(stream, state) { var ch = stream.next(); if (ch === ">") { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } stream.match(/^[^>]+/, true); return tokenTypes.linkInline; } function linkHref(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } var ch = stream.next(); if (ch === '(' || ch === '[') { state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]", 0); if (modeCfg.highlightFormatting) state.formatting = "link-string"; state.linkHref = true; return getType(state); } return 'error'; } var linkRE = { ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/, "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/ } function getLinkHrefInside(endChar) { return function(stream, state) { var ch = stream.next(); if (ch === endChar) { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link-string"; var returnState = getType(state); state.linkHref = false; return returnState; } stream.match(linkRE[endChar]) state.linkHref = true; return getType(state); }; } function footnoteLink(stream, state) { if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) { state.f = footnoteLinkInside; stream.next(); // Consume [ if (modeCfg.highlightFormatting) state.formatting = "link"; state.linkText = true; return getType(state); } return switchInline(stream, state, inlineNormal); } function footnoteLinkInside(stream, state) { if (stream.match(/^\]:/, true)) { state.f = state.inline = footnoteUrl; if (modeCfg.highlightFormatting) state.formatting = "link"; var returnType = getType(state); state.linkText = false; return returnType; } stream.match(/^([^\]\\]|\\.)+/, true); return tokenTypes.linkText; } function footnoteUrl(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } // Match URL stream.match(/^[^\s]+/, true); // Check for link title if (stream.peek() === undefined) { // End of line, set flag to check next line state.linkTitle = true; } else { // More content on line, check if link title stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true); } state.f = state.inline = inlineNormal; return tokenTypes.linkHref + " url"; } var mode = { startState: function() { return { f: blockNormal, prevLine: null, thisLine: null, block: blockNormal, htmlState: null, indentation: 0, inline: inlineNormal, text: handleText, formatting: false, linkText: false, linkHref: false, linkTitle: false, code: 0, em: false, strong: false, header: 0, hr: false, taskList: false, list: false, listStack: [], quote: 0, trailingSpace: 0, trailingSpaceNewLine: false, strikethrough: false, fencedChars: null }; }, copyState: function(s) { return { f: s.f, prevLine: s.prevLine, thisLine: s.thisLine, block: s.block, htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState), indentation: s.indentation, localMode: s.localMode, localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, inline: s.inline, text: s.text, formatting: false, linkTitle: s.linkTitle, code: s.code, em: s.em, strong: s.strong, strikethrough: s.strikethrough, header: s.header, hr: s.hr, taskList: s.taskList, list: s.list, listStack: s.listStack.slice(0), quote: s.quote, indentedCode: s.indentedCode, trailingSpace: s.trailingSpace, trailingSpaceNewLine: s.trailingSpaceNewLine, md_inside: s.md_inside, fencedChars: s.fencedChars }; }, token: function(stream, state) { // Reset state.formatting state.formatting = false; if (stream != state.thisLine) { var forceBlankLine = state.header || state.hr; // Reset state.header and state.hr state.header = 0; state.hr = false; if (stream.match(/^\s*$/, true) || forceBlankLine) { blankLine(state); if (!forceBlankLine) return null state.prevLine = null } state.prevLine = state.thisLine state.thisLine = stream // Reset state.taskList state.taskList = false; // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; state.f = state.block; var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length; state.indentationDiff = Math.min(indentation - state.indentation, 4); state.indentation = state.indentation + state.indentationDiff; if (indentation > 0) return null; } return state.f(stream, state); }, innerMode: function(state) { if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode}; if (state.localState) return {state: state.localState, mode: state.localMode}; return {state: state, mode: mode}; }, blankLine: blankLine, getType: getType, fold: "markdown" }; return mode; }, "xml"); CodeMirror.defineMIME("text/x-markdown", "markdown"); });
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var ActionSettingsInputHdmi = React.createClass({ displayName: 'ActionSettingsInputHdmi', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M18 7V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v3H5v6l3 6v3h8v-3l3-6V7h-1zM8 4h8v3h-2V5h-1v2h-2V5h-1v2H8V4z' }) ); } }); module.exports = ActionSettingsInputHdmi;
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Horizontal Page Break */ // Register a plugin named "pagebreak". CKEDITOR.plugins.add( 'pagebreak', { init : function( editor ) { // Register the command. editor.addCommand( 'pagebreak', CKEDITOR.plugins.pagebreakCmd ); // Register the toolbar button. editor.ui.addButton( 'PageBreak', { label : editor.lang.pagebreak, command : 'pagebreak' }); var cssStyles = [ '{' , 'background: url(' + CKEDITOR.getUrl( this.path + 'images/pagebreak.gif' ) + ') no-repeat center center;' , 'clear: both;' , 'width:100%; _width:99.9%;' , 'border-top: #999999 1px dotted;' , 'border-bottom: #999999 1px dotted;' , 'padding:0;' , 'height: 5px;' , 'cursor: default;' , '}' ].join( '' ).replace(/;/g, ' !important;' ); // Increase specificity to override other styles, e.g. block outline. // Add the style that renders our placeholder. editor.addCss( 'div.cke_pagebreak' + cssStyles ); // Opera needs help to select the page-break. CKEDITOR.env.opera && editor.on( 'contentDom', function() { editor.document.on( 'click', function( evt ) { var target = evt.data.getTarget(); if ( target.is( 'div' ) && target.hasClass( 'cke_pagebreak') ) editor.getSelection().selectElement( target ); }); }); }, afterInit : function( editor ) { var label = editor.lang.pagebreakAlt; // Register a filter to displaying placeholders after mode change. var dataProcessor = editor.dataProcessor, dataFilter = dataProcessor && dataProcessor.dataFilter, htmlFilter = dataProcessor && dataProcessor.htmlFilter; if ( htmlFilter ) { htmlFilter.addRules( { attributes : { 'class' : function( value, element ) { var className = value.replace( 'cke_pagebreak', '' ); if ( className != value ) { var span = CKEDITOR.htmlParser.fragment.fromHtml( '<span style="display: none;">&nbsp;</span>' ); element.children.length = 0; element.add( span ); var attrs = element.attributes; delete attrs[ 'aria-label' ]; delete attrs.contenteditable; delete attrs.title; } return className; } } }, 5 ); } if ( dataFilter ) { dataFilter.addRules( { elements : { div : function( element ) { var attributes = element.attributes, style = attributes && attributes.style, child = style && element.children.length == 1 && element.children[ 0 ], childStyle = child && ( child.name == 'span' ) && child.attributes.style; if ( childStyle && ( /page-break-after\s*:\s*always/i ).test( style ) && ( /display\s*:\s*none/i ).test( childStyle ) ) { attributes.contenteditable = "false"; attributes[ 'class' ] = "cke_pagebreak"; attributes[ 'data-cke-display-name' ] = "pagebreak"; attributes[ 'aria-label' ] = label; attributes[ 'title' ] = label; element.children.length = 0; } } } }); } }, requires : [ 'fakeobjects' ] }); CKEDITOR.plugins.pagebreakCmd = { exec : function( editor ) { var label = editor.lang.pagebreakAlt; // Create read-only element that represents a print break. var pagebreak = CKEDITOR.dom.element.createFromHtml( '<div style="' + 'page-break-after: always;"' + 'contenteditable="false" ' + 'title="'+ label + '" ' + 'aria-label="'+ label + '" ' + 'data-cke-display-name="pagebreak" ' + 'class="cke_pagebreak">' + '</div>', editor.document ); var ranges = editor.getSelection().getRanges( true ); editor.fire( 'saveSnapshot' ); for ( var range, i = ranges.length - 1 ; i >= 0; i-- ) { range = ranges[ i ]; if ( i < ranges.length -1 ) pagebreak = pagebreak.clone( true ); range.splitBlock( 'p' ); range.insertNode( pagebreak ); if ( i == ranges.length - 1 ) { var next = pagebreak.getNext(); range.moveToPosition( pagebreak, CKEDITOR.POSITION_AFTER_END ); // If there's nothing or a non-editable block followed by, establish a new paragraph // to make sure cursor is not trapped. if ( !next || next.type == CKEDITOR.NODE_ELEMENT && !next.isEditable() ) range.fixBlock( true, editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' ); range.select(); } } editor.fire( 'saveSnapshot' ); } };
/*! * ===================================================== * dmui v0.1.0 (http://www.91holy.com) * ===================================================== */ /*! * dmui JavaScript Library v0.1.0 * https://dmui.com/ * Copyright dmui Foundation and other contributors * Released under the MIT license * https://github.com/desangel/dmui/license * * Date: 2016-05-12T06:59Z */ ( function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get dmui. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var dmui = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "dmui requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of dmui 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; (function(){ "use strict"; window.URL = window.URL||window.webkitURL; }()); var util = (function(){ "use strict"; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var util = { isFunction: isFunction, isArray: Array.isArray || isArray, isWindow: isWindow, isNumeric: isNumeric, isEmptyObject: isEmptyObject, isPlainObject: isPlainObject, type: type, extend: extend }; function isFunction( obj ) { return type(obj) === "function"; } function isArray( obj ) { return type(obj) === "array"; } function isWindow( obj ) { return obj != null && obj === obj.window; } function isNumeric( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) return !isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; } function isEmptyObject( obj ) { var name; for ( name in obj ) { return false; } return true; } function isPlainObject( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || type(obj) !== "object" || obj.nodeType || isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. //if ( support.ownLast ) { // for ( key in obj ) { // return hasOwn.call( obj, key ); // } //} // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); } function type( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; } function extend(){ var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction(target)) { target = {}; } // extend itself if only one argument is passed if ( i === length ) { target = {}; //this i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // do not copy prototype function if ( !options.hasOwnProperty(name)){ continue; } // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( name!== 'parent' && deep && copy && !isPlainObject(copy) && typeof copy.clone === "function" ){ //remove parent for no dead loop //clone is for classType object target[ name ] = copy.clone(); if(target[ name ] ===undefined){ target[ name ] = copy; } } else if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; } return util; }()); /* global xyz */ util.classExtend = (function(){ "use strict"; //inheritance function classExtend(ChildClass, ParentClass){ var initializing = false, fnTest = /xyz/.test(function() { xyz; }) ? /\b_super\b/ : /.*/; var _super = ParentClass.prototype; var prop = ChildClass.prototype; var prototype = typeof Object.create === "function" ? Object.create(ParentClass.prototype):new ParentClass(); for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] === "function" && typeof _super[name] === "function" && fnTest.test(prop[name]) ? createCallSuperFunction(name, prop[name]) : prop[name]; } initializing = true; ChildClass.prototype = prototype; ChildClass.prototype.constructor = ChildClass; function createCallSuperFunction(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; } } return classExtend; }()); var document = window.document; util.extend( util, (function(){ "use strict"; var code = { htmlEncode: htmlEncode, htmlDecode: htmlDecode }; function htmlEncode(value){ var temp = document.createElement('div'); (temp.textContent!=null)?(temp.textContent=value) : (temp.innerText=value); var result = temp.html.innerHTML; temp = null; return result; } function htmlDecode(value){ var temp = document.createElement('div'); temp.innerHTML = value; var result = temp.innerText || temp.textContent; temp = null; return result; } return code; }()) ); util.extend(util, (function(){ "use strict"; //ECMA SCRIPT 5 var object = { defineProperty: defineProperty, defineProperties: defineProperties }; function defineProperty(obj, name, prop){ if(typeof Object.defineProperty ==='function'){ Object.defineProperty(obj, name, prop); } else{ obj[name] = prop['value']; } } function defineProperties(obj, props){ if(typeof Object.defineProperties ==='function'){ Object.defineProperties(obj, props); } else{ for(var i in props){ var prop = props[i]; obj[i] = prop['value']; } } } return object; }()) ); util.browser = (function(){ "use strict"; var navigator = window.navigator; var browser = { versions: (function(){ var u = navigator.userAgent, app = navigator.appVersion; var vendor = navigator.vendor; return { u: u, app: app, vendor: vendor, windows: u.indexOf('Windows') > -1, //windows trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1,//火狐内核 chrome: u.indexOf('Chrome') > -1 ,//chrome内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp: u.indexOf('Safari') === -1, //是否web应该程序,没有头部与底部 weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增) weibo: u.indexOf('Weibo') > -1, //是否微博 qq: u.match(/\sQQ/i) === " qq" //是否QQ }; })(), language:(navigator.browserLanguage || navigator.language || navigator.userLanguage).toLowerCase() }; return browser; }()); util.collection = (function(){ "use strict"; var collection = { is: is }; function is(arr, element){ for(var i = 0; i<arr.length; i++){ if(typeof element === 'function'){ if(element(i, arr[i])){return true;} }else{ if(arr[i]===element){return true;} } } return false; } return collection; }()); util.cookie = (function(){ "use strict"; var cookie = { addCookie: addCookie, deleteCookie: deleteCookie, getCookie: getCookie, getDocumentCookie: getDocumentCookie }; function addCookie(name, value, attr){ var str = ""; if(attr){ for(var prop in attr){ str+=";"+prop+"="+attr[prop]; } } document.cookie = name + "=" + window.escape(value) + str; } function deleteCookie(name){ var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null){ document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } } function getCookie(name){ var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null){ return (arr[2]); } return null; } function getDocumentCookie(){ return document.cookie; } return cookie; }()); util.date = (function(){ "use strict"; var getDateHelper = function(){ return { date : getDate(), duration : getDurationHelper(), dateDiff : dateDiff, dateDiffResult : dateDiffResult, dateDiffResultFull : dateDiffResultFull, dateToStr : dateToStr, datetimeToStr : datetimeToStr, getOffsetDate : getOffsetDate, paramToDate : paramToDate, strToDate : strToDate, timeToStr : timeToStr, durationToStr : durationToStr, durationToObj : durationToObj, typeToStr : typeToStr, weekdayToStr : weekdayToStr, zhDateToStr : zhDateToStr, zhDatetimeToStr : zhDatetimeToStr, fillZero : fillZero }; function getDate(){ return { monthFirstDay : monthFirstDay, monthLastDay : monthLastDay }; function monthFirstDay(date){ return paramToDate(date.getFullYear(), date.getMonth()); } function monthLastDay(date){ var result = monthFirstDay(date); result = getOffsetDate('month', result, 1); result = getOffsetDate('date', result, -1); return result; } } function getDurationHelper() { return { today : today, yestoday : yestoday, date: day, currentWeek : currentWeek, lastWeek : lastWeek, currentMonth : currentMonth, currentYear : currentYear, calendarMonth : calendarMonth, month : month, year : year }; function today() { return getDurationStr('date', new Date()); } function yestoday() { return getDurationStr('date', getOffsetDate('date', new Date(), -1)); } function day(date){ return getDurationStr('date', date); } function currentWeek(){ return getDurationStr('day', new Date()); } function lastWeek(){ return getDurationStr('day', getOffsetDate('date', new Date(), -7)); } function currentMonth(){ return getDurationStr('month', new Date()); } function currentYear(){ return getDurationStr('year', new Date()); } function calendarMonth(year, month){ var now = new Date(); year = year || now.getFullYear(); month = month || now.getMonth()+1; return getDurationStr('calendarMonth', paramToDate(year, month-1)); } function month(year, month){ var now = new Date(); year = year || now.getFullYear(); month = month || now.getMonth()+1; return getDurationStr('month', paramToDate(year, month-1)); } function year(year){ return getDurationStr('year', paramToDate(year)); } } function getDurationStr(type, startTime) { var result = getDuration(type, startTime); return { startTime : datetimeToStr(result['startTime']), endTime : datetimeToStr(result['endTime']) }; } function getDuration(type, startTime) { var year, month, date, hour, minute, second; var day; var startTimeDate, endTimeDate; switch (type) { case 'calendarMonth': year = startTime.getFullYear(); month = startTime.getMonth(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate('month', startTimeDate, 1); var startTimeWeekDay = startTimeDate.getDay(); var endTimeWeekDay = endTimeDate.getDay(); startTimeDate = getOffsetDate('date', startTimeDate, - startTimeWeekDay%7); endTimeDate = getOffsetDate('date', endTimeDate, (7-endTimeWeekDay)%7); break; case 'year': year = startTime.getFullYear(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate(type, startTimeDate, 1); break; case 'month': year = startTime.getFullYear(); month = startTime.getMonth(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate(type, startTimeDate, 1); break; case 'date': year = startTime.getFullYear(); month = startTime.getMonth(); date = startTime.getDate(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate(type, startTimeDate, 1); break; case 'day': year = startTime.getFullYear(); month = startTime.getMonth(); date = startTime.getDate(); day = startTime.getDay(); date = date - (day+6)%7; startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate('date', startTimeDate, 7); break; } return { startTime : startTimeDate, endTime : endTimeDate }; } function dateDiff(type, date1, date2){ var result = 0; switch (type) { case 'year': result = Math.floor(((date1.getFullYear() - date2.getFullYear())*12+ date1.getMonth() - date2.getMonth())/12);break; case 'month': result = (date1.getFullYear() - date2.getFullYear())*12 + date1.getMonth() - date2.getMonth() + (((date1.getDate()-date2.getDate())>=0?1:-1) + (date1>=date2?-1: 1))/2;break; case 'date': result = Math.floor(date1.getTime()/(1000*60*60*24))-Math.floor(date2.getTime()/(1000*60*60*24)); break; case 'hour': result = Math.floor(date1.getTime()/(1000*60*60))-Math.floor(date2.getTime()/(1000*60*60)); break; case 'minute': result = Math.floor(date1.getTime()/(1000*60))-Math.floor(date2.getTime()/(1000*60)); break; case 'second': result = Math.floor(date1.getTime()/(1000))-Math.floor(date2.getTime()/(1000)); break; default: result = (date1.getTime()-date2.getTime()); } return result; } function dateDiffResult(date1, date2){ var offset, type; type = 'year'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'month'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'date'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'hour'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'minute'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'second'; offset = dateDiff(type, date1, date2); return {offset: offset, type: type}; } function dateDiffResultFull(type, date1, date2){ var result = {}; var delta = date1.getTime()-date2.getTime(); var rest = delta; switch(type){ case 'year': result['year'] = dateDiff('year', date1, date2); break; case 'date': result['date'] = Math.floor(rest / (1000*60*60*24) ); rest = rest % (1000*60*60*24); result['hour'] = Math.floor(rest / (1000*60*60) ); rest = rest % (1000*60*60); result['minute'] = Math.floor(rest / (1000*60) ); rest = rest % (1000*60); result['second'] = Math.floor(rest / (1000) ); rest = rest % (1000); break; } return result; } function getOffsetDate(type, date, offset) { var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var hour = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); switch (type) { case 'year':year+=offset;break; case 'month':month+=offset;break; case 'date':day+=offset;break; case 'hour':hour+=offset;break; case 'minute':minute+=offset;break; case 'second':second+=offset;break; } return paramToDate(year, month, day, hour, minute, second); } function fillZero(input, num) { var result = '' + input; for (var i = 0; i < (num - result.length); i++) { result = '0' + result; } return result; } function datetimeToStr(date, fmt) { if(typeof date==='string')date = strToDate(date); fmt = fmt||'yyyy-MM-dd hh:mm:ss'; var year = date.getFullYear(); var month = fillZero(date.getMonth() + 1, 2); var dateString = fillZero(date.getDate(), 2); var hour = fillZero(date.getHours() ,2); var minute = fillZero(date.getMinutes(), 2); var second = fillZero(date.getSeconds(), 2); return fmt.replace('yyyy',year).replace('MM',month).replace('dd', dateString).replace('hh',hour).replace('mm',minute).replace('ss', second); } function dateToStr(date, fmt) { if(typeof date==='string')date = strToDate(date); fmt = fmt||'yyyy-MM-dd'; var year = date.getFullYear(); var month = fillZero(date.getMonth() + 1, 2); var dateString = fillZero(date.getDate(), 2); return fmt.replace('yyyy',year).replace('MM',month).replace('dd', dateString); } function timeToStr(date, fmt){ if(typeof date==='string')date = strToDate(date); fmt = fmt||'hh:mm:ss'; var hour = fillZero(date.getHours() ,2); var minute = fillZero(date.getMinutes(), 2); var second = fillZero(date.getSeconds(), 2); return fmt.replace('hh',hour).replace('mm',minute).replace('ss', second); } function durationToStr(millisecond, fmt, fillType){ fmt = fmt||'hh:mm:ss.ms'; fillType = fillType||'hh'; var obj = durationToObj(millisecond); var hour = fillZero(obj['hour'] ,2); var minute = fillZero(obj['minute'], 2); var second = fillZero(obj['second'], 2); if(fillType==='hh'||fillType==='mm'&&obj['hour']===0){ fmt = fmt.replace('hh:', ''); if(fillType==='mm'&&obj['minute']===0){ fmt = fmt.replace('mm:', ''); } } return fmt.replace('hh', hour).replace('mm', minute).replace('ss', second).replace('ms', obj['millisecond']); } function durationToObj(millisecond){ var result = {}; var rest = millisecond; result['hour'] = Math.floor(rest / (1000*60*60) ); rest = rest % (1000*60*60); result['minute'] = Math.floor(rest / (1000*60) ); rest = rest % (1000*60); result['second'] = Math.floor(rest / (1000) ); rest = rest % (1000); result['millisecond'] = rest; return result; } function zhDateToStr(date, fmt){ if(typeof date==='string')date = strToDate(date); fmt = fmt||'yyyyMMdd'; var year = date.getFullYear(); var month = date.getMonth() + 1; var dateString = date.getDate(); return fmt.replace('yyyy',year+'年').replace('MM',month+'月').replace('dd', dateString+'日'); } function zhDatetimeToStr(date){ var now = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var dateString = date.getDate(); var hour = fillZero(date.getHours() ,2); var minute = fillZero(date.getMinutes(), 2); var result = ''; if(now.getFullYear()===year&&now.getMonth()+1===month){ if(now.getDate()-dateString===0){ }else if(now.getDate()-dateString===1){ result += '昨天'; }else if(now.getDate()-dateString===2){ result += '前天'; }else{ result += zhDateToStr(date); } if(now.getDate()-dateString!==0)result += ' '; } result += hour+':'+minute; return result; } // 微信客户端不支持new Date("2015-07-04 12:00:00") function strToDate(dateTimeStr) { if(!dateTimeStr)return null; var date = new Date(0); var dateTimeArray = dateTimeStr.split(' '); var dateStr = dateTimeArray[0]; var dateArray = dateStr.split('-'); date.setFullYear(parseInt(dateArray[0], 0)); date.setMonth(parseInt(dateArray[1], 0) - 1); date.setDate(parseInt(dateArray[2], 0)); if (dateTimeArray.length > 1) { var timeStr = dateTimeArray[1]; var timeArray = timeStr.split(':'); date.setHours(parseInt(timeArray[0], 0)); date.setMinutes(parseInt(timeArray[1], 0)); date.setSeconds(parseInt(timeArray[2], 0)); } return date; } function paramToDate(year, month, date, hour, minute, second) { month =month || 0; date = date!==undefined? date : 1; hour = hour || 0; minute = minute || 0; second = second || 0; var result = new Date(0); result.setFullYear(year); result.setMonth(month); result.setDate(date); result.setHours(hour); result.setMinutes(minute); result.setSeconds(second); return result; } function weekdayToStr(weekday){ var result = ''; switch(weekday){ case 0:result='日';break; case 1:result='一';break; case 2:result='二';break; case 3:result='三';break; case 4:result='四';break; case 5:result='五';break; case 6:result='六';break; } return result; } function typeToStr(type){ var result = ''; switch(type){ case 'year':result='年';break; case 'month':result='月';break; case 'day': case 'date':result='天';break; case 'hour':result='小时';break; case 'minute':result='分钟';break; case 'second':result='秒';break; } return result; } }; return getDateHelper(); }()); util.path = (function(){ "use strict"; function findCurrentPath(){ return document.currentScript&&document.currentScript.src||(function(){ //for IE10+ Safari Opera9 var a = {}, stack; try{ a.b(); }catch(e){ stack = e.stack || e.sourceURL || e.stacktrace; } var rExtractUri = /(?:http|https|file):\/\/.*?\/.+?.js/, absPath = rExtractUri.exec(stack); return absPath[0] || ''; })()||(function(){ // IE5.5 - 9 var scripts = document.scripts; var isLt8 = ('' + document.querySelector).indexOf('[native code]') === -1; for (var i = scripts.length - 1, script; script = scripts[i--];){ if (script.readyState === 'interative'){ return isLt8 ? script.getAttribute('src', 4) : script.src; } } })(); } return { findCurrentPath: findCurrentPath }; }()); var version = "0.1.0"; var dmui = function(){ this.init(); }; dmui.fn = dmui.prototype = { version: version, constructor: dmui, init: function(){ window.console.log(util); } }; var // Map over dmui in case of overwrite _dmui = window.dmui; dmui.noConflict = function( deep ) { if ( deep && window.dmui === dmui ) { window.dmui = _dmui; } return dmui; }; // Expose dmui and $ identifiers, even in AMD // and CommonJS for browser emulators (#13566) if ( !noGlobal ) { window.dmui = dmui; } return dmui; } ) );
import { sortSurveyElements } from '../index'; describe('sortSurveyElements', () => { it('sorts survey elements by weight', () => { const inputSurvey = { title: 'Sample Survey', sections: [ { id: 1, title: 'Later Section', weight: 1 }, { id: 2, title: 'Earlier Section', weight: 0, questions: [ { id: 4, description: 'Q3', weight: 2 }, { id: 5, description: 'Q1', weight: 0 }, { id: 1, description: 'Q2', weight: 1, options: [ { option: 'Choice 2', weight: 1 }, { option: 'Choice 1', weight: 0 }, ], }, ], }, ], }; const outputSurvey = { title: 'Sample Survey', sections: [ { id: 2, title: 'Earlier Section', weight: 0, questions: [ { id: 5, description: 'Q1', weight: 0 }, { id: 1, description: 'Q2', weight: 1, options: [ { option: 'Choice 1', weight: 0 }, { option: 'Choice 2', weight: 1 }, ], }, { id: 4, description: 'Q3', weight: 2 }, ], }, { id: 1, title: 'Later Section', weight: 1 }, ], }; expect(sortSurveyElements(inputSurvey)).toEqual(outputSurvey); }); });
const should = require('should'); const sinon = require('sinon'); const configUtils = require('../../../utils/configUtils'); // Stuff we are testing const img_url = require('../../../../core/frontend/helpers/img_url'); const logging = require('@tryghost/logging'); describe('{{img_url}} helper', function () { let logWarnStub; beforeEach(function () { logWarnStub = sinon.stub(logging, 'warn'); }); afterEach(function () { sinon.restore(); }); describe('without sub-directory', function () { before(function () { configUtils.set({url: 'http://localhost:65535/'}); }); after(function () { configUtils.restore(); }); it('should output relative url of image', function () { const rendered = img_url('/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should output relative url of image if the input is absolute', function () { const rendered = img_url('http://localhost:65535/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should output absolute url of image if the option is present ', function () { const rendered = img_url('/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); should.exist(rendered); rendered.should.equal('http://localhost:65535/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should NOT output absolute url of image if the option is "false" ', function () { const rendered = img_url('/content/images/image-relative-url.png', {hash: {absolute: 'false'}}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); }); it('should output author url', function () { const rendered = img_url('/content/images/author-image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/author-image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should have no output if the image attribute is not provided (with warning)', function () { const rendered = img_url({hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.true(); }); it('should have no output if the image attribute evaluates to undefined (with warning)', function () { const rendered = img_url(undefined, {hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.true(); }); it('should have no output if the image attribute evaluates to null (no waring)', function () { const rendered = img_url(null, {hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.false(); }); }); describe('with sub-directory', function () { before(function () { configUtils.set({url: 'http://localhost:65535/blog'}); }); after(function () { configUtils.restore(); }); it('should output relative url of image', function () { const rendered = img_url('/blog/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/blog/content/images/image-relative-url.png'); }); it('should output absolute url of image if the option is present ', function () { const rendered = img_url('/blog/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); should.exist(rendered); rendered.should.equal('http://localhost:65535/blog/content/images/image-relative-url.png'); }); it('should not change output for an external url', function () { const rendered = img_url('http://example.com/picture.jpg', {}); should.exist(rendered); rendered.should.equal('http://example.com/picture.jpg'); }); }); describe('image_sizes', function () { before(function () { configUtils.set({url: 'http://localhost:65535/'}); }); after(function () { configUtils.restore(); }); it('should output correct url for absolute paths which are internal', function () { const rendered = img_url('http://localhost:65535/content/images/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('/content/images/size/w400/my-coole-img.jpg'); }); it('should output the correct url for protocol relative urls', function () { const rendered = img_url('//website.com/whatever/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('//website.com/whatever/my-coole-img.jpg'); }); it('should output the correct url for relative paths', function () { const rendered = img_url('/content/images/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('/content/images/size/w400/my-coole-img.jpg'); }); it('should output the correct url for relative paths without leading slash', function () { const rendered = img_url('content/images/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('content/images/size/w400/my-coole-img.jpg'); }); }); });
import { findPort, killApp, nextBuild, nextStart, renderViaHTTP, File, waitFor, } from 'next-test-utils' import webdriver from 'next-webdriver' import { join } from 'path' const appDir = join(__dirname, '../') let appPort let app let browser let html const indexPage = new File(join(appDir, 'pages/static-img.js')) const runTests = () => { it('Should allow an image with a static src to omit height and width', async () => { expect(await browser.elementById('basic-static')).toBeTruthy() expect(await browser.elementById('blur-png')).toBeTruthy() expect(await browser.elementById('blur-webp')).toBeTruthy() expect(await browser.elementById('blur-avif')).toBeTruthy() expect(await browser.elementById('blur-jpg')).toBeTruthy() expect(await browser.elementById('static-svg')).toBeTruthy() expect(await browser.elementById('static-gif')).toBeTruthy() expect(await browser.elementById('static-bmp')).toBeTruthy() expect(await browser.elementById('static-ico')).toBeTruthy() expect(await browser.elementById('static-unoptimized')).toBeTruthy() }) it('Should use immutable cache-control header for static import', async () => { await browser.eval( `document.getElementById("basic-static").scrollIntoView()` ) await waitFor(1000) const url = await browser.eval( `document.getElementById("basic-static").src` ) const res = await fetch(url) expect(res.headers.get('cache-control')).toBe( 'public, max-age=315360000, immutable' ) }) it('Should use immutable cache-control header even when unoptimized', async () => { await browser.eval( `document.getElementById("static-unoptimized").scrollIntoView()` ) await waitFor(1000) const url = await browser.eval( `document.getElementById("static-unoptimized").src` ) const res = await fetch(url) expect(res.headers.get('cache-control')).toBe( 'public, max-age=31536000, immutable' ) }) it('Should automatically provide an image height and width', async () => { expect(html).toContain('width:400px;height:300px') }) it('Should allow provided width and height to override intrinsic', async () => { expect(html).toContain('width:200px;height:200px') expect(html).not.toContain('width:400px;height:400px') }) it('Should add a blur placeholder to statically imported jpg', async () => { expect(html).toContain( `style="position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;filter:blur(20px);background-size:cover;background-image:url(&quot;data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoKCgoKCgsMDAsPEA4QDxYUExMUFiIYGhgaGCIzICUgICUgMy03LCksNy1RQDg4QFFeT0pPXnFlZXGPiI+7u/sBCgoKCgoKCwwMCw8QDhAPFhQTExQWIhgaGBoYIjMgJSAgJSAzLTcsKSw3LVFAODhAUV5PSk9ecWVlcY+Ij7u7+//CABEIAAYACAMBIgACEQEDEQH/xAAnAAEBAAAAAAAAAAAAAAAAAAAABwEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEAMQAAAAmgP/xAAcEAACAQUBAAAAAAAAAAAAAAASFBMAAQMFERX/2gAIAQEAAT8AZ1HjrKZX55JysIc4Ff/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z&quot;);background-position:0% 0%"` ) }) it('Should add a blur placeholder to statically imported png', async () => { expect(html).toContain( `style="position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;filter:blur(20px);background-size:cover;background-image:url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAAAAADhZOFXAAAAOklEQVR42iWGsQkAIBDE0iuIdiLOJjiGIzjiL/Meb4okiNYIlLjK3hJMzCQG1/0qmXXOUkjAV+m9wAMe3QiV6Ne8VgAAAABJRU5ErkJggg==&quot;);background-position:0% 0%"` ) }) } describe('Build Error Tests', () => { it('should throw build error when import statement is used with missing file', async () => { await indexPage.replace( '../public/foo/test-rect.jpg', '../public/foo/test-rect-broken.jpg' ) const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) await indexPage.restore() expect(stderr).toContain( "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg" ) // should contain the importing module expect(stderr).toContain('./pages/static-img.js') // should contain a import trace expect(stderr).not.toContain('Import trace for requested module') }) }) describe('Static Image Component Tests', () => { beforeAll(async () => { await nextBuild(appDir) appPort = await findPort() app = await nextStart(appDir, appPort) html = await renderViaHTTP(appPort, '/static-img') browser = await webdriver(appPort, '/static-img') }) afterAll(() => { killApp(app) }) runTests() })
const DrawCard = require('../../drawcard.js'); class AeronDamphair extends DrawCard { setupCardAbilities() { this.reaction({ when: { onCardSaved: event => event.card.getType() === 'character' }, handler: context => { let card = context.event.card; if(card.kneeled) { card.controller.standCard(card); this.game.addMessage('{0} uses {1} to stand {2}', this.controller, this, card); } else { card.controller.kneelCard(card); this.game.addMessage('{0} uses {1} to kneel {2}', this.controller, this, card); } } }); } } AeronDamphair.code = '04071'; module.exports = AeronDamphair;
function foo() { throw <Bar />; } function foo() { throw <Bar>baz</Bar>; } function foo() { throw <Bar baz={baz} />; } function foo() { throw <Bar baz={baz}>foo</Bar>; } function foo() { throw <></>; } function foo() { throw <>foo</>; }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // This is a very simple test, and could be made more robust. // All we do is check for the presence of "http://" or "https://" // at the start of the string. var description = 'Relative src URLs can break (i.e. if recipients are outside the company network) and make your content unavailable to view.'; exports.default = function (props) { if (props.hasOwnProperty('src')) { if (!/^https?:\/\//.test(props['src'])) { return new Error(description); } } };
var assert = require('assert'); var R = require('..'); describe('join', function() { it("concatenates a list's elements to a string, with an seperator string between elements", function() { var list = [1, 2, 3, 4]; assert.strictEqual(R.join('~', list), '1~2~3~4'); }); });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fas'; var iconName = 'intersection'; var width = 384; var height = 512; var ligatures = []; var unicode = 'f668'; var svgPathData = 'M166.74 33.62C69.96 46.04 0 133.11 0 230.68V464c0 8.84 7.16 16 16 16h64c8.84 0 16-7.16 16-16V224c0-59.2 53.85-106.04 115.13-94.14 45.58 8.85 76.87 51.5 76.87 97.93V464c0 8.84 7.16 16 16 16h64c8.84 0 16-7.16 16-16V224c0-114.18-100.17-205.4-217.26-190.38z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faIntersection = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
/* * Moonshine - a Lua virtual machine. * * Email: [email protected] * http://moonshinejs.org * * Copyright (c) 2013-2015 Gamesys Limited. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @fileOverview File class. * @author <a href="mailto:[email protected]">Paul Cuthbertson</a> */ 'use strict'; var shine = shine || {}; /** * Represents a Luac data file. * @constructor * @extends shine.EventEmitter * @param {String} url Url of the distilled JSON file. */ shine.File = function (url, data) { this.url = url; this.data = data; }; /** * Dump memory associated with file. */ shine.File.prototype.dispose = function () { delete this.url; delete this.data; };
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- var promises = require('../utilities/promises'), log = require('../logger'); module.exports = function (tables) { log.warn('The memory data provider is deprecated and will be removed from future versions. Use the sqlite provider instead.'); tables = tables || {}; return function (table) { return { read: function (query) { // need to evaluate query against each item before returning return promises.resolved(values(table)); }, update: function (item) { items(table)[item.id] = item; return promises.resolved(item); }, insert: function (item) { items(table)[item.id] = item; return promises.resolved(item); }, delete: function (id, version) { delete items(table)[id]; return promises.resolved(id); }, undelete: function (id) { // unsupported return promises.resolved({ id: id }); }, truncate: function () { tables[table.name] = {}; return promises.resolved(); }, initialize: function () { return promises.resolved(); } } function items(table) { var name = table.name.toLowerCase(); if(!tables[name]) tables[name] = {}; return tables[name]; } function values(table) { var tableItems = items(table); return Object.keys(tableItems).map(function (id) { return tableItems[id]; }); } }; };
/*globals EmberDev */ import Ember from "ember-metal/core"; import {get} from "ember-metal/property_get"; import {set} from "ember-metal/property_set"; import {forEach} from "ember-metal/array"; import run from "ember-metal/run_loop"; import Application from "ember-application/system/application"; import {DefaultResolver} from "ember-application/system/resolver"; import Router from "ember-routing/system/router"; import {View} from "ember-views/views/view"; import {Controller} from "ember-runtime/controllers/controller"; import NoneLocation from "ember-routing/location/none_location"; import EmberHandlebars from "ember-handlebars"; import EmberObject from "ember-runtime/system/object"; import {outletHelper} from "ember-routing/helpers/outlet"; import jQuery from "ember-views/system/jquery"; var trim = jQuery.trim; var view, app, application, originalLookup, originalDebug; module("Ember.Application", { setup: function() { originalLookup = Ember.lookup; originalDebug = Ember.debug; jQuery("#qunit-fixture").html("<div id='one'><div id='one-child'>HI</div></div><div id='two'>HI</div>"); run(function() { application = Application.create({ rootElement: '#one', router: null }); }); }, teardown: function() { jQuery("#qunit-fixture").empty(); Ember.debug = originalDebug; Ember.lookup = originalLookup; if (application) { run(application, 'destroy'); } if (app) { run(app, 'destroy'); } } }); test("you can make a new application in a non-overlapping element", function() { run(function() { app = Application.create({ rootElement: '#two', router: null }); }); run(app, 'destroy'); ok(true, "should not raise"); }); test("you cannot make a new application that is a parent of an existing application", function() { expectAssertion(function() { run(function() { Application.create({ rootElement: '#qunit-fixture' }); }); }); }); test("you cannot make a new application that is a descendent of an existing application", function() { expectAssertion(function() { run(function() { Application.create({ rootElement: '#one-child' }); }); }); }); test("you cannot make a new application that is a duplicate of an existing application", function() { expectAssertion(function() { run(function() { Application.create({ rootElement: '#one' }); }); }); }); test("you cannot make two default applications without a rootElement error", function() { expectAssertion(function() { run(function() { Application.create({ router: false }); }); }); }); test("acts like a namespace", function() { var lookup = Ember.lookup = {}, app; run(function() { app = lookup.TestApp = Application.create({ rootElement: '#two', router: false }); }); Ember.BOOTED = false; app.Foo = EmberObject.extend(); equal(app.Foo.toString(), "TestApp.Foo", "Classes pick up their parent namespace"); }); module("Ember.Application initialization", { teardown: function() { if (app) { run(app, 'destroy'); } Ember.TEMPLATES = {}; } }); test('initialized application go to initial route', function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); app.register('template:application', EmberHandlebars.compile("{{outlet}}") ); Ember.TEMPLATES.index = EmberHandlebars.compile( "<h1>Hi from index</h1>" ); }); equal(jQuery('#qunit-fixture h1').text(), "Hi from index"); }); test("initialize application via initialize call", function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); app.ApplicationView = View.extend({ template: function() { return "<h1>Hello!</h1>"; } }); }); // This is not a public way to access the container; we just // need to make some assertions about the created router var router = app.__container__.lookup('router:main'); equal(router instanceof Router, true, "Router was set from initialize call"); equal(router.location instanceof NoneLocation, true, "Location was set from location implementation name"); }); test("initialize application with stateManager via initialize call from Router class", function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); app.register('template:application', function() { return "<h1>Hello!</h1>"; }); }); var router = app.__container__.lookup('router:main'); equal(router instanceof Router, true, "Router was set from initialize call"); equal(jQuery("#qunit-fixture h1").text(), "Hello!"); }); test("ApplicationView is inserted into the page", function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.ApplicationView = View.extend({ render: function(buffer) { buffer.push("<h1>Hello!</h1>"); } }); app.ApplicationController = Controller.extend(); app.Router.reopen({ location: 'none' }); }); equal(jQuery("#qunit-fixture h1").text(), "Hello!"); }); test("Minimal Application initialized with just an application template", function() { jQuery('#qunit-fixture').html('<script type="text/x-handlebars">Hello World</script>'); run(function () { app = Application.create({ rootElement: '#qunit-fixture' }); }); equal(trim(jQuery('#qunit-fixture').text()), 'Hello World'); }); test('enable log of libraries with an ENV var', function() { if (EmberDev && EmberDev.runningProdBuild){ ok(true, 'Logging does not occur in production builds'); return; } var debug = Ember.debug; var messages = []; Ember.LOG_VERSION = true; Ember.debug = function(message) { messages.push(message); }; Ember.libraries.register("my-lib", "2.0.0a"); run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); }); equal(messages[1], "Ember : " + Ember.VERSION); equal(messages[2], "Handlebars : " + EmberHandlebars.VERSION); equal(messages[3], "jQuery : " + jQuery().jquery); equal(messages[4], "my-lib : " + "2.0.0a"); Ember.libraries.deRegister("my-lib"); Ember.LOG_VERSION = false; Ember.debug = debug; }); test('disable log version of libraries with an ENV var', function() { var logged = false; Ember.LOG_VERSION = false; Ember.debug = function(message) { logged = true; }; jQuery("#qunit-fixture").empty(); run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); }); ok(!logged, 'library version logging skipped'); }); test("can resolve custom router", function(){ var CustomRouter = Router.extend(); var CustomResolver = DefaultResolver.extend({ resolveOther: function(parsedName){ if (parsedName.type === "router") { return CustomRouter; } else { return this._super(parsedName); } } }); app = run(function(){ return Application.create({ Resolver: CustomResolver }); }); ok(app.__container__.lookup('router:main') instanceof CustomRouter, 'application resolved the correct router'); });
/** * rcmuserAdminUsersApp.rcmuserAdminUsers */ angular.module('rcmuserAdminUsersApp').controller( 'rcmuserAdminUsers', [ '$window', '$scope', '$log', '$uibModal', 'RcmUserResult', 'RcmResults', 'rcmUserUserService', function ( $window, $scope, $log, $uibModal, RcmUserResult, RcmResults, rcmUserUserService ) { var self = this; var userServiceEventManager = rcmUserUserService.getEventManager(); $scope.loading = true; userServiceEventManager.on( 'RcmUserHttp.loading', function (loading) { $scope.loading = loading; } ); $scope.userQuery = ''; $scope.availableStates = [ 'enabled', 'disabled' ]; // User $scope.showMessages = false; var onError = function (data) { $window.alert('An error occurred'); console.error(data); }; var onGetUsersSuccess = function (data) { $scope.users = data.data; $scope.messages = data.messages; }; rcmUserUserService.getUsers( onGetUsersSuccess, onError ); var onGetRolesSuccess = function (data) { $scope.roles = data.data; $scope.messages = data.messages; }; // User Roles rcmUserUserService.getRoles( onGetRolesSuccess, onError ); var onValidUserStatesSuccess = function (data, status) { $scope.availableStates = data.data; }; // valid user states rcmUserUserService.getValidUserStates( onValidUserStatesSuccess ); $scope.rolePropertyId = rcmUserUserService.getPropertyRoleId(); $scope.oneAtATime = false; $scope.addUser = function () { var user = { username: '', password: null, state: 'disabled', email: '', name: '', properties: {}, isNew: true }; user.properties[$scope.rolePropertyId] = []; $scope.users.unshift(user); // clear filter $scope.userQuery = ''; } } ] );
(function(w){function D(c,b,f,k){if(b.points.errorbars){c=[{x:!0,number:!0,required:!0},{y:!0,number:!0,required:!0}];f=b.points.errorbars;if("x"==f||"xy"==f)b.points.xerr.asymmetric&&c.push({x:!0,number:!0,required:!0}),c.push({x:!0,number:!0,required:!0});if("y"==f||"xy"==f)b.points.yerr.asymmetric&&c.push({y:!0,number:!0,required:!0}),c.push({y:!0,number:!0,required:!0});k.format=c}}function A(c,b,f,k,e,u,h,B,a,C,n){k+=C;e+=C;u+=C;"x"==b.err?(e>f+a?v(c,[[e,k],[Math.max(f+a,n[0]),k]]):h=!1,u<f- a?v(c,[[Math.min(f-a,n[1]),k],[u,k]]):B=!1):(e<k-a?v(c,[[f,e],[f,Math.min(k-a,n[0])]]):h=!1,u>k+a?v(c,[[f,Math.max(k+a,n[1])],[f,u]]):B=!1);a=null!=b.radius?b.radius:a;h&&("-"==b.upperCap?"x"==b.err?v(c,[[e,k-a],[e,k+a]]):v(c,[[f-a,e],[f+a,e]]):w.isFunction(b.upperCap)&&("x"==b.err?b.upperCap(c,e,k,a):b.upperCap(c,f,e,a)));B&&("-"==b.lowerCap?"x"==b.err?v(c,[[u,k-a],[u,k+a]]):v(c,[[f-a,u],[f+a,u]]):w.isFunction(b.lowerCap)&&("x"==b.err?b.lowerCap(c,u,k,a):b.lowerCap(c,f,u,a)))}function v(c,b){c.beginPath(); c.moveTo(b[0][0],b[0][1]);for(var f=1;f<b.length;f++)c.lineTo(b[f][0],b[f][1]);c.stroke()}function E(c,b){var f=c.getPlotOffset();b.save();b.translate(f.left,f.top);w.each(c.getData(),function(c,e){if(e.points.errorbars&&(e.points.xerr.show||e.points.yerr.show)){c=e.datapoints.points;var f=e.datapoints.pointsize,h=[e.xaxis,e.yaxis],k=e.points.radius,a=[e.points.xerr,e.points.yerr],v=!1;if(h[0].p2c(h[0].max)<h[0].p2c(h[0].min)){v=!0;var n=a[0].lowerCap;a[0].lowerCap=a[0].upperCap;a[0].upperCap=n}var w= !1;h[1].p2c(h[1].min)<h[1].p2c(h[1].max)&&(w=!0,n=a[1].lowerCap,a[1].lowerCap=a[1].upperCap,a[1].upperCap=n);for(var p=0;p<e.datapoints.points.length;p+=f){var d=e.datapoints.points,q=null,r=null,l=null,m=null;var x=e.points.xerr;var g=e.points.yerr,t=e.points.errorbars;"x"==t||"xy"==t?x.asymmetric?(q=d[p+2],r=d[p+3],"xy"==t&&(g.asymmetric?(l=d[p+4],m=d[p+5]):l=d[p+4])):(q=d[p+2],"xy"==t&&(g.asymmetric?(l=d[p+3],m=d[p+4]):l=d[p+3])):"y"==t&&(g.asymmetric?(l=d[p+2],m=d[p+3]):l=d[p+2]);null==r&&(r= q);null==m&&(m=l);d=[q,r,l,m];x.show||(d[0]=null,d[1]=null);g.show||(d[2]=null,d[3]=null);x=d;for(g=0;g<a.length;g++)if(d=[h[g].min,h[g].max],x[g*a.length]&&(q=c[p],r=c[p+1],l=[q,r][g]+x[g*a.length+1],m=[q,r][g]-x[g*a.length],"x"!=a[g].err||!(r>h[1].max||r<h[1].min||l<h[0].min||m>h[0].max)))if("y"!=a[g].err||!(q>h[0].max||q<h[0].min||l<h[1].min||m>h[1].max)){var y=t=!0;l>d[1]&&(t=!1,l=d[1]);m<d[0]&&(y=!1,m=d[0]);if("x"==a[g].err&&v||"y"==a[g].err&&w)n=m,m=l,l=n,n=y,y=t,t=n,n=d[0],d[0]=d[1],d[1]=n; q=h[0].p2c(q);r=h[1].p2c(r);l=h[g].p2c(l);m=h[g].p2c(m);d[0]=h[g].p2c(d[0]);d[1]=h[g].p2c(d[1]);n=a[g].lineWidth?a[g].lineWidth:e.points.lineWidth;var z=null!=e.points.shadowSize?e.points.shadowSize:e.shadowSize;0<n&&0<z&&(z/=2,b.lineWidth=z,b.strokeStyle="rgba(0,0,0,0.1)",A(b,a[g],q,r,l,m,t,y,k,z+z/2,d),b.strokeStyle="rgba(0,0,0,0.2)",A(b,a[g],q,r,l,m,t,y,k,z/2,d));b.strokeStyle=a[g].color?a[g].color:e.color;b.lineWidth=n;A(b,a[g],q,r,l,m,t,y,k,0,d)}}}});b.restore()}w.plot.plugins.push({init:function(c){c.hooks.processRawData.push(D); c.hooks.draw.push(E)},options:{series:{points:{errorbars:null,xerr:{err:"x",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null},yerr:{err:"y",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null}}}},name:"errorbars",version:"1.0"})})(jQuery);
(function () { 'use strict'; function foo () { return embiggen( 6, 7 ); } /** * Embiggens a number * @param {number} num - the number to embiggen * @param {number} factor - the factor to embiggen it by * @returns {number} */ function embiggen ( num, factor ) { return num * factor; } alert( foo() ); }());
require('./options-styles'); var CodeMirror = require('codemirror'); require('codemirror/addon/fold/foldcode'); require('codemirror/addon/fold/foldgutter'); require('codemirror/addon/fold/brace-fold'); require('codemirror/mode/javascript/javascript'); require('codemirror/addon/hint/show-hint'); require('codemirror/addon/hint/css-hint'); require('codemirror/mode/css/css'); var sweetAlert = require('sweetalert'); var Storage = require('./json-viewer/storage'); var renderThemeList = require('./json-viewer/options/render-theme-list'); var renderAddons = require('./json-viewer/options/render-addons'); var renderStructure = require('./json-viewer/options/render-structure'); var renderStyle = require('./json-viewer/options/render-style'); var bindSaveButton = require('./json-viewer/options/bind-save-button'); var bindResetButton = require('./json-viewer/options/bind-reset-button'); function isValidJSON(pseudoJSON) { try { JSON.parse(pseudoJSON); return true; } catch(e) { return false; } } function renderVersion() { var version = process.env.VERSION; var versionLink = document.getElementsByClassName('version')[0]; versionLink.innerHTML = version; versionLink.href = "https://github.com/tulios/json-viewer/tree/" + version; } function onLoaded() { var currentOptions = Storage.load(); renderVersion(); renderThemeList(CodeMirror, currentOptions.theme); var addonsEditor = renderAddons(CodeMirror, currentOptions.addons); var structureEditor = renderStructure(CodeMirror, currentOptions.structure); var styleEditor = renderStyle(CodeMirror, currentOptions.style); bindResetButton(); bindSaveButton([addonsEditor, structureEditor, styleEditor], function(options) { if (!isValidJSON(options.addons)) { sweetAlert("Ops!", "\"Add-ons\" isn't a valid JSON", "error"); } else if (!isValidJSON(options.structure)) { sweetAlert("Ops!", "\"Structure\" isn't a valid JSON", "error"); } else { Storage.save(options); sweetAlert("Success", "Options saved!", "success"); } }); } document.addEventListener("DOMContentLoaded", onLoaded, false);
/** * Theme: Simple Admin Template * Author: Coderthemes * VectorMap */ ! function($) { "use strict"; var VectorMap = function() { }; VectorMap.prototype.init = function() { //various examples $('#world-map-markers').vectorMap({ map : 'world_mill_en', scaleColors : ['#4bd396', '#4bd396'], normalizeFunction : 'polynomial', hoverOpacity : 0.7, hoverColor : false, regionStyle : { initial : { fill : '#ddd' } }, markerStyle: { initial: { r: 9, 'fill': '#4bd396', 'fill-opacity': 0.9, 'stroke': '#fff', 'stroke-width' : 7, 'stroke-opacity': 0.4 }, hover: { 'stroke': '#fff', 'fill-opacity': 1, 'stroke-width': 1.5 } }, backgroundColor : 'transparent', markers : [{ latLng : [41.90, 12.45], name : 'Vatican City' }, { latLng : [43.73, 7.41], name : 'Monaco' }, { latLng : [-0.52, 166.93], name : 'Nauru' }, { latLng : [-8.51, 179.21], name : 'Tuvalu' }, { latLng : [43.93, 12.46], name : 'San Marino' }, { latLng : [47.14, 9.52], name : 'Liechtenstein' }, { latLng : [7.11, 171.06], name : 'Marshall Islands' }, { latLng : [17.3, -62.73], name : 'Saint Kitts and Nevis' }, { latLng : [3.2, 73.22], name : 'Maldives' }, { latLng : [35.88, 14.5], name : 'Malta' }, { latLng : [12.05, -61.75], name : 'Grenada' }, { latLng : [13.16, -61.23], name : 'Saint Vincent and the Grenadines' }, { latLng : [13.16, -59.55], name : 'Barbados' }, { latLng : [17.11, -61.85], name : 'Antigua and Barbuda' }, { latLng : [-4.61, 55.45], name : 'Seychelles' }, { latLng : [7.35, 134.46], name : 'Palau' }, { latLng : [42.5, 1.51], name : 'Andorra' }, { latLng : [14.01, -60.98], name : 'Saint Lucia' }, { latLng : [6.91, 158.18], name : 'Federated States of Micronesia' }, { latLng : [1.3, 103.8], name : 'Singapore' }, { latLng : [1.46, 173.03], name : 'Kiribati' }, { latLng : [-21.13, -175.2], name : 'Tonga' }, { latLng : [15.3, -61.38], name : 'Dominica' }, { latLng : [-20.2, 57.5], name : 'Mauritius' }, { latLng : [26.02, 50.55], name : 'Bahrain' }, { latLng : [0.33, 6.73], name : 'São Tomé and Príncipe' }] }); $('#usa').vectorMap({ map : 'us_aea_en', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#india').vectorMap({ map : 'in_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#uk').vectorMap({ map : 'uk_mill_en', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#chicago').vectorMap({ map : 'us-il-chicago_mill_en', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#australia').vectorMap({ map : 'au_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#canada').vectorMap({ map : 'ca_lcc', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#germany').vectorMap({ map : 'de_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#asia').vectorMap({ map : 'asia_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); }, //init $.VectorMap = new VectorMap, $.VectorMap.Constructor = VectorMap }(window.jQuery), //initializing function($) { "use strict"; $.VectorMap.init() }(window.jQuery);
/*eslint-env node */ module.exports = function (grunt) { grunt.initConfig({ "bolt-init": { "plugin": { config_dir: "config/bolt" } }, "bolt-build": { "plugin": { config_js: "config/bolt/prod.js", output_dir: "scratch", main: "tinymce.wordcount.Plugin", filename: "plugin", generate_inline: true, minimise_module_names: true, files: { src: ["src/main/js/tinymce/wordcount/Plugin.js"] } } }, copy: { "plugin": { files: [ { src: "scratch/inline/plugin.raw.js", dest: "plugin.js" } ] } }, eslint: { options: { config: "../../../../.eslintrc" }, src: [ "src" ] }, uglify: { options: { beautify: { ascii_only: true, screw_ie8: false }, compress: { screw_ie8: false } }, "plugin": { files: [ { src: "scratch/inline/plugin.js", dest: "plugin.min.js" } ] } } }); grunt.task.loadTasks("../../../../node_modules/@ephox/bolt/tasks"); grunt.task.loadTasks("../../../../node_modules/grunt-contrib-copy/tasks"); grunt.task.loadTasks("../../../../node_modules/grunt-contrib-uglify/tasks"); grunt.task.loadTasks("../../../../node_modules/grunt-eslint/tasks"); grunt.registerTask("default", ["bolt-init", "bolt-build", "copy", "eslint", "uglify"]); };
'use strict'; Editor.polymerElement({ });
//>>built define({"days-standAlone-short":"dom seg ter qua qui sex s\u00e1b".split(" "),"field-weekday":"Dia da semana","field-wed-relative+0":"esta quarta-feira","field-wed-relative+1":"pr\u00f3xima quarta-feira","dateFormatItem-GyMMMEd":"E, d 'de' MMM 'de' y G","dateFormatItem-MMMEd":"E, d 'de' MMM","field-tue-relative+-1":"ter\u00e7a-feira passada","days-format-short":"dom seg ter qua qui sex s\u00e1b".split(" "),"dateFormat-long":"d 'de' MMMM 'de' y G","field-fri-relative+-1":"sexta-feira passada","field-wed-relative+-1":"quarta-feira passada", "dateFormatItem-yyyyQQQ":"QQQQ 'de' y G","dateTimeFormat-medium":"{1}, {0}","dayPeriods-format-wide-pm":"da tarde","dateFormat-full":"EEEE, d 'de' MMMM 'de' y G","dateFormatItem-yyyyMEd":"E, dd/MM/y GGGGG","field-thu-relative+-1":"quinta-feira passada","dateFormatItem-Md":"d/M","dayPeriods-format-abbr-am":"a.m.","dayPeriods-format-wide-noon":"meio-dia","field-era":"Era","quarters-format-wide":["1.\u00ba trimestre","2.\u00ba trimestre","3.\u00ba trimestre","4.\u00ba trimestre"],"field-year":"Ano", "field-hour":"Hora","field-sat-relative+0":"este s\u00e1bado","field-sat-relative+1":"pr\u00f3ximo s\u00e1bado","field-day-relative+0":"hoje","field-thu-relative+0":"esta quinta-feira","field-day-relative+1":"amanh\u00e3","field-thu-relative+1":"pr\u00f3xima quinta-feira","dateFormatItem-GyMMMd":"d 'de' MMM 'de' y G","field-day-relative+2":"depois de amanh\u00e3","quarters-format-abbr":["T1","T2","T3","T4"],"quarters-standAlone-wide":["1.\u00ba trimestre","2.\u00ba trimestre","3.\u00ba trimestre", "4.\u00ba trimestre"],"dateFormatItem-Gy":"y G","dateFormatItem-yyyyMMMEd":"E, d/MM/y G","days-standAlone-wide":"domingo segunda-feira ter\u00e7a-feira quarta-feira quinta-feira sexta-feira s\u00e1bado".split(" "),"dateFormatItem-yyyyMMM":"MM/y G","dateFormatItem-yyyyMMMd":"d/MM/y G","field-sun-relative+0":"este domingo","field-sun-relative+1":"pr\u00f3ximo domingo","quarters-standAlone-abbr":["T1","T2","T3","T4"],"field-minute":"Minuto","field-dayperiod":"Da manh\u00e3/da tarde","days-standAlone-abbr":"dom seg ter qua qui sex s\u00e1b".split(" "), "field-day-relative+-1":"ontem","dateTimeFormat-long":"{1} '\u00e0s' {0}","dayPeriods-format-narrow-am":"a.m.","field-day-relative+-2":"anteontem","dateFormatItem-MMMd":"d 'de' MMM","dateFormatItem-MEd":"E, dd/MM","dateTimeFormat-full":"{1} '\u00e0s' {0}","field-fri-relative+0":"esta sexta-feira","field-fri-relative+1":"pr\u00f3xima sexta-feira","field-day":"Dia","days-format-wide":"domingo segunda-feira ter\u00e7a-feira quarta-feira quinta-feira sexta-feira s\u00e1bado".split(" "),"field-zone":"Fuso hor\u00e1rio", "dateFormatItem-y":"y G","field-year-relative+-1":"ano passado","field-month-relative+-1":"m\u00eas passado","dayPeriods-format-abbr-pm":"p.m.","days-format-abbr":"dom seg ter qua qui sex s\u00e1b".split(" "),"days-format-narrow":"DSTQQSS".split(""),"dateFormatItem-yyyyMd":"dd/MM/y GGGGG","field-month":"M\u00eas","days-standAlone-narrow":"DSTQQSS".split(""),"field-tue-relative+0":"esta ter\u00e7a-feira","field-tue-relative+1":"pr\u00f3xima ter\u00e7a-feira","dayPeriods-format-wide-am":"da manh\u00e3", "field-mon-relative+0":"esta segunda-feira","field-mon-relative+1":"pr\u00f3xima segunda-feira","dateFormat-short":"d/M/y G","field-second":"Segundo","field-sat-relative+-1":"s\u00e1bado passado","field-sun-relative+-1":"domingo passado","field-month-relative+0":"este m\u00eas","field-month-relative+1":"pr\u00f3ximo m\u00eas","dateFormatItem-Ed":"E, d","field-week":"Semana","dateFormat-medium":"d 'de' MMM, y G","field-year-relative+0":"este ano","field-week-relative+-1":"semana passada","dateFormatItem-yyyyM":"MM/y GGGGG", "field-year-relative+1":"pr\u00f3ximo ano","dayPeriods-format-narrow-pm":"p.m.","dateFormatItem-yyyyQQQQ":"QQQQ 'de' y G","dateTimeFormat-short":"{1}, {0}","dateFormatItem-GyMMM":"MMM 'de' y G","field-mon-relative+-1":"segunda-feira passada","dateFormatItem-yyyy":"y G","field-week-relative+0":"esta semana","field-week-relative+1":"pr\u00f3xima semana"});
class A { static get #x() {} get #x() {} }
const fs = require('fs'); const fse = require('fs-extra'); const path = require('path'); module.exports = function (params) { const unpackFile = path.join( params.appOutDir, '*NAMECASENOSPACE*.app/Contents/Resources/app.asar.unpacked' ); fse.removeSync(unpackFile); };
var WINDOW = { ms_Width: 0, ms_Height: 0, ms_Callbacks: { 70: "WINDOW.toggleFullScreen()" // Toggle fullscreen }, initialize: function initialize() { this.updateSize(); // Create callbacks from keyboard $(document).keydown(function(inEvent) { WINDOW.callAction(inEvent.keyCode); }) ; $(window).resize(function(inEvent) { WINDOW.updateSize(); WINDOW.resizeCallback(WINDOW.ms_Width, WINDOW.ms_Height); }); }, updateSize: function updateSize() { this.ms_Width = $(window).width(); this.ms_Height = $(window).height() - 4; }, callAction: function callAction(inId) { if(inId in this.ms_Callbacks) { eval(this.ms_Callbacks[inId]); return false ; } }, toggleFullScreen: function toggleFullScreen() { if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) { if(document.documentElement.requestFullscreen) document.documentElement.requestFullscreen(); else if(document.documentElement.mozRequestFullScreen) document.documentElement.mozRequestFullScreen(); else if(document.documentElement.webkitRequestFullscreen) document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } else { if(document.cancelFullScreen) document.cancelFullScreen(); else if(document.mozCancelFullScreen) document.mozCancelFullScreen(); else if (document.webkitCancelFullScreen) document.webkitCancelFullScreen(); } }, resizeCallback: function resizeCallback(inWidth, inHeight) {} };
// Converted from: ../../examples/obj/torus/Torus.obj // vertices: 576 // faces: 576 // materials: 1 // // Generated with OBJ -> Three.js converter // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_three.py var model = { "version" : 1, "materials": [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "(null)" }], "buffers": "Torus_bin.bin" }; postMessage( model ); close();
/*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); /** * Schema validator error * * @param {Object} properties * @inherits MongooseError * @api private */ function ValidatorError(properties) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } const message = this.formatMessage(msg, properties); MongooseError.call(this, message); properties = Object.assign({}, properties, { message: message }); this.name = 'ValidatorError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.properties = properties; this.kind = properties.type; this.path = properties.path; this.value = properties.value; this.reason = properties.reason; } /*! * Inherits from MongooseError */ ValidatorError.prototype = Object.create(MongooseError.prototype); ValidatorError.prototype.constructor = MongooseError; /*! * The object used to define this validator. Not enumerable to hide * it from `require('util').inspect()` output re: gh-3925 */ Object.defineProperty(ValidatorError.prototype, 'properties', { enumerable: false, writable: true, value: null }); /*! * Formats error messages */ ValidatorError.prototype.formatMessage = function(msg, properties) { if (typeof msg === 'function') { return msg(properties); } const propertyNames = Object.keys(properties); for (let i = 0; i < propertyNames.length; ++i) { const propertyName = propertyNames[i]; if (propertyName === 'message') { continue; } msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); } return msg; }; /*! * toString helper */ ValidatorError.prototype.toString = function() { return this.message; }; /*! * exports */ module.exports = ValidatorError;
/* @Name: Horizontal multilevel menu @Author: Muffin Group @WWW: www.muffingroup.com @Version: 1.5.2 */ (function($){ $.fn.extend({ muffingroup_menu: function(options) { var menu = $(this); var defaults = { delay : 100, hoverClass : 'hover', arrows : true, animation : 'fade', addLast : true }; options = $.extend(defaults, options); // add class if menu item has sumbenu menu.find("li:has(ul)") .addClass("submenu") .append("<span class='menu-toggle'>") // responsive menu toggle .append("<span class='menu-arr-bottom'></span><span class='menu-arr-top'></span>") // border arrows ; // add class if submanu item has another sumbenu if( options.arrows ) { menu.find( "li ul li:has(ul) > a" ).append( "<span class='menu-arrow'><i class='icon-chevron-right'></i></span>" ); } // add bullets in each top-level menu item menu.children( "li:not(:last)" ).append( "<em>&#8226;</em>" ); // hover menu.find("li").hover(function() { $(this).addClass(options.hoverClass); if (options.animation === "fade") { $(this).children("ul").fadeIn(options.delay); } else if (options.animation === "toggle") { $(this).children("ul").stop(true,true).slideDown(options.delay); } }, function(){ $(this).removeClass(options.hoverClass); if (options.animation === "fade") { $(this).children("ul").fadeOut(options.delay); } else if (options.animation === "toggle") { $(this).children("ul").stop(true,true).slideUp(options.delay); } }); // add class .last-item to last sumbenu item $(".submenu ul li:last-child", menu).addClass("last-item"); // addLast if(options.addLast) { $("> li:last-child", menu) .addClass("last") .prev() .addClass("last"); } } }); })(jQuery);
import Moment from 'moment'; import { functions, has, includes } from 'lodash'; export default function(dateString, context) { const date = Moment(dateString); if (has(context.hash, 'type') && includes(functions(date), context.hash.type)) { return date[context.hash.type](); } return date.calendar(); }
Clazz.declarePackage ("J.smiles"); Clazz.load (["java.util.Hashtable", "JU.BS", "J.smiles.VTemp"], "J.smiles.SmilesGenerator", ["JU.List", "$.SB", "J.smiles.InvalidSmilesException", "$.SmilesAromatic", "$.SmilesAtom", "$.SmilesBond", "$.SmilesParser", "$.SmilesSearch", "J.util.BSUtil", "$.Elements", "$.JmolMolecule", "$.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.atoms = null; this.atomCount = 0; this.bsSelected = null; this.bsAromatic = null; this.ringSets = null; this.vTemp = null; this.nPairs = 0; this.bsBondsUp = null; this.bsBondsDn = null; this.bsToDo = null; this.prevAtom = null; this.prevSp2Atoms = null; this.htRingsSequence = null; this.htRings = null; this.bsIncludingH = null; Clazz.instantialize (this, arguments); }, J.smiles, "SmilesGenerator"); Clazz.prepareFields (c$, function () { this.vTemp = new J.smiles.VTemp (); this.bsBondsUp = new JU.BS (); this.bsBondsDn = new JU.BS (); this.htRingsSequence = new java.util.Hashtable (); this.htRings = new java.util.Hashtable (); }); $_M(c$, "getSmiles", function (atoms, atomCount, bsSelected) { var i = bsSelected.nextSetBit (0); if (i < 0) return ""; this.atoms = atoms; this.atomCount = atomCount; this.bsSelected = bsSelected = J.util.BSUtil.copy (bsSelected); return this.getSmilesComponent (atoms[i], bsSelected, false); }, "~A,~N,JU.BS"); $_M(c$, "getBioSmiles", function (atoms, atomCount, bsSelected, allowUnmatchedRings, addCrossLinks, comment) { this.atoms = atoms; this.atomCount = atomCount; var sb = new JU.SB (); var bs = J.util.BSUtil.copy (bsSelected); if (comment != null) sb.append ("//* Jmol bioSMILES ").append (comment.$replace ('*', '_')).append (" *//"); var end = "\n"; var bsIgnore = new JU.BS (); var lastComponent = null; var s; var vLinks = new JU.List (); try { var len = 0; for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) { var a = atoms[i]; var ch = a.getGroup1 ('?'); var bioStructureName = a.getBioStructureTypeName (); var unknown = (ch.equals ("?")); if (end != null) { if (sb.length () > 0) sb.append (end); end = null; len = 0; if (bioStructureName.length > 0) { var id = a.getChainID (); if (id != 0) { s = "//* chain " + a.getChainIDStr () + " " + bioStructureName + " " + a.getResno () + " *// "; len = s.length; sb.append (s); }sb.append ("~").appendC (bioStructureName.charAt (0)).append ("~"); len++; } else { s = this.getSmilesComponent (a, bs, true); if (s.equals (lastComponent)) { end = ""; } else { lastComponent = s; var groupName = a.getGroup3 (true); if (groupName != null) sb.append ("//* ").append (groupName).append (" *//"); sb.append (s); end = ".\n"; }continue; }}if (len >= 75) { sb.append ("\n "); len = 2; }if (unknown) { this.addBracketedBioName (sb, a, bioStructureName.length > 0 ? ".0" : null); } else { sb.append (ch); }len++; var i0 = a.getOffsetResidueAtom ("0", 0); if (addCrossLinks) { a.getCrossLinkLeadAtomIndexes (vLinks); for (var j = 0; j < vLinks.size (); j++) { sb.append (":"); s = this.getRingCache (i0, vLinks.get (j).intValue (), this.htRingsSequence); sb.append (s); len += 1 + s.length; } vLinks.clear (); }a.getGroupBits (bsIgnore); bs.andNot (bsIgnore); var i2 = a.getOffsetResidueAtom ("0", 1); if (i2 < 0 || !bs.get (i2)) { sb.append (" //* ").appendI (a.getResno ()).append (" *//"); if (i2 < 0 && (i2 = bs.nextSetBit (i + 1)) < 0) break; if (len > 0) end = ".\n"; }i = i2 - 1; } } catch (e) { if (Clazz.exceptionOf (e, Exception)) { System.out.println (e.toString ()); return ""; } else { throw e; } } if (!allowUnmatchedRings && !this.htRingsSequence.isEmpty ()) { this.dumpRingKeys (sb, this.htRingsSequence); throw new J.smiles.InvalidSmilesException ("//* ?ring error? *//"); }s = sb.toString (); if (s.endsWith (".\n")) s = s.substring (0, s.length - 2); return s; }, "~A,~N,JU.BS,~B,~B,~S"); $_M(c$, "addBracketedBioName", ($fz = function (sb, a, atomName) { sb.append ("["); if (atomName != null) { var chain = a.getChainIDStr (); sb.append (a.getGroup3 (false)); if (!atomName.equals (".0")) sb.append (atomName).append ("#").appendI (a.getElementNumber ()); sb.append ("//* ").appendI (a.getResno ()); if (chain.length > 0) sb.append (":").append (chain); sb.append (" *//"); } else { sb.append (J.util.Elements.elementNameFromNumber (a.getElementNumber ())); }sb.append ("]"); }, $fz.isPrivate = true, $fz), "JU.SB,J.util.JmolNode,~S"); $_M(c$, "getSmilesComponent", ($fz = function (atom, bs, allowConnectionsToOutsideWorld) { if (atom.getElementNumber () == 1 && atom.getEdges ().length > 0) atom = this.atoms[atom.getBondedAtomIndex (0)]; this.bsSelected = J.util.JmolMolecule.getBranchBitSet (this.atoms, atom.getIndex (), J.util.BSUtil.copy (bs), null, -1, true, false); bs.andNot (this.bsSelected); this.bsIncludingH = J.util.BSUtil.copy (this.bsSelected); for (var j = this.bsSelected.nextSetBit (0); j >= 0; j = this.bsSelected.nextSetBit (j + 1)) { var a = this.atoms[j]; if (a.getElementNumber () == 1 && a.getIsotopeNumber () == 0) this.bsSelected.clear (j); } if (this.bsSelected.cardinality () > 2) { var search = null; search = J.smiles.SmilesParser.getMolecule ("A[=&@]A", true); search.jmolAtoms = this.atoms; search.setSelected (this.bsSelected); search.jmolAtomCount = this.atomCount; search.ringDataMax = 7; search.setRingData (null); this.bsAromatic = search.bsAromatic; this.ringSets = search.ringSets; this.setBondDirections (); } else { this.bsAromatic = new JU.BS (); }this.bsToDo = J.util.BSUtil.copy (this.bsSelected); var sb = new JU.SB (); for (var i = this.bsToDo.nextSetBit (0); i >= 0; i = this.bsToDo.nextSetBit (i + 1)) if (this.atoms[i].getCovalentBondCount () > 4) { this.getSmiles (sb, this.atoms[i], allowConnectionsToOutsideWorld, false); atom = null; } if (atom != null) while ((atom = this.getSmiles (sb, atom, allowConnectionsToOutsideWorld, true)) != null) { } while (this.bsToDo.cardinality () > 0 || !this.htRings.isEmpty ()) { var e = this.htRings.values ().iterator (); if (e.hasNext ()) { atom = this.atoms[(e.next ()[1]).intValue ()]; if (!this.bsToDo.get (atom.getIndex ())) break; } else { atom = this.atoms[this.bsToDo.nextSetBit (0)]; }sb.append ("."); this.prevSp2Atoms = null; this.prevAtom = null; while ((atom = this.getSmiles (sb, atom, allowConnectionsToOutsideWorld, true)) != null) { } } if (!this.htRings.isEmpty ()) { this.dumpRingKeys (sb, this.htRings); throw new J.smiles.InvalidSmilesException ("//* ?ring error? *//\n" + sb); }return sb.toString (); }, $fz.isPrivate = true, $fz), "J.util.JmolNode,JU.BS,~B"); $_M(c$, "getBondStereochemistry", ($fz = function (bond, atomFrom) { if (bond == null) return '\0'; var i = bond.index; var isFirst = (atomFrom == null || bond.getAtomIndex1 () == atomFrom.getIndex ()); return (this.bsBondsUp.get (i) ? (isFirst ? '/' : '\\') : this.bsBondsDn.get (i) ? (isFirst ? '\\' : '/') : '\0'); }, $fz.isPrivate = true, $fz), "J.util.JmolEdge,J.util.JmolNode"); $_M(c$, "setBondDirections", ($fz = function () { var bsDone = new JU.BS (); var edges = Clazz.newArray (2, 3, null); for (var i = this.bsSelected.nextSetBit (0); i >= 0; i = this.bsSelected.nextSetBit (i + 1)) { var atom1 = this.atoms[i]; var bonds = atom1.getEdges (); for (var k = 0; k < bonds.length; k++) { var bond = bonds[k]; var index = bond.index; if (bsDone.get (index)) continue; var atom2 = bond.getOtherAtomNode (atom1); if (bond.getCovalentOrder () != 2 || J.smiles.SmilesSearch.isRingBond (this.ringSets, i, atom2.getIndex ())) continue; bsDone.set (index); var b0 = null; var a0 = null; var i0 = 0; var atom12 = [atom1, atom2]; if (J.util.Logger.debugging) J.util.Logger.debug (atom1 + " == " + atom2); var edgeCount = 1; for (var j = 0; j < 2 && edgeCount > 0 && edgeCount < 3; j++) { edgeCount = 0; var atomA = atom12[j]; var bb = atomA.getEdges (); for (var b = 0; b < bb.length; b++) { if (bb[b].getCovalentOrder () != 1) continue; edges[j][edgeCount++] = bb[b]; if (this.getBondStereochemistry (bb[b], atomA) != '\0') { b0 = bb[b]; i0 = j; }} } if (edgeCount == 3 || edgeCount == 0) continue; if (b0 == null) { i0 = 0; b0 = edges[i0][0]; this.bsBondsUp.set (b0.index); }var c0 = this.getBondStereochemistry (b0, atom12[i0]); a0 = b0.getOtherAtomNode (atom12[i0]); if (a0 == null) continue; for (var j = 0; j < 2; j++) for (var jj = 0; jj < 2; jj++) { var b1 = edges[j][jj]; if (b1 == null || b1 === b0) continue; var bi = b1.index; var a1 = b1.getOtherAtomNode (atom12[j]); if (a1 == null) continue; var c1 = this.getBondStereochemistry (b1, atom12[j]); var isOpposite = J.smiles.SmilesSearch.isDiaxial (atom12[i0], atom12[j], a0, a1, this.vTemp, 0); if (c1 == '\0' || (c1 != c0) == isOpposite) { var isUp = (c0 == '\\' && isOpposite || c0 == '/' && !isOpposite); if (isUp == (b1.getAtomIndex1 () != a1.getIndex ())) this.bsBondsUp.set (bi); else this.bsBondsDn.set (bi); } else { J.util.Logger.error ("BOND STEREOCHEMISTRY ERROR"); }if (J.util.Logger.debugging) J.util.Logger.debug (this.getBondStereochemistry (b0, atom12[0]) + " " + a0.getIndex () + " " + a1.getIndex () + " " + this.getBondStereochemistry (b1, atom12[j])); } } } }, $fz.isPrivate = true, $fz)); $_M(c$, "getSmiles", ($fz = function (sb, atom, allowConnectionsToOutsideWorld, allowBranches) { var atomIndex = atom.getIndex (); if (!this.bsToDo.get (atomIndex)) return null; this.bsToDo.clear (atomIndex); var isExtension = (!this.bsSelected.get (atomIndex)); var prevIndex = (this.prevAtom == null ? -1 : this.prevAtom.getIndex ()); var isAromatic = this.bsAromatic.get (atomIndex); var havePreviousSp2Atoms = (this.prevSp2Atoms != null); var sp2Atoms = this.prevSp2Atoms; var nSp2Atoms = 0; var atomicNumber = atom.getElementNumber (); var nH = 0; var v = new JU.List (); var bond0 = null; var bondPrev = null; var bonds = atom.getEdges (); var aH = null; var stereoFlag = (isAromatic ? 10 : 0); var stereo = new Array (7); if (J.util.Logger.debugging) J.util.Logger.debug (sb.toString ()); if (bonds != null) for (var i = bonds.length; --i >= 0; ) { var bond = bonds[i]; if (!bond.isCovalent ()) continue; var atom1 = bonds[i].getOtherAtomNode (atom); var index1 = atom1.getIndex (); if (index1 == prevIndex) { bondPrev = bonds[i]; continue; }var isH = (atom1.getElementNumber () == 1 && atom1.getIsotopeNumber () == 0); if (!this.bsIncludingH.get (index1)) { if (!isH && allowConnectionsToOutsideWorld && this.bsSelected.get (atomIndex)) this.bsToDo.set (index1); else continue; }if (isH) { aH = atom1; nH++; if (nH > 1) stereoFlag = 10; } else { v.addLast (bonds[i]); }} var strBond = null; if (sp2Atoms == null) sp2Atoms = new Array (5); if (bondPrev != null) { strBond = J.smiles.SmilesBond.getBondOrderString (bondPrev.getCovalentOrder ()); if (this.prevSp2Atoms == null) sp2Atoms[nSp2Atoms++] = this.prevAtom; else nSp2Atoms = 2; }nSp2Atoms += nH; var nMax = 0; var bsBranches = new JU.BS (); if (allowBranches) for (var i = 0; i < v.size (); i++) { var bond = v.get (i); var a = bond.getOtherAtomNode (atom); var n = a.getCovalentBondCount () - a.getCovalentHydrogenCount (); var order = bond.getCovalentOrder (); if (order == 1 && n == 1 && i < v.size () - (bond0 == null ? 1 : 0)) { bsBranches.set (bond.index); } else if ((order > 1 || n > nMax) && !this.htRings.containsKey (J.smiles.SmilesGenerator.getRingKey (a.getIndex (), atomIndex))) { nMax = (order > 1 ? 1000 + order : n); bond0 = bond; }} var atomNext = (bond0 == null ? null : bond0.getOtherAtomNode (atom)); var orderNext = (bond0 == null ? 0 : bond0.getCovalentOrder ()); if (stereoFlag < 7 && bondPrev != null) { if (bondPrev.getCovalentOrder () == 2 && orderNext == 2 && this.prevSp2Atoms != null && this.prevSp2Atoms[1] != null) { stereo[stereoFlag++] = this.prevSp2Atoms[0]; stereo[stereoFlag++] = this.prevSp2Atoms[1]; } else { stereo[stereoFlag++] = this.prevAtom; }}if (stereoFlag < 7 && nH == 1) stereo[stereoFlag++] = aH; var deferStereo = (orderNext == 1 && this.prevSp2Atoms == null); var chBond = this.getBondStereochemistry (bondPrev, this.prevAtom); var sMore = new JU.SB (); for (var i = 0; i < v.size (); i++) { var bond = v.get (i); if (!bsBranches.get (bond.index)) continue; var a = bond.getOtherAtomNode (atom); var s2 = new JU.SB (); s2.append ("("); this.prevAtom = atom; this.prevSp2Atoms = null; var bond0t = bond0; this.getSmiles (s2, a, allowConnectionsToOutsideWorld, allowBranches); bond0 = bond0t; s2.append (")"); if (sMore.indexOf (s2.toString ()) >= 0) stereoFlag = 10; sMore.appendSB (s2); v.remove (i--); if (stereoFlag < 7) stereo[stereoFlag++] = a; if (nSp2Atoms < 5) sp2Atoms[nSp2Atoms++] = a; } var index2 = (orderNext == 2 ? atomNext.getIndex () : -1); if (nH > 1 || isAromatic || index2 < 0 || J.smiles.SmilesSearch.isRingBond (this.ringSets, atomIndex, index2)) { nSp2Atoms = -1; }if (nSp2Atoms < 0) sp2Atoms = null; if (strBond != null || chBond != '\0') { if (chBond != '\0') strBond = "" + chBond; sb.append (strBond); }var atat = null; if (!allowBranches && (v.size () == 5 || v.size () == 6)) atat = this.sortInorganic (atom, v); for (var i = 0; i < v.size (); i++) { var bond = v.get (i); if (bond === bond0) continue; var a = bond.getOtherAtomNode (atom); var s = this.getRingCache (atomIndex, a.getIndex (), this.htRings); strBond = J.smiles.SmilesBond.getBondOrderString (bond.order); if (!deferStereo) { chBond = this.getBondStereochemistry (bond, atom); if (chBond != '\0') strBond = "" + chBond; }sMore.append (strBond); sMore.append (s); if (stereoFlag < 7) stereo[stereoFlag++] = a; if (sp2Atoms != null && nSp2Atoms < 5) sp2Atoms[nSp2Atoms++] = a; } if (havePreviousSp2Atoms && stereoFlag == 2 && orderNext == 2 && atomNext.getCovalentBondCount () == 3) { bonds = atomNext.getEdges (); for (var k = 0; k < bonds.length; k++) { if (bonds[k].isCovalent () && atomNext.getBondedAtomIndex (k) != atomIndex) stereo[stereoFlag++] = this.atoms[atomNext.getBondedAtomIndex (k)]; } nSp2Atoms = 0; } else if (atomNext != null && stereoFlag < 7) { stereo[stereoFlag++] = atomNext; }var valence = atom.getValence (); var charge = atom.getFormalCharge (); var isotope = atom.getIsotopeNumber (); var atomName = atom.getAtomName (); var groupType = atom.getBioStructureTypeName (); if (J.util.Logger.debugging) sb.append ("\n//* " + atom + " *//\t"); if (isExtension && groupType.length != 0 && atomName.length != 0) this.addBracketedBioName (sb, atom, "." + atomName); else sb.append (J.smiles.SmilesAtom.getAtomLabel (atomicNumber, isotope, valence, charge, nH, isAromatic, atat != null ? atat : this.checkStereoPairs (atom, atomIndex, stereo, stereoFlag))); sb.appendSB (sMore); if (bond0 == null) return null; if (orderNext == 2 && (nSp2Atoms == 1 || nSp2Atoms == 2)) { if (sp2Atoms[0] == null) sp2Atoms[0] = atom; if (sp2Atoms[1] == null) sp2Atoms[1] = atom; } else { sp2Atoms = null; nSp2Atoms = 0; }this.prevSp2Atoms = sp2Atoms; this.prevAtom = atom; return atomNext; }, $fz.isPrivate = true, $fz), "JU.SB,J.util.JmolNode,~B,~B"); $_M(c$, "sortInorganic", ($fz = function (atom, v) { var atomIndex = atom.getIndex (); var n = v.size (); var axialPairs = new JU.List (); var bonds = new JU.List (); var a1; var a2; var bond1; var bond2; var bsDone = new JU.BS (); var pair0 = null; var stereo = new Array (6); var isOK = true; var s = ""; for (var i = 0; i < n; i++) { bond1 = v.get (i); stereo[0] = a1 = bond1.getOtherAtomNode (atom); if (i == 0) s = this.addStereoCheck (atomIndex, stereo, 0, ""); else if (isOK && this.addStereoCheck (atomIndex, stereo, 0, s) != null) isOK = false; if (bsDone.get (i)) continue; bsDone.set (i); var isAxial = false; for (var j = i + 1; j < n; j++) { if (bsDone.get (j)) continue; bond2 = v.get (j); a2 = bond2.getOtherAtomNode (atom); if (J.smiles.SmilesSearch.isDiaxial (atom, atom, a1, a2, this.vTemp, -0.95)) { axialPairs.addLast ([bond1, bond2]); isAxial = true; bsDone.set (j); break; }} if (!isAxial) bonds.addLast (bond1); } var nPairs = axialPairs.size (); if (isOK || n == 6 && nPairs != 3 || n == 5 && nPairs == 0) return ""; pair0 = axialPairs.get (0); bond1 = pair0[0]; stereo[0] = bond1.getOtherAtomNode (atom); v.clear (); v.addLast (bond1); if (nPairs > 1) bonds.addLast (axialPairs.get (1)[0]); if (nPairs == 3) bonds.addLast (axialPairs.get (2)[0]); if (nPairs > 1) bonds.addLast (axialPairs.get (1)[1]); if (nPairs == 3) bonds.addLast (axialPairs.get (2)[1]); for (var i = 0; i < bonds.size (); i++) { bond1 = bonds.get (i); v.addLast (bond1); stereo[i + 1] = bond1.getOtherAtomNode (atom); } v.addLast (pair0[1]); return J.smiles.SmilesGenerator.getStereoFlag (atom, stereo, n, this.vTemp); }, $fz.isPrivate = true, $fz), "J.util.JmolNode,JU.List"); $_M(c$, "checkStereoPairs", ($fz = function (atom, atomIndex, stereo, stereoFlag) { if (stereoFlag < 4) return ""; if (stereoFlag == 4 && (atom.getElementNumber ()) == 6) { var s = ""; for (var i = 0; i < 4; i++) if ((s = this.addStereoCheck (atomIndex, stereo, i, s)) == null) { stereoFlag = 10; break; } }return (stereoFlag > 6 ? "" : J.smiles.SmilesGenerator.getStereoFlag (atom, stereo, stereoFlag, this.vTemp)); }, $fz.isPrivate = true, $fz), "J.util.JmolNode,~N,~A,~N"); c$.getStereoFlag = $_M(c$, "getStereoFlag", ($fz = function (atom0, atoms, nAtoms, v) { var atom1 = atoms[0]; var atom2 = atoms[1]; var atom3 = atoms[2]; var atom4 = atoms[3]; var atom5 = atoms[4]; var atom6 = atoms[5]; var chiralClass = 4; switch (nAtoms) { default: case 5: case 6: return (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 1, atom1, atom2, atom3, atom4, atom5, atom6, v) ? "@" : "@@"); case 2: case 4: if (atom3 == null || atom4 == null) return ""; var d = J.smiles.SmilesAromatic.getNormalThroughPoints (atom1, atom2, atom3, v.vTemp, v.vA, v.vB); if (Math.abs (J.smiles.SmilesSearch.distanceToPlane (v.vTemp, d, atom4)) < 0.2) { chiralClass = 8; if (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 1, atom1, atom2, atom3, atom4, atom5, atom6, v)) return "@SP1"; if (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 2, atom1, atom2, atom3, atom4, atom5, atom6, v)) return "@SP2"; if (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 3, atom1, atom2, atom3, atom4, atom5, atom6, v)) return "@SP3"; } else { return (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 1, atom1, atom2, atom3, atom4, atom5, atom6, v) ? "@" : "@@"); }} return ""; }, $fz.isPrivate = true, $fz), "J.util.JmolNode,~A,~N,J.smiles.VTemp"); $_M(c$, "addStereoCheck", ($fz = function (atomIndex, stereo, i, s) { var n = stereo[i].getAtomicAndIsotopeNumber (); var nx = stereo[i].getCovalentBondCount (); var nh = (n == 6 ? stereo[i].getCovalentHydrogenCount () : 0); if (n == 6 ? nx != 4 || nh != 3 : nx > 1) return s; var sa = ";" + n + "/" + nh + "/" + nx + ","; if (s.indexOf (sa) >= 0) { if (nh == 3) { var ndt = 0; for (var j = 0; j < nx && ndt < 3; j++) { var ia = stereo[i].getBondedAtomIndex (j); if (ia == atomIndex) continue; ndt += this.atoms[ia].getAtomicAndIsotopeNumber (); } if (ndt > 3) return s; }return null; }return s + sa; }, $fz.isPrivate = true, $fz), "~N,~A,~N,~S"); $_M(c$, "getRingCache", ($fz = function (i0, i1, ht) { var key = J.smiles.SmilesGenerator.getRingKey (i0, i1); var o = ht.get (key); var s = (o == null ? null : o[0]); if (s == null) { ht.put (key, [s = J.smiles.SmilesParser.getRingPointer (++this.nPairs), Integer.$valueOf (i1)]); if (J.util.Logger.debugging) J.util.Logger.debug ("adding for " + i0 + " ring key " + this.nPairs + ": " + key); } else { ht.remove (key); if (J.util.Logger.debugging) J.util.Logger.debug ("using ring key " + key); }return s; }, $fz.isPrivate = true, $fz), "~N,~N,java.util.Map"); $_M(c$, "dumpRingKeys", ($fz = function (sb, ht) { J.util.Logger.info (sb.toString () + "\n\n"); for (var key, $key = ht.keySet ().iterator (); $key.hasNext () && ((key = $key.next ()) || true);) J.util.Logger.info ("unmatched ring key: " + key); }, $fz.isPrivate = true, $fz), "JU.SB,java.util.Map"); c$.getRingKey = $_M(c$, "getRingKey", function (i0, i1) { return Math.min (i0, i1) + "_" + Math.max (i0, i1); }, "~N,~N"); });
define([ // '../../../../src/utils/event', // '../../../../src/utils/objectCreate' ], function( // Event, // objectCreate ){ var objectCreate = hello.utils.objectCreate; var utils = hello.utils; // // Events // describe('utils / event', function(){ var hello, arbitary_data, event_name; beforeEach(function(){ // Pass an arbitary piece of data around arbitary_data = {boom:true}; event_name = 'custom'; hello = { utils : utils }; utils.Event.call(hello); }); it('should bind events by name and be able to trigger them by name', function(){ // Make request var spy = sinon.spy(function( data, type ){ expect( event_name ).to.be( type ); expect( arbitary_data ).to.be( data ); }); hello.on( event_name, spy ); hello.emit( event_name, arbitary_data ); expect( spy.called ).to.be.ok(); }); it('should listen to any event by using a "*"', function(){ // Make request var spy = sinon.spy(function( data, type ){ expect( event_name ).to.be( type ); expect( arbitary_data ).to.be( data ); }); hello.on( '*', spy ); hello.emit( event_name, arbitary_data ); expect( spy.called ).to.be.ok(); }); it('should unbind an event by name and callback', function(){ // Listeners var spy = sinon.spy(function(){ // should not be called. }); var spy2 = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); hello.on( event_name, spy2 ); // Remove hello.off( event_name, spy ); // Trigger hello.emit( event_name ); // Test spies expect( !spy.called ).to.be.ok(); expect( spy2.called ).to.be.ok(); }); it('should unbind all events by name', function(){ // Listeners var spy = sinon.spy(function(){ // should not be called. }); var spy2 = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); hello.on( event_name, spy2 ); // Remove hello.off( event_name ); // Trigger hello.emit( event_name ); // Test spies expect( !spy.called ).to.be.ok(); expect( !spy2.called ).to.be.ok(); }); it('should trigger events on its proto (predecessor in chain)', function(){ // PROTO // Listeners var spy = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); // PROTO var child = objectCreate(hello); var spy2 = sinon.spy(function(){ // should not be called. }); hello.on( event_name, spy2 ); // Trigger hello.emit( event_name ); // Test spies expect( spy.called ).to.be.ok(); expect( spy2.called ).to.be.ok(); }); }); });
import collapsibleFactory from '../common/collapsible'; import collapsibleGroupFactory from '../common/collapsible-group'; const PLUGIN_KEY = 'menu'; /* * Manage the behaviour of a menu * @param {jQuery} $menu */ class Menu { constructor($menu) { this.$menu = $menu; this.$body = $('body'); this.hasMaxMenuDisplayDepth = this.$body.find('.navPages-list').hasClass('navPages-list-depth-max'); // Init collapsible this.collapsibles = collapsibleFactory('[data-collapsible]', { $context: this.$menu }); this.collapsibleGroups = collapsibleGroupFactory($menu); // Auto-bind this.onMenuClick = this.onMenuClick.bind(this); this.onDocumentClick = this.onDocumentClick.bind(this); // Listen this.bindEvents(); } collapseAll() { this.collapsibles.forEach(collapsible => collapsible.close()); this.collapsibleGroups.forEach(group => group.close()); } collapseNeighbors($neighbors) { const $collapsibles = collapsibleFactory('[data-collapsible]', { $context: $neighbors }); $collapsibles.forEach($collapsible => $collapsible.close()); } bindEvents() { this.$menu.on('click', this.onMenuClick); this.$body.on('click', this.onDocumentClick); } unbindEvents() { this.$menu.off('click', this.onMenuClick); this.$body.off('click', this.onDocumentClick); } onMenuClick(event) { event.stopPropagation(); if (this.hasMaxMenuDisplayDepth) { const $neighbors = $(event.target).parent().siblings(); this.collapseNeighbors($neighbors); } } onDocumentClick() { this.collapseAll(); } } /* * Create a new Menu instance * @param {string} [selector] * @return {Menu} */ export default function menuFactory(selector = `[data-${PLUGIN_KEY}]`) { const $menu = $(selector).eq(0); const instanceKey = `${PLUGIN_KEY}Instance`; const cachedMenu = $menu.data(instanceKey); if (cachedMenu instanceof Menu) { return cachedMenu; } const menu = new Menu($menu); $menu.data(instanceKey, menu); return menu; }
'use strict'; var users = require('../../app/controllers/users'), speakers = require('../../app/controllers/speakers'); module.exports = function(app) { // Speakers Routes app.route('/speakers') .get(speakers.list) .post(users.requiresLogin, speakers.create); app.route('/speakers/:speakerId') .get(speakers.read) .put(users.requiresLogin, speakers.hasAuthorization, speakers.update) .delete(users.requiresLogin, speakers.hasAuthorization, speakers.delete); // Finish by binding the Speaker middleware app.param('speakerId', speakers.speakerByID); };
import * as React from 'react'; import ApiPage from 'docs/src/modules/components/ApiPage'; import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations'; import jsonPageContent from './avatar.json'; export default function Page(props) { const { descriptions, pageContent } = props; return <ApiPage descriptions={descriptions} pageContent={pageContent} />; } Page.getInitialProps = () => { const req = require.context('docs/translations/api-docs/avatar', false, /avatar.*.json$/); const descriptions = mapApiPageTranslations(req); return { descriptions, pageContent: jsonPageContent, }; };
var webpack = require('webpack'); var path = require('path'); module.exports = { entry: './src/main.ts', output: { filename: './bundle.js' }, resolve: { root: [ path.join(__dirname, 'src') ], extensions: ['', '.ts', '.js'] }, module: { loaders: [ { test: /\.ts$/, loader: 'ts-loader' } ] } };
(function($) { $.Redactor.prototype.source = function() { return { init: function() { var button = this.button.addFirst('html', 'HTML'); this.button.setIcon(button, '<i class="re-icon-html"></i>'); this.button.addCallback(button, this.source.toggle); var style = { 'width': '100%', 'margin': '0', 'background': '#1d1d1d', 'box-sizing': 'border-box', 'color': '#ccc', 'font-size': '15px', 'outline': 'none', 'padding': '20px', 'line-height': '24px', 'font-family': 'Consolas, Menlo, Monaco, "Courier New", monospace' }; this.source.$textarea = $('<textarea />'); this.source.$textarea.css(style).hide(); if (this.opts.type === 'textarea') { this.core.box().append(this.source.$textarea); } else { this.core.box().after(this.source.$textarea); } this.core.element().on('destroy.callback.redactor', $.proxy(function() { this.source.$textarea.remove(); }, this)); }, toggle: function() { return (this.source.$textarea.hasClass('open')) ? this.source.hide() : this.source.show(); }, setCaretOnShow: function() { this.source.offset = this.offset.get(); var scroll = $(window).scrollTop(); var width = this.core.editor().innerWidth(); var height = this.core.editor().innerHeight(); // caret position sync this.source.start = 0; this.source.end = 0; var $editorDiv = $("<div/>").append($.parseHTML(this.core.editor().html(), document, true)); var $selectionMarkers = $editorDiv.find("span.redactor-selection-marker"); if ($selectionMarkers.length > 0) { var editorHtml = $editorDiv.html().replace(/&amp;/g, '&'); if ($selectionMarkers.length === 1) { this.source.start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML")); this.source.end = this.source.start; } else if ($selectionMarkers.length === 2) { this.source.start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML")); this.source.end = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-2").prop("outerHTML")) - $editorDiv.find("#selection-marker-1").prop("outerHTML").toString().length; } } }, setCaretOnHide: function(html) { this.source.start = this.source.$textarea.get(0).selectionStart; this.source.end = this.source.$textarea.get(0).selectionEnd; // if selection starts from end if (this.source.start > this.source.end && this.source.end > 0) { var tempStart = this.source.end; var tempEnd = this.source.start; this.source.start = tempStart; this.source.end = tempEnd; } this.source.start = this.source.enlargeOffset(html, this.source.start); this.source.end = this.source.enlargeOffset(html, this.source.end); html = html.substr(0, this.source.start) + this.marker.html(1) + html.substr(this.source.start); if (this.source.end > this.source.start) { var markerLength = this.marker.html(1).toString().length; html = html.substr(0, this.source.end + markerLength) + this.marker.html(2) + html.substr(this.source.end + markerLength); } return html; }, hide: function() { this.source.$textarea.removeClass('open').hide(); this.source.$textarea.off('.redactor-source'); var code = this.source.$textarea.val(); code = this.paragraphize.load(code); code = this.source.setCaretOnHide(code); this.code.start(code); this.button.enableAll(); this.core.editor().show().focus(); this.selection.restore(); this.placeholder.enable(); this.core.callback('visual'); }, show: function() { this.selection.save(); this.source.setCaretOnShow(); var height = this.core.editor().height(); var code = this.code.get(); // callback code = this.core.callback('source', code); this.core.editor().hide(); this.button.disableAll('html'); this.source.$textarea.val(code).height(height).addClass('open').show(); this.source.$textarea.on('keyup.redactor-source', $.proxy(function() { if (this.opts.type === 'textarea') { this.core.textarea().val(this.source.$textarea.val()); } }, this)); this.marker.remove(); $(window).scrollTop(scroll); if (this.source.$textarea[0].setSelectionRange) { this.source.$textarea[0].setSelectionRange(this.source.start, this.source.end); } this.source.$textarea[0].scrollTop = 0; setTimeout($.proxy(function() { this.source.$textarea.focus(); }, this), 0); }, enlargeOffset: function(html, offset) { var htmlLength = html.length; var c = 0; if (html[offset] === '>') { c++; } else { for(var i = offset; i <= htmlLength; i++) { c++; if (html[i] === '>') { break; } else if (html[i] === '<' || i === htmlLength) { c = 0; break; } } } return offset + c; } }; }; })(jQuery);
(function () { 'use strict'; angular .module('crowdsource.config', ['angular-loading-bar']) .config(config); config.$inject = ['$httpProvider', '$locationProvider', '$mdThemingProvider', 'cfpLoadingBarProvider']; /** * @name config * @desc Enable HTML5 routing */ function config($httpProvider, $locationProvider, $mdThemingProvider, cfpLoadingBarProvider) { $httpProvider.interceptors.push('AuthHttpResponseInterceptor'); $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); cfpLoadingBarProvider.includeSpinner = false; // Extend palettes var customBlue = $mdThemingProvider.extendPalette('indigo', { "50":"#e8e9f2","100":"#babdd8","200":"#8d91bf", "300":"#666ca9","400":"#404893","500":"#1a237e", "600":"#171f6e","700":"#141a5f","800":"#10164f", "900":"#0d123f","A100":"#babdd8","A200":"#8d91bf", "A400":"#404893","A700":"#141a5f" }); var customYellow = $mdThemingProvider.extendPalette('yellow', { "50": "#fffef3", "100": "#fffbdb", "200": "#fff9c4", "300": "#fff6b0", "400": "#fff49c", "500": "#fff288", "600": "#dfd477", "700": "#bfb666", "800": "#9f9755", "900": "#807944", "A100": "#fffbdb", "A200": "#fff9c4", "A400": "#fff49c", "A700": "#bfb666" }); var customGrey = $mdThemingProvider.extendPalette('grey', { "50":"#ffffff","100":"#ffffff","200":"#ffffff", "300":"#ffffff","400":"#ffffff","500":"#ffffff", "600":"#dfdfdf","700":"#bfbfbf","800":"#9f9f9f", "900":"#808080","A100":"#ffffff","A200":"#ffffff", "A400":"#ffffff","A700":"#bfbfbf" }); // Register the new color palette map with the name <code>neonRed</code> $mdThemingProvider.definePalette('customBlue', customBlue); $mdThemingProvider.definePalette('customYellow', customYellow); $mdThemingProvider.definePalette('customGrey', customGrey); $mdThemingProvider.theme('default') .primaryPalette('customBlue') .accentPalette('customYellow') .warnPalette('red') .backgroundPalette('customGrey'); $mdThemingProvider.theme('alternate') .primaryPalette('indigo') .accentPalette('orange') .warnPalette('red') .backgroundPalette('grey'); $mdThemingProvider.setDefaultTheme('default'); // $mdThemingProvider.alwaysWatchTheme(true); //testing /*OAuthProvider.configure({ baseUrl: 'http://localhost:8000', clientId: 'client_id', clientSecret: 'client_secret', grantPath : '/api/oauth2-ng/token' }); OAuthTokenProvider.configure({ name: 'token', options: { secure: false //TODO this has to be changed to True } });*/ } })();
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If the eval function is called with some argument, then use a first argument es5id: 15.1.2.1_A1.2_T1 description: eval("x = 1", "x = 2"), x equal 1, not 2 ---*/ //CHECK#1 var x; eval("x = 1", "x = 2"); if (x !== 1) { $ERROR('#1: eval("x = 1", "x = 2"); x === 1. Actual: ' + (x)); }
module.exports = [ require('./ngdoc'), require('./name'), require('./area'), require('./module'), require('./id'), require('./restrict'), require('./eventType'), require('./example'), require('./element'), require('./fullName'), require('./priority'), require('./title'), require('./parent'), require('./packageName'), require('./scope') ];
Astro.createValidator({ name: 'array', validate: _.isArray, events: { validationerror: function(e) { var fieldName = e.data.field; e.data.message = 'The "' + fieldName + '" field\'s value has to be an array'; } } });
/* * * * (c) 2010-2020 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from './Globals.js'; /** * @interface Highcharts.PointEventsOptionsObject */ /** * Fires when the point is selected either programmatically or following a click * on the point. One parameter, `event`, is passed to the function. Returning * `false` cancels the operation. * @name Highcharts.PointEventsOptionsObject#select * @type {Highcharts.PointSelectCallbackFunction|undefined} */ /** * Fires when the point is unselected either programmatically or following a * click on the point. One parameter, `event`, is passed to the function. * Returning `false` cancels the operation. * @name Highcharts.PointEventsOptionsObject#unselect * @type {Highcharts.PointUnselectCallbackFunction|undefined} */ /** * Information about the select/unselect event. * * @interface Highcharts.PointInteractionEventObject * @extends global.Event */ /** * @name Highcharts.PointInteractionEventObject#accumulate * @type {boolean} */ /** * Gets fired when the point is selected either programmatically or following a * click on the point. * * @callback Highcharts.PointSelectCallbackFunction * * @param {Highcharts.Point} this * Point where the event occured. * * @param {Highcharts.PointInteractionEventObject} event * Event that occured. */ /** * Fires when the point is unselected either programmatically or following a * click on the point. * * @callback Highcharts.PointUnselectCallbackFunction * * @param {Highcharts.Point} this * Point where the event occured. * * @param {Highcharts.PointInteractionEventObject} event * Event that occured. */ import Legend from './Legend.js'; import Point from './Point.js'; import U from './Utilities.js'; var addEvent = U.addEvent, createElement = U.createElement, css = U.css, defined = U.defined, extend = U.extend, fireEvent = U.fireEvent, isArray = U.isArray, isFunction = U.isFunction, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick; import './Chart.js'; import './Options.js'; import './Series.js'; var Chart = H.Chart, defaultOptions = H.defaultOptions, defaultPlotOptions = H.defaultPlotOptions, hasTouch = H.hasTouch, Series = H.Series, seriesTypes = H.seriesTypes, svg = H.svg, TrackerMixin; /* eslint-disable valid-jsdoc */ /** * TrackerMixin for points and graphs. * * @private * @mixin Highcharts.TrackerMixin */ TrackerMixin = H.TrackerMixin = { /** * Draw the tracker for a point. * * @private * @function Highcharts.TrackerMixin.drawTrackerPoint * @param {Highcharts.Series} this * @fires Highcharts.Series#event:afterDrawTracker */ drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, onMouseOver = function (e) { var point = pointer.getPointFromEvent(e); // undefined on graph in scatterchart if (typeof point !== 'undefined') { pointer.isDirectTouch = true; point.onMouseOver(e); } }, dataLabels; // Add reference to the point series.points.forEach(function (point) { dataLabels = (isArray(point.dataLabels) ? point.dataLabels : (point.dataLabel ? [point.dataLabel] : [])); if (point.graphic) { point.graphic.element.point = point; } dataLabels.forEach(function (dataLabel) { if (dataLabel.div) { dataLabel.div.point = point; } else { dataLabel.element.point = point; } }); }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { series.trackerGroups.forEach(function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass('highcharts-tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }); if (hasTouch) { series[key].on('touchstart', onMouseOver); } if (!chart.styledMode && series.options.cursor) { series[key] .css(css) .css({ cursor: series.options.cursor }); } } }); series._hasTracking = true; } fireEvent(this, 'afterDrawTracker'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. * * @private * @function Highcharts.TrackerMixin.drawTrackerGraph * @param {Highcharts.Series} this * @fires Highcharts.Series#event:afterDrawTracker */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, i, onMouseOver = function (e) { pointer.normalize(e); if (chart.hoverSeries !== series && !pointer.isStickyTooltip(e)) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an * element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (svg ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === 'M') { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], 'L'); } if ((i && trackerPath[i] === 'M') || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, 'L', trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else if (series.graph) { // create series.tracker = renderer.path(trackerPath) .attr({ visibility: series.visible ? 'visible' : 'hidden', zIndex: 2 }) .addClass(trackByArea ? 'highcharts-tracker-area' : 'highcharts-tracker-line') .add(series.group); if (!chart.styledMode) { series.tracker.attr({ 'stroke-linejoin': 'round', stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : 'none', 'stroke-width': series.graph.strokeWidth() + (trackByArea ? 0 : 2 * snap) }); } // The tracker is added to the series group, which is clipped, but // is covered by the marker group. So the marker group also needs to // capture events. [series.tracker, series.markerGroup].forEach(function (tracker) { tracker.addClass('highcharts-tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }); if (options.cursor && !chart.styledMode) { tracker.css({ cursor: options.cursor }); } if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } fireEvent(this, 'afterDrawTracker'); } }; /* End TrackerMixin */ // Add tracking event listener to the series group, so the point graphics // themselves act as trackers if (seriesTypes.column) { /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.column#drawTracker */ seriesTypes.column.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.pie#drawTracker */ seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.scatter#drawTracker */ seriesTypes.scatter.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } // Extend Legend for item events. extend(Legend.prototype, { /** * @private * @function Highcharts.Legend#setItemEvents * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item * @param {Highcharts.SVGElement} legendItem * @param {boolean} [useHTML=false] * @fires Highcharts.Point#event:legendItemClick * @fires Highcharts.Series#event:legendItemClick */ setItemEvents: function (item, legendItem, useHTML) { var legend = this, boxWrapper = legend.chart.renderer.boxWrapper, isPoint = item instanceof Point, activeClass = 'highcharts-legend-' + (isPoint ? 'point' : 'series') + '-active', styledMode = legend.chart.styledMode, // When `useHTML`, the symbol is rendered in other group, so // we need to apply events listeners to both places legendItems = useHTML ? [legendItem, item.legendSymbol] : [item.legendGroup]; // Set the events on the item group, or in case of useHTML, the item // itself (#1249) legendItems.forEach(function (element) { if (element) { element .on('mouseover', function () { if (item.visible) { legend.allItems.forEach(function (inactiveItem) { if (item !== inactiveItem) { inactiveItem.setState('inactive', !isPoint); } }); } item.setState('hover'); // A CSS class to dim or hide other than the hovered // series. // Works only if hovered series is visible (#10071). if (item.visible) { boxWrapper.addClass(activeClass); } if (!styledMode) { legendItem.css(legend.options.itemHoverStyle); } }) .on('mouseout', function () { if (!legend.chart.styledMode) { legendItem.css(merge(item.visible ? legend.itemStyle : legend.itemHiddenStyle)); } legend.allItems.forEach(function (inactiveItem) { if (item !== inactiveItem) { inactiveItem.setState('', !isPoint); } }); // A CSS class to dim or hide other than the hovered // series. boxWrapper.removeClass(activeClass); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { if (item.setVisible) { item.setVisible(); } // Reset inactive state legend.allItems.forEach(function (inactiveItem) { if (item !== inactiveItem) { inactiveItem.setState(item.visible ? 'inactive' : '', !isPoint); } }); }; // A CSS class to dim or hide other than the hovered // series. Event handling in iOS causes the activeClass // to be added prior to click in some cases (#7418). boxWrapper.removeClass(activeClass); // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); } }); }, /** * @private * @function Highcharts.Legend#createCheckboxForItem * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item * @fires Highcharts.Series#event:checkboxClick */ createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', className: 'highcharts-legend-checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item.series || item, 'checkboxClick', { checked: target.checked, item: item }, function () { item.select(); }); }); } }); // Extend the Chart object with interaction extend(Chart.prototype, /** @lends Chart.prototype */ { /** * Display the zoom button, so users can reset zoom to the default view * settings. * * @function Highcharts.Chart#showResetZoom * * @fires Highcharts.Chart#event:afterShowResetZoom * @fires Highcharts.Chart#event:beforeShowResetZoom */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = (btnOptions.relativeTo === 'chart' || btnOptions.relativeTo === 'spaceBox' ? null : 'plotBox'); /** * @private */ function zoomOut() { chart.zoomOut(); } fireEvent(this, 'beforeShowResetZoom', null, function () { chart.resetZoomButton = chart.renderer .button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .addClass('highcharts-reset-zoom') .add() .align(btnOptions.position, false, alignTo); }); fireEvent(this, 'afterShowResetZoom'); }, /** * Zoom the chart out after a user has zoomed in. See also * [Axis.setExtremes](/class-reference/Highcharts.Axis#setExtremes). * * @function Highcharts.Chart#zoomOut * * @fires Highcharts.Chart#event:selection */ zoomOut: function () { fireEvent(this, 'selection', { resetSelection: true }, this.zoom); }, /** * Zoom into a given portion of the chart given by axis coordinates. * * @private * @function Highcharts.Chart#zoom * @param {Highcharts.SelectEventObject} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, mouseDownPos = chart.inverted ? pointer.mouseDownX : pointer.mouseDownY, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { chart.axes.forEach(function (axis) { hasZoomed = axis.zoom(); }); pointer.initiated = false; // #6804 } else { // else, zoom in on all axes event.xAxis.concat(event.yAxis).forEach(function (axisData) { var axis = axisData.axis, axisStartPos = chart.inverted ? axis.left : axis.top, axisEndPos = chart.inverted ? axisStartPos + axis.width : axisStartPos + axis.height, isXAxis = axis.isXAxis, isWithinPane = false; // Check if zoomed area is within the pane (#1289). // In case of multiple panes only one pane should be zoomed. if ((!isXAxis && mouseDownPos >= axisStartPos && mouseDownPos <= axisEndPos) || isXAxis || !defined(mouseDownPos)) { isWithinPane = true; } // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] && isWithinPane) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw(pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100)); } }, /** * Pan the chart by dragging the mouse across the pane. This function is * called on mouse move, and the distance to pan is computed from chartX * compared to the first chartX position in the dragging operation. * * @private * @function Highcharts.Chart#pan * @param {Highcharts.PointerEventObject} e * @param {string} panning */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, panningOptions, chartOptions = chart.options.chart, doRedraw, type; if (typeof panning === 'object') { panningOptions = panning; } else { panningOptions = { enabled: panning, type: 'x' }; } if (chartOptions && chartOptions.panning) { chartOptions.panning = panningOptions; } type = panningOptions.type; fireEvent(this, 'pan', { originalEvent: e }, function () { // remove active points for shared tooltip if (hoverPoints) { hoverPoints.forEach(function (point) { point.setState(); }); } // panning axis mapping var xy = [1]; // x if (type === 'xy') { xy = [1, 0]; } else if (type === 'y') { xy = [0]; } xy.forEach(function (isX) { var axis = chart[isX ? 'xAxis' : 'yAxis'][0], axisOpt = axis.options, horiz = axis.horiz, mousePos = e[horiz ? 'chartX' : 'chartY'], mouseDown = horiz ? 'mouseDownX' : 'mouseDownY', startPos = chart[mouseDown], halfPointRange = (axis.pointRange || 0) / 2, pointRangeDirection = (axis.reversed && !chart.inverted) || (!axis.reversed && chart.inverted) ? -1 : 1, extremes = axis.getExtremes(), panMin = axis.toValue(startPos - mousePos, true) + halfPointRange * pointRangeDirection, panMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange * pointRangeDirection, flipped = panMax < panMin, newMin = flipped ? panMax : panMin, newMax = flipped ? panMin : panMax, paddedMin = Math.min(extremes.dataMin, halfPointRange ? extremes.min : axis.toValue(axis.toPixels(extremes.min) - axis.minPixelPadding)), paddedMax = Math.max(extremes.dataMax, halfPointRange ? extremes.max : axis.toValue(axis.toPixels(extremes.max) + axis.minPixelPadding)), spill; // It is not necessary to calculate extremes on ordinal axis, // because the are already calculated, so we don't want to // override them. if (!axisOpt.ordinal) { // If the new range spills over, either to the min or max, // adjust the new range. if (isX) { spill = paddedMin - newMin; if (spill > 0) { newMax += spill; newMin = paddedMin; } spill = newMax - paddedMax; if (spill > 0) { newMax = paddedMax; newMin -= spill; } } // Set new extremes if they are actually new if (axis.series.length && newMin !== extremes.min && newMax !== extremes.max && isX ? true : (axis.panningState && newMin >= axis.panningState .startMin && newMax <= axis.panningState .startMax // )) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } // set new reference for next run: chart[mouseDown] = mousePos; } }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); }); } }); // Extend the Point object with interaction extend(Point.prototype, /** @lends Highcharts.Point.prototype */ { /** * Toggle the selection status of a point. * * @see Highcharts.Chart#getSelectedPoints * * @sample highcharts/members/point-select/ * Select a point from a button * @sample highcharts/chart/events-selection-points/ * Select a range of points through a drag selection * @sample maps/series/data-id/ * Select a point in Highmaps * * @function Highcharts.Point#select * * @param {boolean} [selected] * When `true`, the point is selected. When `false`, the point is * unselected. When `null` or `undefined`, the selection state is toggled. * * @param {boolean} [accumulate=false] * When `true`, the selection is added to other selected points. * When `false`, other selected points are deselected. Internally in * Highcharts, when * [allowPointSelect](https://api.highcharts.com/highcharts/plotOptions.series.allowPointSelect) * is `true`, selected points are accumulated on Control, Shift or Cmd * clicking the point. * * @fires Highcharts.Point#event:select * @fires Highcharts.Point#event:unselect */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); this.selectedStaging = selected; // fire the event with the default handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { /** * Whether the point is selected or not. * * @see Point#select * @see Chart#getSelectedPoints * * @name Highcharts.Point#selected * @type {boolean} */ point.selected = point.options.selected = selected; series.options.data[series.data.indexOf(point)] = point.options; point.setState(selected && 'select'); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { chart.getSelectedPoints().forEach(function (loopPoint) { var loopSeries = loopPoint.series; if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; loopSeries.options.data[loopSeries.data.indexOf(loopPoint)] = loopPoint.options; // Programatically selecting a point should restore // normal state, but when click happened on other // point, set inactive state to match other points loopPoint.setState(chart.hoverPoints && loopSeries.options.inactiveOtherPoints ? 'inactive' : ''); loopPoint.firePointEvent('unselect'); } }); } }); delete this.selectedStaging; }, /** * Runs on mouse over the point. Called internally from mouse and touch * events. * * @function Highcharts.Point#onMouseOver * * @param {Highcharts.PointerEventObject} [e] * The event arguments. */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, pointer = chart.pointer; e = e ? pointer.normalize(e) : // In cases where onMouseOver is called directly without an event pointer.getChartCoordinatesFromPoint(point, chart.inverted); pointer.runPointActions(e, point); }, /** * Runs on mouse out from the point. Called internally from mouse and touch * events. * * @function Highcharts.Point#onMouseOut * @fires Highcharts.Point#event:mouseOut */ onMouseOut: function () { var point = this, chart = point.series.chart; point.firePointEvent('mouseOut'); if (!point.series.options.inactiveOtherPoints) { (chart.hoverPoints || []).forEach(function (p) { p.setState(); }); } chart.hoverPoints = chart.hoverPoint = null; }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. * * @private * @function Highcharts.Point#importEvents */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events; point.events = events; objectEach(events, function (event, eventType) { if (isFunction(event)) { addEvent(point, eventType, event); } }); this.hasImportedEvents = true; } }, /** * Set the point's state. * * @function Highcharts.Point#setState * * @param {Highcharts.PointStateValue|""} [state] * The new state, can be one of `'hover'`, `'select'`, `'inactive'`, * or `''` (an empty string), `'normal'` or `undefined` to set to * normal state. * @param {boolean} [move] * State for animation. * * @fires Highcharts.Point#event:afterSetState */ setState: function (state, move) { var point = this, series = point.series, previousState = point.state, stateOptions = (series.options.states[state || 'normal'] || {}), markerOptions = (defaultPlotOptions[series.type].marker && series.options.marker), normalDisabled = (markerOptions && markerOptions.enabled === false), markerStateOptions = ((markerOptions && markerOptions.states && markerOptions.states[state || 'normal']) || {}), stateDisabled = markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, halo = series.halo, haloOptions, markerAttribs, pointAttribs, pointAttribsAnimation, hasMarkers = (markerOptions && series.markerAttribs), newSymbol; state = state || ''; // empty string if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== 'select') || // series' state options is disabled (stateOptions.enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } point.state = state; if (hasMarkers) { markerAttribs = series.markerAttribs(point, state); } // Apply hover styles to the existing point if (point.graphic) { if (previousState) { point.graphic.removeClass('highcharts-point-' + previousState); } if (state) { point.graphic.addClass('highcharts-point-' + state); } if (!chart.styledMode) { pointAttribs = series.pointAttribs(point, state); pointAttribsAnimation = pick(chart.options.chart.animation, stateOptions.animation); // Some inactive points (e.g. slices in pie) should apply // oppacity also for it's labels if (series.options.inactiveOtherPoints) { (point.dataLabels || []).forEach(function (label) { if (label) { label.animate({ opacity: pointAttribs.opacity }, pointAttribsAnimation); } }); if (point.connector) { point.connector.animate({ opacity: pointAttribs.opacity }, pointAttribsAnimation); } } point.graphic.animate(pointAttribs, pointAttribsAnimation); } if (markerAttribs) { point.graphic.animate(markerAttribs, pick( // Turn off globally: chart.options.chart.animation, markerStateOptions.animation, markerOptions.animation)); } // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, // create a shared graphic for the hover state if (state && markerStateOptions) { newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw // away the state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (markerAttribs) { if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer .symbol(newSymbol, markerAttribs.x, markerAttribs.y, markerAttribs.width, markerAttribs.height) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ x: markerAttribs.x, y: markerAttribs.y }); } } if (!chart.styledMode && stateMarkerGraphic) { stateMarkerGraphic.attr(series.pointAttribs(point, state)); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && point.isInside ? 'show' : 'hide'](); // #2450 stateMarkerGraphic.element.point = point; // #4310 } } // Show me your halo haloOptions = stateOptions.halo; var markerGraphic = (point.graphic || stateMarkerGraphic); var markerVisibility = (markerGraphic && markerGraphic.visibility || 'inherit'); if (haloOptions && haloOptions.size && markerGraphic && markerVisibility !== 'hidden' && !point.isCluster) { if (!halo) { series.halo = halo = chart.renderer.path() // #5818, #5903, #6705 .add(markerGraphic.parentGroup); } halo.show()[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); halo.attr({ 'class': 'highcharts-halo highcharts-color-' + pick(point.colorIndex, series.colorIndex) + (point.className ? ' ' + point.className : ''), 'visibility': markerVisibility, 'zIndex': -1 // #4929, #8276 }); halo.point = point; // #6055 if (!chart.styledMode) { halo.attr(extend({ 'fill': point.color || series.color, 'fill-opacity': haloOptions.opacity }, haloOptions.attributes)); } } else if (halo && halo.point && halo.point.haloPath) { // Animate back to 0 on the current halo point (#6055) halo.animate({ d: halo.point.haloPath(0) }, null, // Hide after unhovering. The `complete` callback runs in the // halo's context (#7681). halo.hide); } fireEvent(point, 'afterSetState'); }, /** * Get the path definition for the halo, which is usually a shadow-like * circle around the currently hovered point. * * @function Highcharts.Point#haloPath * * @param {number} size * The radius of the circular halo. * * @return {Highcharts.SVGElement} * The path definition. */ haloPath: function (size) { var series = this.series, chart = series.chart; return chart.renderer.symbols.circle(Math.floor(this.plotX) - size, this.plotY - size, size * 2, size * 2); } }); // Extend the Series object with interaction extend(Series.prototype, /** @lends Highcharts.Series.prototype */ { /** * Runs on mouse over the series graphical items. * * @function Highcharts.Series#onMouseOver * @fires Highcharts.Series#event:mouseOver */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState('hover'); /** * Contains the original hovered series. * * @name Highcharts.Chart#hoverSeries * @type {Highcharts.Series|null} */ chart.hoverSeries = series; }, /** * Runs on mouse out of the series graphical items. * * @function Highcharts.Series#onMouseOut * * @fires Highcharts.Series#event:mouseOut */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // #182, set to null before the mouseOut event fires chart.hoverSeries = null; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !series.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // Reset all inactive states chart.series.forEach(function (s) { s.setState('', true); }); }, /** * Set the state of the series. Called internally on mouse interaction * operations, but it can also be called directly to visually * highlight a series. * * @function Highcharts.Series#setState * * @param {Highcharts.SeriesStateValue|""} [state] * The new state, can be either `'hover'`, `'inactive'`, `'select'`, * or `''` (an empty string), `'normal'` or `undefined` to set to * normal state. * @param {boolean} [inherit] * Determines if state should be inherited by points too. */ setState: function (state, inherit) { var series = this, options = series.options, graph = series.graph, inactiveOtherPoints = options.inactiveOtherPoints, stateOptions = options.states, lineWidth = options.lineWidth, opacity = options.opacity, // By default a quick animation to hover/inactive, // slower to un-hover stateAnimation = pick((stateOptions[state || 'normal'] && stateOptions[state || 'normal'].animation), series.chart.options.chart.animation), attribs, i = 0; state = state || ''; if (series.state !== state) { // Toggle class names [ series.group, series.markerGroup, series.dataLabelsGroup ].forEach(function (group) { if (group) { // Old state if (series.state) { group.removeClass('highcharts-series-' + series.state); } // New state if (state) { group.addClass('highcharts-series-' + state); } } }); series.state = state; if (!series.chart.styledMode) { if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = (stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0)); // #4035 opacity = pick(stateOptions[state].opacity, opacity); } if (graph && !graph.dashstyle) { attribs = { 'stroke-width': lineWidth }; // Animate the graph stroke-width. graph.animate(attribs, stateAnimation); while (series['zone-graph-' + i]) { series['zone-graph-' + i].attr(attribs); i = i + 1; } } // For some types (pie, networkgraph, sankey) opacity is // resolved on a point level if (!inactiveOtherPoints) { [ series.group, series.markerGroup, series.dataLabelsGroup, series.labelBySeries ].forEach(function (group) { if (group) { group.animate({ opacity: opacity }, stateAnimation); } }); } } } // Don't loop over points on a series that doesn't apply inactive state // to siblings markers (e.g. line, column) if (inherit && inactiveOtherPoints && series.points) { series.setAllPointsToState(state); } }, /** * Set the state for all points in the series. * * @function Highcharts.Series#setAllPointsToState * * @private * * @param {string} [state] * Can be either `hover` or undefined to set to normal state. */ setAllPointsToState: function (state) { this.points.forEach(function (point) { if (point.setState) { point.setState(state); } }); }, /** * Show or hide the series. * * @function Highcharts.Series#setVisible * * @param {boolean} [visible] * True to show the series, false to hide. If undefined, the visibility is * toggled. * * @param {boolean} [redraw=true] * Whether to redraw the chart after the series is altered. If doing more * operations on the chart, it is a good idea to set redraw to false and * call {@link Chart#redraw|chart.redraw()} after. * * @fires Highcharts.Series#event:hide * @fires Highcharts.Series#event:show */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.options.visible = series.userOptions.visible = typeof vis === 'undefined' ? !oldVisibility : vis; // #5618 showOrHide = vis ? 'show' : 'hide'; // show or hide elements [ 'group', 'dataLabelsGroup', 'markerGroup', 'tracker', 'tt' ].forEach(function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { chart.series.forEach(function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series series.linkedSeries.forEach(function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } fireEvent(series, showOrHide); if (redraw !== false) { chart.redraw(); } }, /** * Show the series if hidden. * * @sample highcharts/members/series-hide/ * Toggle visibility from a button * * @function Highcharts.Series#show * @fires Highcharts.Series#event:show */ show: function () { this.setVisible(true); }, /** * Hide the series if visible. If the * [chart.ignoreHiddenSeries](https://api.highcharts.com/highcharts/chart.ignoreHiddenSeries) * option is true, the chart is redrawn without this series. * * @sample highcharts/members/series-hide/ * Toggle visibility from a button * * @function Highcharts.Series#hide * @fires Highcharts.Series#event:hide */ hide: function () { this.setVisible(false); }, /** * Select or unselect the series. This means its * {@link Highcharts.Series.selected|selected} * property is set, the checkbox in the legend is toggled and when selected, * the series is returned by the {@link Highcharts.Chart#getSelectedSeries} * function. * * @sample highcharts/members/series-select/ * Select a series from a button * * @function Highcharts.Series#select * * @param {boolean} [selected] * True to select the series, false to unselect. If undefined, the selection * state is toggled. * * @fires Highcharts.Series#event:select * @fires Highcharts.Series#event:unselect */ select: function (selected) { var series = this; series.selected = selected = this.options.selected = (typeof selected === 'undefined' ? !series.selected : selected); if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerGraph as Highcharts.Series#drawTracker */ drawTracker: TrackerMixin.drawTrackerGraph });
//When change in default attribute: // Make code revision and check all values working with the default HTML attribute name 'gridindex' and or the variable `attribute` var navigationItem, attribute; var navigationActive = false; var gridindex = "1-2"; var backupGridindex = "1-2"; var lastGridindex_col = {}; var attributes = ["nav-gridindex"] function getElem(col, row) { if (attribute == undefined) { return document.querySelector("[gridindex='" + String(col) + "-" + String(row) + "']"); } else { return document.querySelector("[" + attribute + "='" + String(col) + "-" + String(row) + "']"); } } function getAttribute(elem) { var i; for (i in attributes) { if (elem.getAttribute(attributes[i]) != null) { attribute = attributes[i]; break } else { attribute = undefined; } i += 1; } if (attribute == undefined) { gridindex = String(elem.getAttribute("gridindex")); console.log("%cFocus event: Calling element with id: " + gridindex, "color:orange;"); } else { gridindex = String(elem.getAttribute(attribute)); } } function getIndex(elem) { if (attribute == undefined) { gridindex = String(elem.getAttribute("gridindex")); if (gridindex == "null") { getAttribute(elem); } else { console.log("%cFocus event: Calling element with id: " + gridindex, "color:orange;"); } } else { getAttribute(elem); } } function down() { var elem, col, row; var navelem = false; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); row += 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.parentNode.parentNode.className.indexOf("nav-children") > -1 ) { elem.parentNode.parentNode.style.display = "block"; navigationItem = elem.parentNode.parentNode; navelem = true; } else { if (navigationItem != undefined) { navigationItem.style = ""; } } if (elem.offsetHeight > 0 || navelem) { elem.focus(); gridindex = String(col) + "-" + String(row); navelem = false; break; } else { row += 1; } } else { lastGridindex_col[String(col)] = String(row); col += 1; if (getElem(col, 1) != null) { gridindex = String(col) + "-0"; down(); } break; } } } function up() { var elem, col, row; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); row -= 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.parentNode.parentNode.className.indexOf("nav-children") > -1 ) { elem.parentNode.parentNode.style.display = "block"; navigationItem = elem.parentNode.parentNode; navelem = true; } else { if (navigationItem != undefined) { navigationItem.style = ""; } } if (elem.offsetHeight > 0) { elem.focus(); gridindex = String(col) + "-" + String(row); break; } else { row -= 1; } } else { if (getElem(col-1, 1) != null) { if (lastGridindex_col[String(col-1)] == undefined) { lastGridindex_col[String(col-1)] = "1"; } gridindex = String(col-1) + "-" + lastGridindex_col[String(col-1)]; if (lastGridindex_col[String(col-1)] == 1) { gridindex = String(col-1) + "-" + String(parseInt(lastGridindex_col[String(col-1)])+1); } up(); } break; } } } function left() { var elem, col, row; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); col -= 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.offsetHeight > 0) { elem.focus(); gridindex = String(col) + "-" + String(row); break; } else { col -= 1; } } else { col += 1; break; } } } function right() { var elem, col, row; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); col += 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.offsetHeight > 0) { elem.focus(); gridindex = String(col) + "-" + String(row); break; } else { col += 1; } } else { col -= 1; break; } } } document.body.addEventListener("keydown", function(event) { var key = event.keyCode || event.which; if (event.altKey) { var col, row; if (key == 78) { // key 'n' // activate/deactivate navigation (toggling) if (navigationActive) { // deactivate navigation attribute = undefined; navigationActive = false; gridindex = backupGridindex; row = gridindex.split("-"); col = parseInt(row[0]); row = parseInt(row[1]); getElem(col, row).focus(); } else { // activate navigation attribute = "nav-gridindex"; navigationActive = true; backupGridindex = gridindex; gridindex = "1-1"; row = gridindex.split("-"); col = parseInt(row[0]); row = parseInt(row[1]); getElem(col, row).focus(); } } else if (key == 27) { // escape // escape key attribute = undefined; navigationActive = false; gridindex = backupGridindex; row = gridindex.split("-"); col = parseInt(row[0]); row = parseInt(row[1]); getElem(col, row).focus(); } } else { if (key == 38 || key == 121) { // arrow up, F10 up(); event.preventDefault(); } else if (key == 40 || key == 120) { // arrow down, F9 down(); event.preventDefault(); } else if (key == 37 || key == 122) { // arrow left, F11 left(); event.preventDefault(); } else if (key == 39 || key == 123) { // arrow right, F12 right(); event.preventDefault(); } } }) getElem(1, 2).focus();
// @ts-check const { ESLintUtils } = require('@typescript-eslint/experimental-utils') const RuleTester = ESLintUtils.RuleTester const rule = require('../react-proper-lifecycle-methods') // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2015, sourceType: 'module', }, }) ruleTester.run('react-proper-lifecycle-methods', rule, { valid: [ // component without lifecycle methods passes without errors { filename: 'app/src/component-no-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-no-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public componentWillMount() {} public componentDidMount() {} public componentWillUnmount() {} public componentWillUpdate(nextProps: ICloningRepositoryProps) {} public componentDidUpdate(prevProps: ICloningRepositoryProps) {} public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-with-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillMount() {} public componentDidMount() {} public componentWillUnmount() {} public componentWillUpdate(nextProps: ICloningRepositoryProps, nextState: ICloningRepositoryState) {} public componentDidUpdate(prevProps: ICloningRepositoryProps, prevState: ICloningRepositoryState) {} public render() { return null } } `, }, { filename: 'app/src/pure-component-lifecycle-events-with-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.PureComponent<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillMount() {} public componentDidMount() {} public componentWillUnmount() {} public componentWillUpdate(nextProps: ICloningRepositoryProps, nextState: ICloningRepositoryState) {} public componentDidUpdate(prevProps: ICloningRepositoryProps, prevState: ICloningRepositoryState) {} public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-with-type-literal.tsx', code: ` import * as React from 'react' interface IWindowControlState {} export class WindowControls extends React.Component<{}, IWindowControlState> { public shouldComponentUpdate(nextProps: {}, nextState: IWindowControlState) { return nextState.windowState !== this.state.windowState } public componentWillUpdate(nextProps: {}, nextState: IWindowControlState) { } public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-with-type-literal.tsx', code: ` import * as React from 'react' interface IWindowControlState {} export class WindowControls extends React.Component { public shouldComponentUpdate(nextProps: {}) { return nextState.windowState !== this.state.windowState } public componentWillUpdate(nextProps: {}) { } public render() { return null } } `, }, // a regular class with the same method name is ignored { filename: 'app/src/ui/other.tsx', code: ` class Something { public componentWillUpdate(foo: string) { } } `, }, ], invalid: [ // // shouldComponentUpdate expects the first parameter to be nextProps and match the component's prop type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public shouldComponentUpdate(foo: string) { return true } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedName: 'nextProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryProps', }, }, ], }, // // shouldComponentUpdate expects the second parameter to be nextState and match the component's state type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public shouldComponentUpdate(nextProps: ICloningRepositoryProps, foo: string) { return true } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedName: 'nextState', }, }, { messageId: 'typeMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryState', }, }, ], }, // // shouldComponentUpdate is not permitted to have any additional parameters // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public shouldComponentUpdate(nextProps: ICloningRepositoryProps, nextState: ICloningRepositoryState, additionalParam: void) { return true } public render() { return null } } `, errors: [ { messageId: 'unknownParameter', data: { methodName: 'shouldComponentUpdate', parameterName: 'additionalParam', }, }, ], }, // // componentWillUpdate expects the first parameter to be nextProps and match the component's prop type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public componentWillUpdate(bar: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedName: 'nextProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedType: 'ICloningRepositoryProps', }, }, ], }, // // componentWillUpdate expects the first parameter to be nextProps and match the component's type literal // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface IWindowControlState {} export class CloningRepositoryView extends React.Component<{}, IWindowControlState> { public componentWillUpdate(bar: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedName: 'nextProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedType: '{}', }, }, ], }, // // componentWillUpdate expects the second parameter to be nextState and match the component's state type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillUpdate(nextProps: ICloningRepositoryProps, foo: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'foo', expectedName: 'nextState', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryState', }, }, ], }, // // componentWillUpdate expects the first parameter to be nextProps and match the component's type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface IWindowControlProps {} interface IWindowControlState {} export class CloningRepositoryView extends React.Component<IWindowControlProps, IWindowControlState> { public componentDidUpdate(bar: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'bar', expectedName: 'prevProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'bar', expectedType: 'IWindowControlProps', }, }, ], }, // // componentDidUpdate expects the second parameter to be nextState and match the component's state type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentDidUpdate(prevProps: ICloningRepositoryProps, foo: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'foo', expectedName: 'prevState', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryState', }, }, ], }, // // Methods inside a component following the `component*` or `shouldComponent*` pattern should be rejected // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillDoSomething() { } public shouldComponentFoo() { return false } public render() { return null } } `, errors: [ { messageId: 'reservedMethodName', data: { methodName: 'componentWillDoSomething', }, }, { messageId: 'reservedMethodName', data: { methodName: 'shouldComponentFoo', }, }, ], }, // // Methods inside a non-generic component following the `component*` or `shouldComponent*` pattern should be rejected // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' export class CloningRepositoryView extends React.Component { public componentWillDoSomething() { } public shouldComponentFoo() { return false } public render() { return null } } `, errors: [ { messageId: 'reservedMethodName', data: { methodName: 'componentWillDoSomething', }, }, { messageId: 'reservedMethodName', data: { methodName: 'shouldComponentFoo', }, }, ], }, ], })
angular.module('ui.bootstrap.alert', []) .controller('UibAlertController', ['$scope', '$attrs', '$timeout', function($scope, $attrs, $timeout) { $scope.closeable = !!$attrs.close; if (angular.isDefined($attrs.dismissOnTimeout)) { $timeout(function() { $scope.close(); }, parseInt($attrs.dismissOnTimeout, 10)); } }]) .directive('uibAlert', function() { return { controller: 'UibAlertController', controllerAs: 'alert', templateUrl: function(element, attrs) { return attrs.templateUrl || 'template/alert/alert.html'; }, transclude: true, replace: true, scope: { type: '@', close: '&' } }; }); /* Deprecated alert below */ angular.module('ui.bootstrap.alert') .value('$alertSuppressWarning', false) .controller('AlertController', ['$scope', '$attrs', '$controller', '$log', '$alertSuppressWarning', function($scope, $attrs, $controller, $log, $alertSuppressWarning) { if (!$alertSuppressWarning) { $log.warn('AlertController is now deprecated. Use UibAlertController instead.'); } angular.extend(this, $controller('UibAlertController', { $scope: $scope, $attrs: $attrs })); }]) .directive('alert', ['$log', '$alertSuppressWarning', function($log, $alertSuppressWarning) { return { controller: 'AlertController', controllerAs: 'alert', templateUrl: function(element, attrs) { return attrs.templateUrl || 'template/alert/alert.html'; }, transclude: true, replace: true, scope: { type: '@', close: '&' }, link: function() { if (!$alertSuppressWarning) { $log.warn('alert is now deprecated. Use uib-alert instead.'); } } }; }]);
/* * This file contains generic tests that are run against every rule. Early on, * we found some common rule patterns that would cause errors under certain * conditions. Instead of tracking them down individually, this file runs * the same tests on every defined rule to track down these patterns. * * When run in addition to the other tests, this causes the Rhino CLI test * to fail due to Java stack overflow. This must be run separate from other tests. */ (function() { "use strict"; var Assert = YUITest.Assert, suite = new YUITest.TestSuite("General Tests for all Rules"), rules = CSSLint.getRules(), len = rules.length, i; function testAll(i, rules) { suite.add(new YUITest.TestCase({ name: "General Tests for " + rules[i].id, setUp: function() { this.options = {}; this.options[rules[i].id] = 1; }, "Using @viewport should not result in an error": function() { var result = CSSLint.verify("@viewport { width: auto; }", this.options); Assert.areEqual(0, result.messages.length); }, "Using @keyframes should not result in an error": function() { var result = CSSLint.verify("@keyframes resize { 0% {padding: 0;} 50% {padding: 0;} 100% {padding: 0;}}", this.options); Assert.areEqual(0, result.messages.length); }, "Using @page should not result in an error": function() { var result = CSSLint.verify("@page { width: 100px; }", this.options); Assert.areEqual(0, result.messages.length); }, "Using @page @top-left should not result in an error": function() { var result = CSSLint.verify("@page { @top-left { content: ''; } }", this.options); Assert.areEqual(0, result.messages.length); }, "Using a regular rule should not result in an error": function() { var result = CSSLint.verify("body { margin: 0; }", this.options); Assert.areEqual(0, result.messages.length); } })); } for (i = 0; i < len; i++) { testAll(i, rules); } YUITest.TestRunner.add(suite); })();
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { SyncWaterfallHook } = require("tapable"); const Template = require("../Template"); class JsonpMainTemplatePlugin { apply(mainTemplate) { const needChunkOnDemandLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; const needChunkLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.chunks.length > 1) return true; if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; const needEntryDeferringCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.chunks.length > 1) return true; } return false; }; const needPrefetchingCode = chunk => { const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch; return allPrefetchChunks && Object.keys(allPrefetchChunks).length; }; // TODO webpack 5, no adding to .hooks, use WeakMap and static methods ["jsonpScript", "linkPreload", "linkPrefetch"].forEach(hook => { if (!mainTemplate.hooks[hook]) { mainTemplate.hooks[hook] = new SyncWaterfallHook([ "source", "chunk", "hash" ]); } }); const getScriptSrcPath = (hash, chunk, chunkIdExpression) => { const chunkFilename = mainTemplate.outputOptions.chunkFilename; const chunkMaps = chunk.getChunkMaps(); return mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: `" + ${chunkIdExpression} + "`, hash: `" + ${JSON.stringify( chunkMaps.hash )}[${chunkIdExpression}] + "`, hashWithLength(length) { const shortChunkHashMap = Object.create(null); for (const chunkId of Object.keys(chunkMaps.hash)) { if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( 0, length ); } } return `" + ${JSON.stringify( shortChunkHashMap )}[${chunkIdExpression}] + "`; }, name: `" + (${JSON.stringify( chunkMaps.name )}[${chunkIdExpression}]||${chunkIdExpression}) + "`, contentHash: { javascript: `" + ${JSON.stringify( chunkMaps.contentHash.javascript )}[${chunkIdExpression}] + "` }, contentHashWithLength: { javascript: length => { const shortContentHashMap = {}; const contentHash = chunkMaps.contentHash.javascript; for (const chunkId of Object.keys(contentHash)) { if (typeof contentHash[chunkId] === "string") { shortContentHashMap[chunkId] = contentHash[chunkId].substr( 0, length ); } } return `" + ${JSON.stringify( shortContentHashMap )}[${chunkIdExpression}] + "`; } } }, contentHashType: "javascript" }); }; mainTemplate.hooks.localVars.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const extraCode = []; if (needChunkLoadingCode(chunk)) { extraCode.push( "", "// object to store loaded and loading chunks", "// undefined = chunk not loaded, null = chunk preloaded/prefetched", "// Promise = chunk loading, 0 = chunk loaded", "var installedChunks = {", Template.indent( chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") ), "};", "", needEntryDeferringCode(chunk) ? "var deferredModules = [];" : "" ); } if (needChunkOnDemandLoadingCode(chunk)) { extraCode.push( "", "// script path function", "function jsonpScriptSrc(chunkId) {", Template.indent([ `return ${mainTemplate.requireFn}.p + ${getScriptSrcPath( hash, chunk, "chunkId" )}` ]), "}" ); } if (extraCode.length === 0) return source; return Template.asString([source, ...extraCode]); } ); mainTemplate.hooks.jsonpScript.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout; const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; return Template.asString([ "var script = document.createElement('script');", "var onScriptComplete;", jsonpScriptType ? `script.type = ${JSON.stringify(jsonpScriptType)};` : "", "script.charset = 'utf-8';", `script.timeout = ${chunkLoadTimeout / 1000};`, `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", "script.src = jsonpScriptSrc(chunkId);", crossOriginLoading ? Template.asString([ "if (script.src.indexOf(window.location.origin + '/') !== 0) {", Template.indent( `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` ), "}" ]) : "", "onScriptComplete = function (event) {", Template.indent([ "// avoid mem leaks in IE.", "script.onerror = script.onload = null;", "clearTimeout(timeout);", "var chunk = installedChunks[chunkId];", "if(chunk !== 0) {", Template.indent([ "if(chunk) {", Template.indent([ "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", "var realSrc = event && event.target && event.target.src;", "var error = new Error('Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')');", "error.type = errorType;", "error.request = realSrc;", "chunk[1](error);" ]), "}", "installedChunks[chunkId] = undefined;" ]), "}" ]), "};", "var timeout = setTimeout(function(){", Template.indent([ "onScriptComplete({ type: 'timeout', target: script });" ]), `}, ${chunkLoadTimeout});`, "script.onerror = script.onload = onScriptComplete;" ]); } ); mainTemplate.hooks.linkPreload.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; return Template.asString([ "var link = document.createElement('link');", jsonpScriptType ? `link.type = ${JSON.stringify(jsonpScriptType)};` : "", "link.charset = 'utf-8';", `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", 'link.rel = "preload";', 'link.as = "script";', "link.href = jsonpScriptSrc(chunkId);", crossOriginLoading ? Template.asString([ "if (link.href.indexOf(window.location.origin + '/') !== 0) {", Template.indent( `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` ), "}" ]) : "" ]); } ); mainTemplate.hooks.linkPrefetch.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; return Template.asString([ "var link = document.createElement('link');", crossOriginLoading ? `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` : "", `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", 'link.rel = "prefetch";', 'link.as = "script";', "link.href = jsonpScriptSrc(chunkId);" ]); } ); mainTemplate.hooks.requireEnsure.tap( "JsonpMainTemplatePlugin load", (source, chunk, hash) => { return Template.asString([ source, "", "// JSONP chunk loading for javascript", "", "var installedChunkData = installedChunks[chunkId];", 'if(installedChunkData !== 0) { // 0 means "already installed".', Template.indent([ "", '// a Promise means "currently loading".', "if(installedChunkData) {", Template.indent(["promises.push(installedChunkData[2]);"]), "} else {", Template.indent([ "// setup Promise in chunk cache", "var promise = new Promise(function(resolve, reject) {", Template.indent([ "installedChunkData = installedChunks[chunkId] = [resolve, reject];" ]), "});", "promises.push(installedChunkData[2] = promise);", "", "// start chunk loading", mainTemplate.hooks.jsonpScript.call("", chunk, hash), "document.head.appendChild(script);" ]), "}" ]), "}" ]); } ); mainTemplate.hooks.requireEnsure.tap( { name: "JsonpMainTemplatePlugin preload", stage: 10 }, (source, chunk, hash) => { const chunkMap = chunk.getChildIdsByOrdersMap().preload; if (!chunkMap || Object.keys(chunkMap).length === 0) return source; return Template.asString([ source, "", "// chunk preloadng for javascript", "", `var chunkPreloadMap = ${JSON.stringify(chunkMap, null, "\t")};`, "", "var chunkPreloadData = chunkPreloadMap[chunkId];", "if(chunkPreloadData) {", Template.indent([ "chunkPreloadData.forEach(function(chunkId) {", Template.indent([ "if(installedChunks[chunkId] === undefined) {", Template.indent([ "installedChunks[chunkId] = null;", mainTemplate.hooks.linkPreload.call("", chunk, hash), "document.head.appendChild(link);" ]), "}" ]), "});" ]), "}" ]); } ); mainTemplate.hooks.requireExtensions.tap( "JsonpMainTemplatePlugin", (source, chunk) => { if (!needChunkOnDemandLoadingCode(chunk)) return source; return Template.asString([ source, "", "// on error function for async loading", `${ mainTemplate.requireFn }.oe = function(err) { console.error(err); throw err; };` ]); } ); mainTemplate.hooks.bootstrap.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needChunkLoadingCode(chunk)) { const withDefer = needEntryDeferringCode(chunk); const withPrefetch = needPrefetchingCode(chunk); return Template.asString([ source, "", "// install a JSONP callback for chunk loading", "function webpackJsonpCallback(data) {", Template.indent([ "var chunkIds = data[0];", "var moreModules = data[1];", withDefer ? "var executeModules = data[2];" : "", withPrefetch ? "var prefetchChunks = data[3] || [];" : "", '// add "moreModules" to the modules object,', '// then flag all "chunkIds" as loaded and fire callback', "var moduleId, chunkId, i = 0, resolves = [];", "for(;i < chunkIds.length; i++) {", Template.indent([ "chunkId = chunkIds[i];", "if(installedChunks[chunkId]) {", Template.indent("resolves.push(installedChunks[chunkId][0]);"), "}", "installedChunks[chunkId] = 0;" ]), "}", "for(moduleId in moreModules) {", Template.indent([ "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {", Template.indent( mainTemplate.renderAddModule( hash, chunk, "moduleId", "moreModules[moduleId]" ) ), "}" ]), "}", "if(parentJsonpFunction) parentJsonpFunction(data);", withPrefetch ? Template.asString([ "// chunk prefetching for javascript", "prefetchChunks.forEach(function(chunkId) {", Template.indent([ "if(installedChunks[chunkId] === undefined) {", Template.indent([ "installedChunks[chunkId] = null;", mainTemplate.hooks.linkPrefetch.call("", chunk, hash), "document.head.appendChild(link);" ]), "}" ]), "});" ]) : "", "while(resolves.length) {", Template.indent("resolves.shift()();"), "}", withDefer ? Template.asString([ "", "// add entry modules from loaded chunk to deferred list", "deferredModules.push.apply(deferredModules, executeModules || []);", "", "// run deferred modules when all chunks ready", "return checkDeferredModules();" ]) : "" ]), "};", withDefer ? Template.asString([ "function checkDeferredModules() {", Template.indent([ "var result;", "for(var i = 0; i < deferredModules.length; i++) {", Template.indent([ "var deferredModule = deferredModules[i];", "var fulfilled = true;", "for(var j = 1; j < deferredModule.length; j++) {", Template.indent([ "var depId = deferredModule[j];", "if(installedChunks[depId] !== 0) fulfilled = false;" ]), "}", "if(fulfilled) {", Template.indent([ "deferredModules.splice(i--, 1);", "result = " + mainTemplate.requireFn + "(" + mainTemplate.requireFn + ".s = deferredModule[0]);" ]), "}" ]), "}", "return result;" ]), "}" ]) : "" ]); } return source; } ); mainTemplate.hooks.beforeStartup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needChunkLoadingCode(chunk)) { var jsonpFunction = mainTemplate.outputOptions.jsonpFunction; var globalObject = mainTemplate.outputOptions.globalObject; return Template.asString([ `var jsonpArray = ${globalObject}[${JSON.stringify( jsonpFunction )}] = ${globalObject}[${JSON.stringify(jsonpFunction)}] || [];`, "var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);", "jsonpArray.push = webpackJsonpCallback;", "jsonpArray = jsonpArray.slice();", "for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);", "var parentJsonpFunction = oldJsonpFunction;", "", source ]); } return source; } ); mainTemplate.hooks.beforeStartup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const prefetchChunks = chunk.getChildIdsByOrders().prefetch; if ( needChunkLoadingCode(chunk) && prefetchChunks && prefetchChunks.length ) { return Template.asString([ source, `webpackJsonpCallback([[], {}, 0, ${JSON.stringify( prefetchChunks )}]);` ]); } return source; } ); mainTemplate.hooks.startup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needEntryDeferringCode(chunk)) { if (chunk.hasEntryModule()) { const entries = [chunk.entryModule].filter(Boolean).map(m => [m.id].concat( Array.from(chunk.groupsIterable)[0] .chunks.filter(c => c !== chunk) .map(c => c.id) ) ); return Template.asString([ "// add entry module to deferred list", `deferredModules.push(${entries .map(e => JSON.stringify(e)) .join(", ")});`, "// run deferred modules when ready", "return checkDeferredModules();" ]); } else { return Template.asString([ "// run deferred modules from other chunks", "checkDeferredModules();" ]); } } return source; } ); mainTemplate.hooks.hotBootstrap.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const globalObject = mainTemplate.outputOptions.globalObject; const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename; const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: '" + chunkId + "' } } ); const currentHotUpdateMainFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateMainFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` } ); const runtimeSource = Template.getFunctionContent( require("./JsonpMainTemplate.runtime") ) .replace(/\/\/\$semicolon/g, ";") .replace(/\$require\$/g, mainTemplate.requireFn) .replace( /\$crossOriginLoading\$/g, crossOriginLoading ? JSON.stringify(crossOriginLoading) : "null" ) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) .replace(/\$hash\$/g, JSON.stringify(hash)); return `${source} function hotDisposeChunk(chunkId) { delete installedChunks[chunkId]; } var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( hotUpdateFunction )}]; ${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; } ); mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => { hash.update("jsonp"); hash.update("6"); }); } } module.exports = JsonpMainTemplatePlugin;
// from https://gist.github.com/mathewbyrne/1280286 slugify = function(text){ return text.toString().toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text } var render = function(data) { var data = data.data; var out = '* [' + data.title + '](https://github.com/git-tips/tips#' + slugify(data.title) + ')\n'; return out; }; module.exports = render;
define(function() { "use strict"; function RangeFilter(columnKey, isMinEnabled, minValue, isMaxEnabled, maxValue) { InputValidator.validateNotNull("columnKey", columnKey); InputValidator.validateNotNull("isMinEnabled", isMinEnabled); InputValidator.validateNotNull("minValue", minValue); InputValidator.validateNotNull("isMaxEnabled", isMaxEnabled); InputValidator.validateNotNull("maxValue", maxValue); this.columnKey = function() { return columnKey; }; this.isMinEnabled = function() { return isMinEnabled; }; this.minValue = function() { return minValue; }; this.isMaxEnabled = function() { return isMaxEnabled; }; this.maxValue = function() { return maxValue; }; this.passes = function(data) { InputValidator.validateNotNull("data", data); var value = data[columnKey]; return (!isMinEnabled || minValue <= value) && (!isMaxEnabled || value <= maxValue); }; this.toObject = function() { return ( { type: "RangeFilter", columnKey: columnKey, isMinEnabled: isMinEnabled, minValue: minValue, isMaxEnabled: isMaxEnabled, maxValue: maxValue, }); }; this.toString = function() { return "RangeFilter (" + isMinEnabled + " " + minValue + "\u2264" + columnKey + "\u2264" + isMaxEnabled + " " + maxValue + ")"; }; } RangeFilter.fromObject = function(object) { InputValidator.validateNotNull("object", object); var columnKey = object.columnKey; var isMinEnabled = object.isMinEnabled; var minValue = object.minValue; var isMaxEnabled = object.isMaxEnabled; var maxValue = object.maxValue; return new RangeFilter(columnKey, isMinEnabled, minValue, isMaxEnabled, maxValue); }; return RangeFilter; });
const debug = require('ghost-ignition').debug('api:canary:utils:serializers:input:authors'); const slugFilterOrder = require('./utils/slug-filter-order'); const utils = require('../../index'); function setDefaultOrder(frame) { if (!frame.options.order && frame.options.filter) { frame.options.autoOrder = slugFilterOrder('users', frame.options.filter); } if (!frame.options.order && !frame.options.autoOrder) { frame.options.order = 'name asc'; } } module.exports = { browse(apiConfig, frame) { debug('browse'); if (utils.isContentAPI(frame)) { setDefaultOrder(frame); } }, read(apiConfig, frame) { debug('read'); if (utils.isContentAPI(frame)) { setDefaultOrder(frame); } } };
(function() { 'use strict'; /* * This feature allows you to specify a grid over a portion or the entire chart area. * * @name grid */ d4.feature('grid', function(name) { var xAxis = d3.svg.axis(); var yAxis = d3.svg.axis(); return { accessors: { formatXAxis: function(xAxis) { return xAxis.orient('bottom'); }, formatYAxis: function(yAxis) { return yAxis.orient('left'); } }, proxies: [{ target: xAxis, prefix: 'x' }, { target: yAxis, prefix: 'y' }], render: function(scope, data, selection) { xAxis.scale(this.x); yAxis.scale(this.y); var formattedXAxis = d4.functor(scope.accessors.formatXAxis).bind(this)(xAxis); var formattedYAxis = d4.functor(scope.accessors.formatYAxis).bind(this)(yAxis); var grid = d4.appendOnce(selection, 'g.grid.border.' + name); var gridBg = d4.appendOnce(grid, 'rect'); var gridX = d4.appendOnce(grid, 'g.x.grid.' + name); var gridY = d4.appendOnce(grid, 'g.y.grid.' + name); gridBg .attr('transform', 'translate(0,0)') .attr('x', 0) .attr('y', 0) .attr('width', this.width) .attr('height', this.height); gridX .attr('transform', 'translate(0,' + this.height + ')') .call(formattedXAxis .tickSize(-this.height, 0, 0) .tickFormat('')); gridY .attr('transform', 'translate(0,0)') .call(formattedYAxis .tickSize(-this.width, 0, 0) .tickFormat('')); return grid; } }; }); }).call(this);
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); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; import { NgModule, Component, ContentChildren, Directive, ElementRef, Renderer, EventEmitter, HostBinding, Input, Optional, Output, QueryList, ViewChild, ViewEncapsulation, forwardRef } from '@angular/core'; import { NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import { MdUniqueSelectionDispatcher, coerceBooleanProperty, DefaultStyleCompatibilityModeModule } from '../core'; /** * Provider Expression that allows md-button-toggle-group to register as a ControlValueAccessor. * This allows it to support [(ngModel)]. */ export var MD_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(function () { return MdButtonToggleGroup; }), multi: true }; var _uniqueIdCounter = 0; /** A simple change event emitted by either MdButtonToggle or MdButtonToggleGroup. */ export var MdButtonToggleChange = (function () { function MdButtonToggleChange() { } return MdButtonToggleChange; }()); /** Exclusive selection button toggle group that behaves like a radio-button group. */ export var MdButtonToggleGroup = (function () { function MdButtonToggleGroup() { /** The value for the button toggle group. Should match currently selected button toggle. */ this._value = null; /** The HTML name attribute applied to toggles in this group. */ this._name = "md-radio-group-" + _uniqueIdCounter++; /** Disables all toggles in the group. */ this._disabled = null; /** Whether the button toggle group should be vertical. */ this._vertical = false; /** The currently selected button toggle, should match the value. */ this._selected = null; /** Whether the button toggle group is initialized or not. */ this._isInitialized = false; /** * The method to be called in order to update ngModel. * Now `ngModel` binding is not supported in multiple selection mode. */ this._controlValueAccessorChangeFn = function (value) { }; /** onTouch function registered via registerOnTouch (ControlValueAccessor). */ this.onTouched = function () { }; /** Event emitted when the group's value changes. */ this._change = new EventEmitter(); /** Child button toggle buttons. */ this._buttonToggles = null; } Object.defineProperty(MdButtonToggleGroup.prototype, "change", { get: function () { return this._change.asObservable(); }, enumerable: true, configurable: true }); /** TODO: internal */ MdButtonToggleGroup.prototype.ngAfterViewInit = function () { this._isInitialized = true; }; Object.defineProperty(MdButtonToggleGroup.prototype, "name", { get: function () { return this._name; }, set: function (value) { this._name = value; this._updateButtonToggleNames(); }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "disabled", { get: function () { return this._disabled; }, set: function (value) { this._disabled = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "vertical", { get: function () { return this._vertical; }, set: function (value) { this._vertical = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "value", { get: function () { return this._value; }, set: function (newValue) { if (this._value != newValue) { this._value = newValue; this._updateSelectedButtonToggleFromValue(); // Only emit a change event if the view is completely initialized. // We don't want to emit a change event for the initial values. if (this._isInitialized) { this._emitChangeEvent(); } } }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "selected", { get: function () { return this._selected; }, set: function (selected) { this._selected = selected; this.value = selected ? selected.value : null; if (selected && !selected.checked) { selected.checked = true; } }, enumerable: true, configurable: true }); MdButtonToggleGroup.prototype._updateButtonToggleNames = function () { var _this = this; if (this._buttonToggles) { this._buttonToggles.forEach(function (toggle) { toggle.name = _this._name; }); } }; // TODO: Refactor into shared code with radio. MdButtonToggleGroup.prototype._updateSelectedButtonToggleFromValue = function () { var _this = this; var isAlreadySelected = this._selected != null && this._selected.value == this._value; if (this._buttonToggles != null && !isAlreadySelected) { var matchingButtonToggle = this._buttonToggles.filter(function (buttonToggle) { return buttonToggle.value == _this._value; })[0]; if (matchingButtonToggle) { this.selected = matchingButtonToggle; } else if (this.value == null) { this.selected = null; this._buttonToggles.forEach(function (buttonToggle) { buttonToggle.checked = false; }); } } }; /** Dispatch change event with current selection and group value. */ MdButtonToggleGroup.prototype._emitChangeEvent = function () { var event = new MdButtonToggleChange(); event.source = this._selected; event.value = this._value; this._controlValueAccessorChangeFn(event.value); this._change.emit(event); }; /** * Implemented as part of ControlValueAccessor. * TODO: internal */ MdButtonToggleGroup.prototype.writeValue = function (value) { this.value = value; }; /** * Implemented as part of ControlValueAccessor. * TODO: internal */ MdButtonToggleGroup.prototype.registerOnChange = function (fn) { this._controlValueAccessorChangeFn = fn; }; /** * Implemented as part of ControlValueAccessor. * TODO: internal */ MdButtonToggleGroup.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; __decorate([ Output(), __metadata('design:type', Observable) ], MdButtonToggleGroup.prototype, "change", null); __decorate([ ContentChildren(forwardRef(function () { return MdButtonToggle; })), __metadata('design:type', QueryList) ], MdButtonToggleGroup.prototype, "_buttonToggles", void 0); __decorate([ Input(), __metadata('design:type', String) ], MdButtonToggleGroup.prototype, "name", null); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroup.prototype, "disabled", null); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroup.prototype, "vertical", null); __decorate([ Input(), __metadata('design:type', Object) ], MdButtonToggleGroup.prototype, "value", null); __decorate([ Input(), __metadata('design:type', Object) ], MdButtonToggleGroup.prototype, "selected", null); MdButtonToggleGroup = __decorate([ Directive({ selector: 'md-button-toggle-group:not([multiple])', providers: [MD_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR], host: { 'role': 'radiogroup', '[class.md-button-toggle-vertical]': 'vertical' }, exportAs: 'mdButtonToggleGroup', }), __metadata('design:paramtypes', []) ], MdButtonToggleGroup); return MdButtonToggleGroup; }()); /** Multiple selection button-toggle group. `ngModel` is not supported in this mode. */ export var MdButtonToggleGroupMultiple = (function () { function MdButtonToggleGroupMultiple() { /** Disables all toggles in the group. */ this._disabled = null; /** Whether the button toggle group should be vertical. */ this._vertical = false; } Object.defineProperty(MdButtonToggleGroupMultiple.prototype, "disabled", { get: function () { return this._disabled; }, set: function (value) { this._disabled = (value != null && value !== false) ? true : null; }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroupMultiple.prototype, "vertical", { get: function () { return this._vertical; }, set: function (value) { this._vertical = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroupMultiple.prototype, "disabled", null); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroupMultiple.prototype, "vertical", null); MdButtonToggleGroupMultiple = __decorate([ Directive({ selector: 'md-button-toggle-group[multiple]', exportAs: 'mdButtonToggleGroup', host: { '[class.md-button-toggle-vertical]': 'vertical' } }), __metadata('design:paramtypes', []) ], MdButtonToggleGroupMultiple); return MdButtonToggleGroupMultiple; }()); export var MdButtonToggle = (function () { function MdButtonToggle(toggleGroup, toggleGroupMultiple, buttonToggleDispatcher, _renderer) { var _this = this; this.buttonToggleDispatcher = buttonToggleDispatcher; this._renderer = _renderer; /** Whether or not this button toggle is checked. */ this._checked = false; /** Whether or not this button toggle is disabled. */ this._disabled = null; /** Value assigned to this button toggle. */ this._value = null; /** Whether or not the button toggle is a single selection. */ this._isSingleSelector = null; /** Event emitted when the group value changes. */ this._change = new EventEmitter(); this.buttonToggleGroup = toggleGroup; this.buttonToggleGroupMultiple = toggleGroupMultiple; if (this.buttonToggleGroup) { buttonToggleDispatcher.listen(function (id, name) { if (id != _this.id && name == _this.name) { _this.checked = false; } }); this._type = 'radio'; this.name = this.buttonToggleGroup.name; this._isSingleSelector = true; } else { // Even if there is no group at all, treat the button toggle as a checkbox so it can be // toggled on or off. this._type = 'checkbox'; this._isSingleSelector = false; } } Object.defineProperty(MdButtonToggle.prototype, "change", { get: function () { return this._change.asObservable(); }, enumerable: true, configurable: true }); MdButtonToggle.prototype.ngOnInit = function () { if (this.id == null) { this.id = "md-button-toggle-" + _uniqueIdCounter++; } if (this.buttonToggleGroup && this._value == this.buttonToggleGroup.value) { this._checked = true; } }; Object.defineProperty(MdButtonToggle.prototype, "inputId", { get: function () { return this.id + "-input"; }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggle.prototype, "checked", { get: function () { return this._checked; }, set: function (newCheckedState) { if (this._isSingleSelector) { if (newCheckedState) { // Notify all button toggles with the same name (in the same group) to un-check. this.buttonToggleDispatcher.notify(this.id, this.name); } } this._checked = newCheckedState; if (newCheckedState && this._isSingleSelector && this.buttonToggleGroup.value != this.value) { this.buttonToggleGroup.selected = this; } }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggle.prototype, "value", { /** MdButtonToggleGroup reads this to assign its own value. */ get: function () { return this._value; }, set: function (value) { if (this._value != value) { if (this.buttonToggleGroup != null && this.checked) { this.buttonToggleGroup.value = value; } this._value = value; } }, enumerable: true, configurable: true }); /** Dispatch change event with current value. */ MdButtonToggle.prototype._emitChangeEvent = function () { var event = new MdButtonToggleChange(); event.source = this; event.value = this._value; this._change.emit(event); }; Object.defineProperty(MdButtonToggle.prototype, "disabled", { get: function () { return this._disabled || (this.buttonToggleGroup != null && this.buttonToggleGroup.disabled) || (this.buttonToggleGroupMultiple != null && this.buttonToggleGroupMultiple.disabled); }, set: function (value) { this._disabled = (value != null && value !== false) ? true : null; }, enumerable: true, configurable: true }); /** Toggle the state of the current button toggle. */ MdButtonToggle.prototype._toggle = function () { this.checked = !this.checked; }; /** Checks the button toggle due to an interaction with the underlying native input. */ MdButtonToggle.prototype._onInputChange = function (event) { event.stopPropagation(); if (this._isSingleSelector) { // Propagate the change one-way via the group, which will in turn mark this // button toggle as checked. this.checked = true; this.buttonToggleGroup.selected = this; this.buttonToggleGroup.onTouched(); } else { this._toggle(); } // Emit a change event when the native input does. this._emitChangeEvent(); }; /** TODO: internal */ MdButtonToggle.prototype._onInputClick = function (event) { // We have to stop propagation for click events on the visual hidden input element. // By default, when a user clicks on a label element, a generated click event will be // dispatched on the associated input element. Since we are using a label element as our // root container, the click event on the `slide-toggle` will be executed twice. // The real click event will bubble up, and the generated click event also tries to bubble up. // This will lead to multiple click events. // Preventing bubbling for the second event will solve that issue. event.stopPropagation(); }; MdButtonToggle.prototype.focus = function () { this._renderer.invokeElementMethod(this._inputElement.nativeElement, 'focus'); }; __decorate([ HostBinding(), Input(), __metadata('design:type', String) ], MdButtonToggle.prototype, "id", void 0); __decorate([ Input(), __metadata('design:type', String) ], MdButtonToggle.prototype, "name", void 0); __decorate([ Output(), __metadata('design:type', Observable) ], MdButtonToggle.prototype, "change", null); __decorate([ ViewChild('input'), __metadata('design:type', ElementRef) ], MdButtonToggle.prototype, "_inputElement", void 0); __decorate([ HostBinding('class.md-button-toggle-checked'), Input(), __metadata('design:type', Boolean) ], MdButtonToggle.prototype, "checked", null); __decorate([ Input(), __metadata('design:type', Object) ], MdButtonToggle.prototype, "value", null); __decorate([ HostBinding('class.md-button-toggle-disabled'), Input(), __metadata('design:type', Boolean) ], MdButtonToggle.prototype, "disabled", null); MdButtonToggle = __decorate([ Component({selector: 'md-button-toggle', template: "<label [attr.for]=\"inputId\" class=\"md-button-toggle-label\"> <input #input class=\"md-button-toggle-input md-visually-hidden\" [type]=\"_type\" [id]=\"inputId\" [checked]=\"checked\" [disabled]=\"disabled\" [name]=\"name\" (change)=\"_onInputChange($event)\" (click)=\"_onInputClick($event)\"> <div class=\"md-button-toggle-label-content\"> <ng-content></ng-content> </div> </label> ", styles: ["md-button-toggle-group { box-shadow: 0px 3px 1px -2px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12); position: relative; display: inline-flex; flex-direction: row; border-radius: 2px; cursor: pointer; white-space: nowrap; } .md-button-toggle-vertical { flex-direction: column; } .md-button-toggle-vertical .md-button-toggle-label-content { display: block; } .md-button-toggle-disabled .md-button-toggle-label-content { cursor: default; } md-button-toggle { white-space: nowrap; } .md-button-toggle-label-content { display: inline-block; line-height: 36px; padding: 0 16px; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .md-button-toggle-label-content > * { vertical-align: middle; } /*# sourceMappingURL=button-toggle.css.map */ "], encapsulation: ViewEncapsulation.None, }), __param(0, Optional()), __param(1, Optional()), __metadata('design:paramtypes', [MdButtonToggleGroup, MdButtonToggleGroupMultiple, MdUniqueSelectionDispatcher, Renderer]) ], MdButtonToggle); return MdButtonToggle; }()); export var MdButtonToggleModule = (function () { function MdButtonToggleModule() { } MdButtonToggleModule.forRoot = function () { return { ngModule: MdButtonToggleModule, providers: [MdUniqueSelectionDispatcher] }; }; MdButtonToggleModule = __decorate([ NgModule({ imports: [FormsModule, DefaultStyleCompatibilityModeModule], exports: [ MdButtonToggleGroup, MdButtonToggleGroupMultiple, MdButtonToggle, DefaultStyleCompatibilityModeModule, ], declarations: [MdButtonToggleGroup, MdButtonToggleGroupMultiple, MdButtonToggle], }), __metadata('design:paramtypes', []) ], MdButtonToggleModule); return MdButtonToggleModule; }()); //# sourceMappingURL=button-toggle.js.map
var searchData= [ ['get_5fmodel_5fhandle',['GET_MODEL_HANDLE',['../serializer_8h.html#a887590f4b40f78bf359c8e56f03c56fe',1,'serializer.h']]] ];
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ContentLowPriority = function ContentLowPriority(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 18H9v2l3-3-3-3v2h-.5C6.02 16 4 13.98 4 11.5S6.02 7 8.5 7H12V5H8.5C4.92 5 2 7.92 2 11.5z' }) ); }; ContentLowPriority = (0, _pure2.default)(ContentLowPriority); ContentLowPriority.displayName = 'ContentLowPriority'; exports.default = ContentLowPriority;
import { Mesh, OrthographicCamera, PerspectiveCamera, PlaneGeometry, Scene, ShaderMaterial, UniformsUtils, WebGLRenderTarget } from 'three'; import { BokehShader } from '../shaders/BokehShader2.js'; import { BokehDepthShader } from '../shaders/BokehShader2.js'; class CinematicCamera extends PerspectiveCamera { constructor( fov, aspect, near, far ) { super( fov, aspect, near, far ); this.type = 'CinematicCamera'; this.postprocessing = { enabled: true }; this.shaderSettings = { rings: 3, samples: 4 }; const depthShader = BokehDepthShader; this.materialDepth = new ShaderMaterial( { uniforms: depthShader.uniforms, vertexShader: depthShader.vertexShader, fragmentShader: depthShader.fragmentShader } ); this.materialDepth.uniforms[ 'mNear' ].value = near; this.materialDepth.uniforms[ 'mFar' ].value = far; // In case of cinematicCamera, having a default lens set is important this.setLens(); this.initPostProcessing(); } // providing fnumber and coc(Circle of Confusion) as extra arguments // In case of cinematicCamera, having a default lens set is important // if fnumber and coc are not provided, cinematicCamera tries to act as a basic PerspectiveCamera setLens( focalLength = 35, filmGauge = 35, fNumber = 8, coc = 0.019 ) { this.filmGauge = filmGauge; this.setFocalLength( focalLength ); this.fNumber = fNumber; this.coc = coc; // fNumber is focalLength by aperture this.aperture = focalLength / this.fNumber; // hyperFocal is required to calculate depthOfField when a lens tries to focus at a distance with given fNumber and focalLength this.hyperFocal = ( focalLength * focalLength ) / ( this.aperture * this.coc ); } linearize( depth ) { const zfar = this.far; const znear = this.near; return - zfar * znear / ( depth * ( zfar - znear ) - zfar ); } smoothstep( near, far, depth ) { const x = this.saturate( ( depth - near ) / ( far - near ) ); return x * x * ( 3 - 2 * x ); } saturate( x ) { return Math.max( 0, Math.min( 1, x ) ); } // function for focusing at a distance from the camera focusAt( focusDistance = 20 ) { const focalLength = this.getFocalLength(); // distance from the camera (normal to frustrum) to focus on this.focus = focusDistance; // the nearest point from the camera which is in focus (unused) this.nearPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal + ( this.focus - focalLength ) ); // the farthest point from the camera which is in focus (unused) this.farPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal - ( this.focus - focalLength ) ); // the gap or width of the space in which is everything is in focus (unused) this.depthOfField = this.farPoint - this.nearPoint; // Considering minimum distance of focus for a standard lens (unused) if ( this.depthOfField < 0 ) this.depthOfField = 0; this.sdistance = this.smoothstep( this.near, this.far, this.focus ); this.ldistance = this.linearize( 1 - this.sdistance ); this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = this.ldistance; } initPostProcessing() { if ( this.postprocessing.enabled ) { this.postprocessing.scene = new Scene(); this.postprocessing.camera = new OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 ); this.postprocessing.scene.add( this.postprocessing.camera ); this.postprocessing.rtTextureDepth = new WebGLRenderTarget( window.innerWidth, window.innerHeight ); this.postprocessing.rtTextureColor = new WebGLRenderTarget( window.innerWidth, window.innerHeight ); const bokeh_shader = BokehShader; this.postprocessing.bokeh_uniforms = UniformsUtils.clone( bokeh_shader.uniforms ); this.postprocessing.bokeh_uniforms[ 'tColor' ].value = this.postprocessing.rtTextureColor.texture; this.postprocessing.bokeh_uniforms[ 'tDepth' ].value = this.postprocessing.rtTextureDepth.texture; this.postprocessing.bokeh_uniforms[ 'manualdof' ].value = 0; this.postprocessing.bokeh_uniforms[ 'shaderFocus' ].value = 0; this.postprocessing.bokeh_uniforms[ 'fstop' ].value = 2.8; this.postprocessing.bokeh_uniforms[ 'showFocus' ].value = 1; this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = 0.1; //console.log( this.postprocessing.bokeh_uniforms[ "focalDepth" ].value ); this.postprocessing.bokeh_uniforms[ 'znear' ].value = this.near; this.postprocessing.bokeh_uniforms[ 'zfar' ].value = this.near; this.postprocessing.bokeh_uniforms[ 'textureWidth' ].value = window.innerWidth; this.postprocessing.bokeh_uniforms[ 'textureHeight' ].value = window.innerHeight; this.postprocessing.materialBokeh = new ShaderMaterial( { uniforms: this.postprocessing.bokeh_uniforms, vertexShader: bokeh_shader.vertexShader, fragmentShader: bokeh_shader.fragmentShader, defines: { RINGS: this.shaderSettings.rings, SAMPLES: this.shaderSettings.samples, DEPTH_PACKING: 1 } } ); this.postprocessing.quad = new Mesh( new PlaneGeometry( window.innerWidth, window.innerHeight ), this.postprocessing.materialBokeh ); this.postprocessing.quad.position.z = - 500; this.postprocessing.scene.add( this.postprocessing.quad ); } } renderCinematic( scene, renderer ) { if ( this.postprocessing.enabled ) { const currentRenderTarget = renderer.getRenderTarget(); renderer.clear(); // Render scene into texture scene.overrideMaterial = null; renderer.setRenderTarget( this.postprocessing.rtTextureColor ); renderer.clear(); renderer.render( scene, this ); // Render depth into texture scene.overrideMaterial = this.materialDepth; renderer.setRenderTarget( this.postprocessing.rtTextureDepth ); renderer.clear(); renderer.render( scene, this ); // Render bokeh composite renderer.setRenderTarget( null ); renderer.render( this.postprocessing.scene, this.postprocessing.camera ); renderer.setRenderTarget( currentRenderTarget ); } } } export { CinematicCamera };
import Social from './Social' export default Social
/* Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colorbutton', 'ja', { auto: '自動', bgColorTitle: '背景色', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Gray', '008080': 'Teal', '000080': 'Navy', '4B0082': 'Indigo', '696969': 'Dark Gray', B22222: 'Fire Brick', A52A2A: 'Brown', DAA520: 'Golden Rod', '006400': 'Dark Green', '40E0D0': 'Turquoise', '0000CD': 'Medium Blue', '800080': 'Purple', '808080': 'Gray', F00: 'Red', FF8C00: 'Dark Orange', FFD700: 'Gold', '008000': 'Green', '0FF': 'Cyan', '00F': 'Blue', EE82EE: 'Violet', A9A9A9: 'Dim Gray', FFA07A: 'Light Salmon', FFA500: 'Orange', FFFF00: 'Yellow', '00FF00': 'Lime', AFEEEE: 'Pale Turquoise', ADD8E6: 'Light Blue', DDA0DD: 'Plum', D3D3D3: 'Light Grey', FFF0F5: 'Lavender Blush', FAEBD7: 'Antique White', FFFFE0: 'Light Yellow', F0FFF0: 'Honeydew', F0FFFF: 'Azure', F0F8FF: 'Alice Blue', E6E6FA: 'Lavender', FFF: 'White', '1ABC9C': 'Strong Cyan', '2ECC71': 'Emerald', '3498DB': 'Bright Blue', '9B59B6': 'Amethyst', '4E5F70': 'Grayish Blue', 'F1C40F': 'Vivid Yellow', '16A085': 'Dark Cyan', '27AE60': 'Dark Emerald', '2980B9': 'Strong Blue', '8E44AD': 'Dark Violet', '2C3E50': 'Desaturated Blue', 'F39C12': 'Orange', 'E67E22': 'Carrot', 'E74C3C': 'Pale Red', 'ECF0F1': 'Bright Silver', '95A5A6': 'Light Grayish Cyan', 'DDD': 'Light Gray', 'D35400': 'Pumpkin', 'C0392B': 'Strong Red', 'BDC3C7': 'Silver', '7F8C8D': 'Grayish Cyan', '999': 'Dark Gray' }, more: 'その他の色...', panelTitle: '色', textColorTitle: '文字色' } );
var parent = require('../../actual/array-buffer'); module.exports = parent;
/*! * gumshoe v4.0.1 * A simple, framework-agnostic scrollspy script. * (c) 2019 Chris Ferdinandi * MIT License * http://github.com/cferdinandi/gumshoe */ (function (root, factory) { if ( typeof define === 'function' && define.amd ) { define([], (function () { return factory(root); })); } else if ( typeof exports === 'object' ) { module.exports = factory(root); } else { root.Gumshoe = factory(root); } })(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) { 'use strict'; // // Defaults // var defaults = { // Active classes navClass: 'active', contentClass: 'active', // Nested navigation nested: false, nestedClass: 'active', // Offset & reflow offset: 0, reflow: false, // Event support events: true }; // // Methods // /** * Merge two or more objects together. * @param {Object} objects The objects to merge together * @returns {Object} Merged values of defaults and options */ var extend = function () { var merged = {}; Array.prototype.forEach.call(arguments, (function (obj) { for (var key in obj) { if (!obj.hasOwnProperty(key)) return; merged[key] = obj[key]; } })); return merged; }; /** * Emit a custom event * @param {String} type The event type * @param {Node} elem The element to attach the event to * @param {Object} detail Any details to pass along with the event */ var emitEvent = function (type, elem, detail) { // Make sure events are enabled if (!detail.settings.events) return; // Create a new event var event = new CustomEvent(type, { bubbles: true, cancelable: true, detail: detail }); // Dispatch the event elem.dispatchEvent(event); }; /** * Get an element's distance from the top of the Document. * @param {Node} elem The element * @return {Number} Distance from the top in pixels */ var getOffsetTop = function (elem) { var location = 0; if (elem.offsetParent) { while (elem) { location += elem.offsetTop; elem = elem.offsetParent; } } return location >= 0 ? location : 0; }; /** * Sort content from first to last in the DOM * @param {Array} contents The content areas */ var sortContents = function (contents) { contents.sort((function (item1, item2) { var offset1 = getOffsetTop(item1.content); var offset2 = getOffsetTop(item2.content); if (offset1 < offset2) return -1; return 1; })); }; /** * Get the offset to use for calculating position * @param {Object} settings The settings for this instantiation * @return {Float} The number of pixels to offset the calculations */ var getOffset = function (settings) { // if the offset is a function run it if (typeof settings.offset === 'function') { return parseFloat(settings.offset()); } // Otherwise, return it as-is return parseFloat(settings.offset); }; /** * Determine if an element is in the viewport * @param {Node} elem The element * @param {Object} settings The settings for this instantiation * @return {Boolean} Returns true if element is in the viewport */ var isInViewport = function (elem, settings) { var bounds = elem.getBoundingClientRect(); var offset = getOffset(settings); return parseInt(bounds.top, 10) <= offset && parseInt(bounds.bottom, 10) > offset; }; /** * Get the active content * @param {Array} contents The content areas * @param {Object} settings The settings for this instantiation * @return {Object} The content area and matching navigation link */ var getActive = function (contents, settings) { for (var i = contents.length - 1; i >= 0; i--) { if (isInViewport(contents[i].content, settings)) return contents[i]; } }; /** * Deactivate parent navs in a nested navigation * @param {Node} nav The starting navigation element * @param {Object} settings The settings for this instantiation */ var deactivateNested = function (nav, settings) { // If nesting isn't activated, bail if (!settings.nested) return; // Get the parent navigation var li = nav.parentNode.closest('li'); if (!li) return; // Remove the active class li.classList.remove(settings.nestedClass); // Apply recursively to any parent navigation elements deactivateNested(li, settings); }; /** * Deactivate a nav and content area * @param {Object} items The nav item and content to deactivate * @param {Object} settings The settings for this instantiation */ var deactivate = function (items, settings) { // Make sure their are items to deactivate if (!items) return; // Get the parent list item var li = items.nav.closest('li'); if (!li) return; // Remove the active class from the nav and content li.classList.remove(settings.navClass); items.content.classList.remove(settings.contentClass); // Deactivate any parent navs in a nested navigation deactivateNested(li, settings); // Emit a custom event emitEvent('gumshoeDeactivate', li, { link: items.nav, content: items.content, settings: settings }); }; /** * Activate parent navs in a nested navigation * @param {Node} nav The starting navigation element * @param {Object} settings The settings for this instantiation */ var activateNested = function (nav, settings) { // If nesting isn't activated, bail if (!settings.nested) return; // Get the parent navigation var li = nav.parentNode.closest('li'); if (!li) return; // Add the active class li.classList.add(settings.nestedClass); // Apply recursively to any parent navigation elements activateNested(li, settings); }; /** * Activate a nav and content area * @param {Object} items The nav item and content to activate * @param {Object} settings The settings for this instantiation */ var activate = function (items, settings) { // Make sure their are items to activate if (!items) return; // Get the parent list item var li = items.nav.closest('li'); if (!li) return; // Add the active class to the nav and content li.classList.add(settings.navClass); items.content.classList.add(settings.contentClass); // Activate any parent navs in a nested navigation activateNested(li, settings); // Emit a custom event emitEvent('gumshoeActivate', li, { link: items.nav, content: items.content, settings: settings }); }; /** * Create the Constructor object * @param {String} selector The selector to use for navigation items * @param {Object} options User options and settings */ var Constructor = function (selector, options) { // // Variables // var publicAPIs = {}; var navItems, contents, current, timeout, settings; // // Methods // /** * Set variables from DOM elements */ publicAPIs.setup = function () { // Get all nav items navItems = document.querySelectorAll(selector); // Create contents array contents = []; // Loop through each item, get it's matching content, and push to the array Array.prototype.forEach.call(navItems, (function (item) { // Get the content for the nav item var content = document.getElementById(decodeURIComponent(item.hash.substr(1))); if (!content) return; // Push to the contents array contents.push({ nav: item, content: content }); })); // Sort contents by the order they appear in the DOM sortContents(contents); }; /** * Detect which content is currently active */ publicAPIs.detect = function () { // Get the active content var active = getActive(contents, settings); // if there's no active content, deactivate and bail if (!active) { if (current) { deactivate(current, settings); current = null; } return; } // If the active content is the one currently active, do nothing if (current && active.content === current.content) return; // Deactivate the current content and activate the new content deactivate(current, settings); activate(active, settings); // Update the currently active content current = active; }; /** * Detect the active content on scroll * Debounced for performance */ var scrollHandler = function (event) { // If there's a timer, cancel it if (timeout) { window.cancelAnimationFrame(timeout); } // Setup debounce callback timeout = window.requestAnimationFrame(publicAPIs.detect); }; /** * Update content sorting on resize * Debounced for performance */ var resizeHandler = function (event) { // If there's a timer, cancel it if (timeout) { window.cancelAnimationFrame(timeout); } // Setup debounce callback timeout = window.requestAnimationFrame((function () { sortContents(); publicAPIs.detect(); })); }; /** * Destroy the current instantiation */ publicAPIs.destroy = function () { // Undo DOM changes if (current) { deactivate(current); } // Remove event listeners window.removeEventListener('scroll', scrollHandler, false); if (settings.reflow) { window.removeEventListener('resize', resizeHandler, false); } // Reset variables contents = null; navItems = null; current = null; timeout = null; settings = null; }; /** * Initialize the current instantiation * @param {Object} options User options and settings */ publicAPIs.init = function (options) { // Merge user options into defaults settings = extend(defaults, options || {}); // Setup variables based on the current DOM publicAPIs.setup(); // Find the currently active content publicAPIs.detect(); // Setup event listeners window.addEventListener('scroll', scrollHandler, false); if (settings.reflow) { window.addEventListener('resize', resizeHandler, false); } }; // // Initialize and return the public APIs // publicAPIs.init(options); return publicAPIs; }; // // Return the Constructor // return Constructor; }));
var Mocks = require("mocks"); var AssistantToTheTransportManager = require('core/transports/assistant_to_the_transport_manager').default; var Util = require('core/util').default; describe("AssistantToTheTransportManager", function() { var transport, transportClass; var manager; beforeEach(function() { jasmine.Clock.useMock(); spyOn(Util, "now").andReturn(1); transport = Mocks.getTransport(true); transportManager = Mocks.getTransportManager(); transportClass = Mocks.getTransportClass(true, transport); assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 10000, maxPingDelay: 120000 } ); }); describe("#isSupported", function() { it("should return true when transport is supported", function() { var assistant = new AssistantToTheTransportManager( transportManager, Mocks.getTransportClass(true), { minPingDelay: 10000, maxPingDelay: 50000 } ); expect(assistant.isSupported()).toBe(true); }); it("should return false when transport is not supported", function() { var assistant = new AssistantToTheTransportManager( transportManager, Mocks.getTransportClass(false), { minPingDelay: 10000, maxPingDelay: 50000 } ); expect(assistant.isSupported()).toBe(false); }); it("should return true if transport is alive", function() { transportManager.isAlive.andReturn(true); expect(assistant.isSupported()).toBe(true); }); it("should return false if transport is not alive", function() { transportManager.isAlive.andReturn(false); expect(assistant.isSupported()).toBe(false); }); }); describe("#createConnection", function() { it("should pass parameters to the transport", function() { assistant.createConnection("foo", 66, "abc", { test: true }); expect(transportClass.createConnection) .toHaveBeenCalledWith("foo", 66, "abc", { test: true }); }); it("should return the transport instance", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(connection).toBe(transport); }); }); describe("after an opened connection closed with a protocol error (code 1002)", function() { var connection; beforeEach(function() { connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100001); connection.emit("closed", { wasClean: true, code: 1002 }); }); it("should report its death to the manager", function() { expect(transportManager.reportDeath).toHaveBeenCalled(); }); }); describe("after an opened connection closed with a unsupported error (code 1003)", function() { var connection; beforeEach(function() { connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100001); connection.emit("closed", { wasClean: true, code: 1003 }); }); it("should report its death to the manager", function() { expect(transportManager.reportDeath).toHaveBeenCalled(); }); }); describe("after an opened connection died after less than 2*maxPingDelay", function() { var connection; var assistant; beforeEach(function() { assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 10000, maxPingDelay: 100000 } ); connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(190001); connection.emit("closed", { wasClean: false }); }); it("should report its death once to the manager", function() { expect(transportManager.reportDeath.calls.length).toEqual(1); }); it("should set the activity timeout on the next connection to lifetime/2 ms", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", { activityTimeout: 95000 } ); }); }); describe("after an opened connection died after more than 2*maxPingDelay", function() { var connection; var assistant; beforeEach(function() { assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 10000, maxPingDelay: 50000 } ); connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100002); connection.emit("closed", { wasClean: false }); }); it("should not report its death to the manager", function() { expect(transportManager.reportDeath).not.toHaveBeenCalled(); }); it("should not set the activity timeout on the next connection", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", {} ); }); }); describe("after an opened connection died after less than 2*minPingDelay", function() { var connection; var assistant; beforeEach(function() { assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 20000, maxPingDelay: 100000 } ); connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(32001); connection.emit("closed", { wasClean: false }); }); it("should report its death once to the manager", function() { expect(transportManager.reportDeath.calls.length).toEqual(1); }); it("should set the activity timeout on the next connection to minPingDelay ms", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", { activityTimeout: 20000 } ); }); }); describe("after an opened connection closed cleanly", function() { var connection; beforeEach(function() { connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100001); connection.emit("closed", { wasClean: true }); }); it("should not report its death to the manager", function() { expect(transportManager.reportDeath).not.toHaveBeenCalled(); }); it("should not set the activity timeout on the next connection", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", {} ); }); }); });
const React = require('react') module.exports = () => <div>test2</div>
/*! * Waves v0.5.3 * http://fian.my.id/Waves * * Copyright 2014 Alfiana E. Sibuea and other contributors * Released under the MIT license * https://github.com/fians/Waves/blob/master/LICENSE */ ;(function(window) { 'use strict'; var Waves = Waves || {}; var $$ = document.querySelectorAll.bind(document); // Find exact position of element function isWindow(obj) { return obj !== null && obj === obj.window; } function getWindow(elem) { return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView; } function offset(elem) { var docElem, win, box = {top: 0, left: 0}, doc = elem && elem.ownerDocument; docElem = doc.documentElement; if (typeof elem.getBoundingClientRect !== typeof undefined) { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; } function convertStyle(obj) { var style = ''; for (var a in obj) { if (obj.hasOwnProperty(a)) { style += (a + ':' + obj[a] + ';'); } } return style; } var Effect = { // Effect delay duration: 500, show: function(e) { // Disable right click if (e.button === 2) { return false; } var el = this; // Create ripple var ripple = document.createElement('div'); ripple.className = 'waves-ripple'; el.appendChild(ripple); // Get click coordinate and element witdh var pos = offset(el); var relativeY = (e.pageY - pos.top) - 10; var relativeX = (e.pageX - pos.left) - 10; // var scale = 'scale('+((el.clientWidth / 100) * 2.5)+')'; var scale = 'scale(15)'; // Support for touch devices if ('touches' in e) { relativeY = (e.touches[0].pageY - pos.top) - 45; relativeX = (e.touches[0].pageX - pos.left) - 45; } // Attach data to element ripple.setAttribute('data-hold', Date.now()); ripple.setAttribute('data-scale', scale); ripple.setAttribute('data-x', relativeX); ripple.setAttribute('data-y', relativeY); // Set ripple position var rippleStyle = { 'top': relativeY+'px', 'left': relativeX+'px' }; ripple.className = ripple.className + ' waves-notransition'; ripple.setAttribute('style', convertStyle(rippleStyle)); ripple.className = ripple.className.replace('waves-notransition', ''); // Scale the ripple rippleStyle['-webkit-transform'] = scale; rippleStyle['-moz-transform'] = scale; rippleStyle['-ms-transform'] = scale; rippleStyle['-o-transform'] = scale; rippleStyle.transform = scale; rippleStyle.opacity = '1'; rippleStyle['-webkit-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-moz-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-o-transition-duration'] = Effect.duration + 'ms'; rippleStyle['transition-duration'] = Effect.duration + 'ms'; ripple.setAttribute('style', convertStyle(rippleStyle)); }, hide: function() { var el = this; var width = el.clientWidth * 1.4; // Get first ripple var ripple = null; var childrenLength = el.children.length; for (var a = 0; a < childrenLength; a++) { if (el.children[a].className.indexOf('waves-ripple') !== -1) { ripple = el.children[a]; continue; } } if (!ripple) { return false; } var relativeX = ripple.getAttribute('data-x'); var relativeY = ripple.getAttribute('data-y'); var scale = ripple.getAttribute('data-scale'); // Get delay beetween mousedown and mouse leave var diff = Date.now() - Number(ripple.getAttribute('data-hold')); var delay = 500 - diff; if (delay < 0) { delay = 0; } // Fade out ripple after delay setTimeout(function() { var style = { 'top': relativeY+'px', 'left': relativeX+'px', 'opacity': '0', // Duration '-webkit-transition-duration': Effect.duration + 'ms', '-moz-transition-duration': Effect.duration + 'ms', '-o-transition-duration': Effect.duration + 'ms', 'transition-duration': Effect.duration + 'ms', '-webkit-transform': scale, '-moz-transform': scale, '-ms-transform': scale, '-o-transform': scale, 'transform': scale, }; ripple.setAttribute('style', convertStyle(style)); setTimeout(function() { try { el.removeChild(ripple); } catch(e) { return false; } }, Effect.duration); }, delay); }, // Little hack to make <input> can perform waves effect wrapInput: function(elements) { for (var a = 0; a < elements.length; a++) { var el = elements[a]; if (el.tagName.toLowerCase() === 'input') { var parent = el.parentNode; // If input already have parent just pass through if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) { return false; } // Put element class and style to the specified parent var wrapper = document.createElement('i'); wrapper.className = el.className + ' waves-input-wrapper'; var elementStyle = el.getAttribute('style'); var dimensionStyle = 'width:'+el.offsetWidth+'px;height:'+el.clientHeight+'px;'; if (!elementStyle) { elementStyle = ''; } wrapper.setAttribute('style', dimensionStyle+elementStyle); el.className = 'waves-button-input'; el.removeAttribute('style'); // Put element as child parent.replaceChild(wrapper, el); wrapper.appendChild(el); } } } }; Waves.displayEffect = function(options) { options = options || {}; if ('duration' in options) { Effect.duration = options.duration; } //Wrap input inside <i> tag Effect.wrapInput($$('.waves-effect')); Array.prototype.forEach.call($$('.waves-effect'), function(i) { if ('ontouchstart' in window) { i.addEventListener('mouseup', Effect.hide, false); i.addEventListener('touchstart', Effect.show, false); i.addEventListener('mouseleave', Effect.hide, false); i.addEventListener('touchend', Effect.hide, false); i.addEventListener('touchcancel', Effect.hide, false); } else { i.addEventListener('mousedown', Effect.show, false); i.addEventListener('mouseup', Effect.hide, false); i.addEventListener('mouseleave', Effect.hide, false); } }); }; window.Waves = Waves; Waves.displayEffect(); })(window);
/* * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, nomen: true, regexp: true, maxerr: 50 */ /*global define, brackets, $, window */ define(function (require, exports, module) { "use strict"; var KeyEvent = brackets.getModule("utils/KeyEvent"), Strings = brackets.getModule("strings"), Mustache = brackets.getModule("thirdparty/mustache/mustache"); var TimingFunctionUtils = require("TimingFunctionUtils"); /** Mustache template that forms the bare DOM structure of the UI */ var BezierCurveEditorTemplate = require("text!BezierCurveEditorTemplate.html"); /** @const @type {number} */ var HEIGHT_ABOVE = 75, // extra height above main grid HEIGHT_BELOW = 75, // extra height below main grid HEIGHT_MAIN = 150, // height of main grid WIDTH_MAIN = 150; // width of main grid var animationRequest = null; /** * CubicBezier object constructor * * @param {string|Array.number[4]} coordinates Four parameters passes to cubic-bezier() * either in string or array format. */ function CubicBezier(coordinates) { if (typeof coordinates === "string") { this.coordinates = coordinates.split(","); } else { this.coordinates = coordinates; } if (!this.coordinates) { throw "No offsets were defined"; } this.coordinates = this.coordinates.map(function (n) { return +n; }); var i; for (i = 3; i >= 0; i--) { var xy = this.coordinates[i]; if (isNaN(xy) || (((i % 2) === 0) && (xy < 0 || xy > 1))) { throw "Wrong coordinate at " + i + "(" + xy + ")"; } } } /** * BezierCanvas object constructor * * @param {Element} canvas Inline editor <canvas> element * @param {CubicBezier} bezier Associated CubicBezier object * @param {number|Array.number} padding Element padding */ function BezierCanvas(canvas, bezier, padding) { this.canvas = canvas; this.bezier = bezier; this.padding = this.getPadding(padding); // Convert to a cartesian coordinate system with axes from 0 to 1 var ctx = this.canvas.getContext("2d"), p = this.padding; ctx.scale(canvas.width * (1 - p[1] - p[3]), -canvas.height * 0.5 * (1 - p[0] - p[2])); ctx.translate(p[3] / (1 - p[1] - p[3]), (-1 - p[0] / (1 - p[0] - p[2])) - 0.5); } BezierCanvas.prototype = { /** * Calculates CSS offsets for <canvas> element * * @return {left:string, top:string} */ getOffsets: function () { var p = this.padding, w = this.canvas.width, h = this.canvas.height * 0.5; return [{ left: w * (this.bezier.coordinates[0] * (1 - p[3] - p[1]) - p[3]) + "px", top: h * (1 - this.bezier.coordinates[1] * (1 - p[0] - p[2]) - p[0]) + "px" }, { left: w * (this.bezier.coordinates[2] * (1 - p[3] - p[1]) - p[3]) + "px", top: h * (1 - this.bezier.coordinates[3] * (1 - p[0] - p[2]) - p[0]) + "px" }]; }, /** * Round off number to hundreths place, convert to string, and strip leading zero * * @param {number} v Value * @return {string} */ prettify: function (v) { return (Math.round(v * 100) / 100).toString().replace(/^0\./, "."); }, /** * Get CSS left, top offsets for endpoint handle * * @param {Element} element Endpoint handle <button> element * @return {Array.string[2]} */ offsetsToCoordinates: function (element) { var p = this.padding, w = this.canvas.width, h = this.canvas.height * 0.5; // Convert padding percentage to actual padding p = p.map(function (a, i) { return a * ((i % 2) ? w : h); }); return [ this.prettify((parseInt($(element).css("left"), 10) - p[3]) / (w + p[1] + p[3])), this.prettify((h - parseInt($(element).css("top"), 10) - p[2]) / (h - p[0] - p[2])) ]; }, /** * Paint canvas * * @param {Object} settings Paint settings */ plot: function (settings) { var xy = this.bezier.coordinates, ctx = this.canvas.getContext("2d"), setting; var defaultSettings = { handleTimingFunction: "#2893ef", handleThickness: 0.008, vBorderThickness: 0.02, hBorderThickness: 0.01, bezierTimingFunction: "#2893ef", bezierThickness: 0.03 }; settings = settings || {}; for (setting in defaultSettings) { if (defaultSettings.hasOwnProperty(setting)) { if (!settings.hasOwnProperty(setting)) { settings[setting] = defaultSettings[setting]; } } } ctx.clearRect(-0.5, -0.5, 2, 2); // Draw control handles ctx.beginPath(); ctx.fillStyle = settings.handleTimingFunction; ctx.lineWidth = settings.handleThickness; ctx.strokeStyle = settings.handleTimingFunction; ctx.moveTo(0, 0); ctx.lineTo(xy[0], xy[1]); ctx.moveTo(1, 1); ctx.lineTo(xy[2], xy[3]); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.arc(xy[0], xy[1], 1.5 * settings.handleThickness, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.arc(xy[2], xy[3], 1.5 * settings.handleThickness, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fill(); // Draw bezier curve ctx.beginPath(); ctx.lineWidth = settings.bezierThickness; ctx.strokeStyle = settings.bezierColor; ctx.moveTo(0, 0); ctx.bezierCurveTo(xy[0], xy[1], xy[2], xy[3], 1, 1); ctx.stroke(); ctx.closePath(); }, /** * Convert CSS padding shorthand to longhand * * @param {number|Array.number} padding Element padding * @return {Array.number} */ getPadding: function (padding) { var p = (typeof padding === "number") ? [padding] : padding; if (p.length === 1) { p[1] = p[0]; } if (p.length === 2) { p[2] = p[0]; } if (p.length === 3) { p[3] = p[1]; } return p; } }; // Event handlers /** * Handle click in <canvas> element * * @param {Event} e Mouse click event */ function _curveClick(e) { var self = e.target, bezierEditor = self.bezierEditor; var curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE, $P1 = $(bezierEditor.P1), $P2 = $(bezierEditor.P2); // Helper function to calculate distance between 2-D points function distance(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } // Find which point is closer var distP1 = distance(x, y, parseInt($P1.css("left"), 10), parseInt($P1.css("top"), 10)), distP2 = distance(x, y, parseInt($P2.css("left"), 10), parseInt($P2.css("top"), 10)), $P = (distP1 < distP2) ? $P1 : $P2; $P.css({ left: x + "px", top: y + "px" }); $P.get(0).focus(); // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); } /** * Helper function for handling point move * * @param {Event} e Mouse move event * @param {number} x New horizontal position * @param {number} y New vertical position */ function handlePointMove(e, x, y) { var self = e.target, bezierEditor = self.bezierEditor; // Helper function to redraw curve function mouseMoveRedraw() { if (!bezierEditor.dragElement) { animationRequest = null; return; } // Update code bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); animationRequest = window.requestAnimationFrame(mouseMoveRedraw); } // This is a dragging state, but left button is no longer down, so mouse // exited element, was released, and re-entered element. Treat like a drop. if (bezierEditor.dragElement && (e.which !== 1)) { bezierEditor.dragElement = null; bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); bezierEditor = null; return; } // Constrain time (x-axis) to 0 to 1 range. Progression (y-axis) is // theoretically not constrained, although canvas to drawing curve is // arbitrarily constrained to -0.5 to 1.5 range. x = Math.min(Math.max(0, x), WIDTH_MAIN); if (bezierEditor.dragElement) { $(bezierEditor.dragElement).css({ left: x + "px", top: y + "px" }); } // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); if (!animationRequest) { animationRequest = window.requestAnimationFrame(mouseMoveRedraw); } } /** * Update Time (x-axis) and Progression (y-axis) data for mouse position * * @param {Element} canvas <canvas> element * @param {number} x Horizontal position * @param {number} y Vertical position */ function updateTimeProgression(curve, x, y) { var percentX = Math.round(100 * x / WIDTH_MAIN), percentY = Math.round(100 * ((HEIGHT_MAIN - y) / HEIGHT_MAIN)); // Constrain horizontal percentage to [0, 100] range percentX = Math.min(Math.max(0, percentX), 100); curve.parentNode.setAttribute("data-time", percentX); curve.parentNode.setAttribute("data-progression", percentY); } /** * Handle mouse move in <canvas> element * * @param {Event} e Mouse move event */ function _curveMouseMove(e) { var self = e.target, bezierEditor = self.bezierEditor, curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE; updateTimeProgression(self, x, y); if (bezierEditor.dragElement) { if (e.pageX === 0 && e.pageY === 0) { return; } handlePointMove(e, x, y); } } /** * Handle mouse move in <button> element * * @param {Event} e Mouse move event */ function _pointMouseMove(e) { var self = e.target, bezierEditor = self.bezierEditor, curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE; updateTimeProgression(bezierEditor.curve, x, y); if (e.pageX === 0 && e.pageY === 0) { return; } handlePointMove(e, x, y); } /** * Handle mouse down in <button> element * * @param {Event} e Mouse down event */ function _pointMouseDown(e) { var self = e.target; self.bezierEditor.dragElement = self; } /** * Handle mouse up in <button> element * * @param {Event} e Mouse up event */ function _pointMouseUp(e) { var self = e.target; self.focus(); if (self.bezierEditor.dragElement) { self.bezierEditor.dragElement = null; self.bezierEditor._commitTimingFunction(); self.bezierEditor._updateCanvas(); } } /** * Handle key down in <button> element * * @param {Event} e Key down event */ function _pointKeyDown(e) { var code = e.keyCode, self = e.target, bezierEditor = self.bezierEditor; if (code >= KeyEvent.DOM_VK_LEFT && code <= KeyEvent.DOM_VK_DOWN) { e.preventDefault(); // Arrow keys pressed var $this = $(e.target), left = parseInt($this.css("left"), 10), top = parseInt($this.css("top"), 10), offset = (e.shiftKey ? 15 : 3), newVal; switch (code) { case KeyEvent.DOM_VK_LEFT: newVal = Math.max(0, left - offset); if (left === newVal) { return false; } $this.css({ left: newVal + "px" }); break; case KeyEvent.DOM_VK_UP: newVal = Math.max(-HEIGHT_ABOVE, top - offset); if (top === newVal) { return false; } $this.css({ top: newVal + "px" }); break; case KeyEvent.DOM_VK_RIGHT: newVal = Math.min(WIDTH_MAIN, left + offset); if (left === newVal) { return false; } $this.css({ left: newVal + "px" }); break; case KeyEvent.DOM_VK_DOWN: newVal = Math.min(HEIGHT_MAIN + HEIGHT_BELOW, top + offset); if (top === newVal) { return false; } $this.css({ top: newVal + "px" }); break; } // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); return true; } else if (code === KeyEvent.DOM_VK_ESCAPE) { return true; } else if (code === KeyEvent.DOM_VK_TAB && !e.ctrlKey && !e.metaKey && !e.altKey) { // Switch between the two points by tabbing if ($(e.target).hasClass("P1")) { $(".P2").focus(); } else { $(".P1").focus(); } e.preventDefault(); return true; } return false; } /** * Constructor for BezierCurveEditor Object. This control may be used standalone * or within an InlineTimingFunctionEditor inline widget. * * @param {!jQuery} $parent DOM node into which to append the root of the bezier curve editor UI * @param {!RegExpMatch} bezierCurve RegExp match object of initially selected bezierCurve * @param {!function(string)} callback Called whenever selected bezierCurve changes */ function BezierCurveEditor($parent, bezierCurve, callback) { // Create the DOM structure, filling in localized strings via Mustache this.$element = $(Mustache.render(BezierCurveEditorTemplate, Strings)); $parent.append(this.$element); this._callback = callback; this.dragElement = null; // current cubic-bezier() function params this._cubicBezierCoords = this._getCubicBezierCoords(bezierCurve); this.hint = {}; this.hint.elem = $(".hint", this.$element); // If function was auto-corrected, then originalString holds the original function, // and an informational message needs to be shown if (bezierCurve.originalString) { TimingFunctionUtils.showHideHint(this.hint, true, bezierCurve.originalString, "cubic-bezier(" + this._cubicBezierCoords.join(", ") + ")"); } else { TimingFunctionUtils.showHideHint(this.hint, false); } this.P1 = this.$element.find(".P1")[0]; this.P2 = this.$element.find(".P2")[0]; this.curve = this.$element.find(".curve")[0]; this.P1.bezierEditor = this.P2.bezierEditor = this.curve.bezierEditor = this; this.bezierCanvas = new BezierCanvas(this.curve, null, [0, 0]); // redraw canvas this._updateCanvas(); $(this.curve) .on("click", _curveClick) .on("mousemove", _curveMouseMove); $(this.P1) .on("mousemove", _pointMouseMove) .on("mousedown", _pointMouseDown) .on("mouseup", _pointMouseUp) .on("keydown", _pointKeyDown); $(this.P2) .on("mousemove", _pointMouseMove) .on("mousedown", _pointMouseDown) .on("mouseup", _pointMouseUp) .on("keydown", _pointKeyDown); } /** * Destructor called by InlineTimingFunctionEditor.onClosed() */ BezierCurveEditor.prototype.destroy = function () { this.P1.bezierEditor = this.P2.bezierEditor = this.curve.bezierEditor = null; $(this.curve) .off("click", _curveClick) .off("mousemove", _curveMouseMove); $(this.P1) .off("mousemove", _pointMouseMove) .off("mousedown", _pointMouseDown) .off("mouseup", _pointMouseUp) .off("keydown", _pointKeyDown); $(this.P2) .off("mousemove", _pointMouseMove) .off("mousedown", _pointMouseDown) .off("mouseup", _pointMouseUp) .off("keydown", _pointKeyDown); }; /** Returns the root DOM node of the BezierCurveEditor UI */ BezierCurveEditor.prototype.getRootElement = function () { return this.$element; }; /** * Default focus needs to go somewhere, so give it to P1 */ BezierCurveEditor.prototype.focus = function () { this.P1.focus(); return true; }; /** * Generates cubic-bezier function based on coords, and updates the doc */ BezierCurveEditor.prototype._commitTimingFunction = function () { var bezierCurveVal = "cubic-bezier(" + this._cubicBezierCoords[0] + ", " + this._cubicBezierCoords[1] + ", " + this._cubicBezierCoords[2] + ", " + this._cubicBezierCoords[3] + ")"; this._callback(bezierCurveVal); TimingFunctionUtils.showHideHint(this.hint, false); }; /** * Handle all matches returned from TimingFunctionUtils.cubicBezierMatch() and * return array of coords * * @param {RegExp.match} match Matches returned from cubicBezierMatch() * @return {Array.number[4]} */ BezierCurveEditor.prototype._getCubicBezierCoords = function (match) { if (match[0].match(/^cubic-bezier/)) { // cubic-bezier() return match.slice(1, 5); } else { // handle special cases of cubic-bezier calls switch (match[0]) { case "linear": return [ "0", "0", "1", "1" ]; case "ease": return [ ".25", ".1", ".25", "1" ]; case "ease-in": return [ ".42", "0", "1", "1" ]; case "ease-out": return [ "0", "0", ".58", "1" ]; case "ease-in-out": return [ ".42", "0", ".58", "1" ]; } } window.console.log("brackets-cubic-bezier: getCubicBezierCoords() passed invalid RegExp match array"); return [ "0", "0", "0", "0" ]; }; /** * Get <canvas> element's bounding box * * @return {left: number, top: number, width: number, height: number} */ BezierCurveEditor.prototype._getCurveBoundingBox = function () { var $canvas = this.$element.find(".curve"), canvasOffset = $canvas.offset(); return { left: canvasOffset.left, top: canvasOffset.top, width: $canvas.width(), height: $canvas.height() }; }; /** * Update <canvas> after a change */ BezierCurveEditor.prototype._updateCanvas = function () { // collect data, build model if (this._cubicBezierCoords) { this.bezierCanvas.bezier = window.bezier = new CubicBezier(this._cubicBezierCoords); var offsets = this.bezierCanvas.getOffsets(); $(this.P1).css({ left: offsets[0].left, top: offsets[0].top }); $(this.P2).css({ left: offsets[1].left, top: offsets[1].top }); this.bezierCanvas.plot(); } }; /** * Handle external update * * @param {!RegExpMatch} bezierCurve RegExp match object of updated bezierCurve */ BezierCurveEditor.prototype.handleExternalUpdate = function (bezierCurve) { this._cubicBezierCoords = this._getCubicBezierCoords(bezierCurve); this._updateCanvas(); // If function was auto-corrected, then originalString holds the original function, // and an informational message needs to be shown if (bezierCurve.originalString) { TimingFunctionUtils.showHideHint(this.hint, true, bezierCurve.originalString, "cubic-bezier(" + this._cubicBezierCoords.join(", ") + ")"); } else { TimingFunctionUtils.showHideHint(this.hint, false); } }; exports.BezierCurveEditor = BezierCurveEditor; });
uv.LineGraph = function (graphdef, config) { var self = this; uv.Graph.call(self, graphdef, config).setDefaults().init(); self.linegroups = {}; self.dataset = uv.util.getDataArray(self.graphdef); var linegroup, linepath, linefunc, idx, len = self.categories.length, domainData = self.labels; self.axes[self.config.graph.orientation === 'Horizontal' ? 'ver' : 'hor'].scale.domain(domainData); for (idx = 0; idx < len; idx = idx + 1) { linepath = self.chart.append('g').classed('cg-' + uv.util.formatClassName(self.categories[idx]), true) .append('g').classed('cge-' + uv.util.formatClassName(self.categories[idx]), true).datum(self.dataset[idx]); linegroup = { path: linepath, func: undefined }; self['draw' + self.config.graph.orientation + 'Lines'](linegroup, idx); self.linegroups[self.categories[idx]] = linegroup; } self.finalize(); }; uv.LineGraph.prototype = uv.util.inherits(uv.Graph); uv.LineGraph.prototype.setDefaults = function () { var self = this; self.graphdef.stepup = 'normal'; self.config.scale.ordinality = 0; return this; }; uv.LineGraph.prototype.drawHorizontalLines = function (linegroup, idx) { var self = this, axes = self.axes, config = self.config, color = uv.util.getColorBand(self.config, idx); self.axes.ver.scale.rangePoints([0, self.height()]); linegroup.func = d3.svg.line() .x(function (d) { return axes.hor.scale(d.value); }) .y(function (d) { return axes.ver.scale(d.name) + axes.ver.scale.rangeBand() / 2; }) .interpolate(uv.config.line.interpolation); linegroup.path.append('path') .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .attr('d', linegroup.func) .style('fill', 'none') .style('stroke', color) .style('stroke-width', self.config.line.strokewidth) .style('stroke-opacity', self.config.line.strokeopacity) .transition() .duration(3 * self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('stroke-opacity', 1) .call(uv.util.endAll, function (d,i){ d3.select(this.parentNode.parentNode).selectAll('path').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('path').on('mouseout', uv.effects.line.mouseout(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseout', uv.effects.line.mouseout(self, idx)); }); if (self.config.line.showcircles) { linegroup.path.selectAll('circle') .data(self.dataset[idx]) .enter().append('circle') .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .attr('cx', linegroup.func.x()) .attr('cy', linegroup.func.y()) .attr('r', self.config.line.circleradius) .style('fill', color) .style('fill-opacity', self.config.line.circleopacity) .style('stroke', '#fff') .append('svg:title') .text( function (d, i) { return uv.util.getTooltipText(self, self.categories[idx], self.labels[i], d);}); } linegroup.path.selectAll('text') .data(self.dataset[idx]) .enter().append('text') .attr('x', function (d) { return axes.hor.scale(d.value); }) .attr('y', function(d) { return axes.ver.scale(d.name) + axes.ver.scale.rangeBand()/2; }) .attr('dx', 10) .attr('dy', '.35em') .attr('text-anchor', 'start') .style('opacity', 0) .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', self.config.label.showlabel ? uv.util.getColorBand(self.config, idx) : 'none') .style('font-family', self.config.line.fontfamily) .style('font-size', self.config.line.fontsize) .style('font-weight', self.config.line.fontweight) .text(function(d) { return uv.util.getLabelValue(self, d); }) .transition() .duration(3 * self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('opacity', 1); return this; }; uv.LineGraph.prototype.drawVerticalLines = function (linegroup, idx) { var self = this, axes = self.axes, config = self.config, color = uv.util.getColorBand(self.config, idx); self.axes.hor.scale.rangePoints([0, self.width()]); linegroup.func = d3.svg.line() .x(function (d) { return axes.hor.scale(d.name) + axes.hor.scale.rangeBand() / 2; }) .y(function (d) { return axes.ver.scale(d.value); }) .interpolate(uv.config.line.interpolation); linegroup.path.append('path') .attr('d', linegroup.func) .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', 'none') .style('stroke', color) .style('stroke-width', self.config.line.strokewidth) .style('stroke-opacity', self.config.line.strokeopacity) .transition() .duration(self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('stroke-opacity', 1) .call(uv.util.endAll, function (d,i){ d3.select(this.parentNode.parentNode).selectAll('path').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('path').on('mouseout', uv.effects.line.mouseout(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseout', uv.effects.line.mouseout(self, idx)); }); if (self.config.line.showcircles) { linegroup.path.selectAll('circle') .data(self.dataset[idx]) .enter().append('circle') .attr('cx', linegroup.func.x()) .attr('cy', linegroup.func.y()) .attr('r', self.config.line.circleradius) .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', color) .style('fill-opacity', self.config.line.circleopacity) .style('stroke', '#fff') .append('svg:title') .text( function (d, i) { return uv.util.getTooltipText(self, self.categories[idx], self.labels[i], d);}); } linegroup.path.selectAll('text') .data(self.dataset[idx]) .enter().append('text') .attr('x', function (d) { return axes.hor.scale(d.name) + axes.hor.scale.rangeBand() / 2; }) .attr('y', function (d) { return axes.ver.scale(d.value) - 20; }) .attr('dx', 0) .attr('dy', '.71em') .attr('text-anchor', 'middle') .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', self.config.label.showlabel ? uv.util.getColorBand(self.config, idx) : 'none') .style('font-family', self.config.line.fontfamily) .style('font-size', self.config.line.fontsize) .style('font-weight', self.config.line.fontweight) .style('opacity', 0) .text(function(d) { return uv.util.getLabelValue(self, d); }) .transition() .duration(3 * self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('opacity', 1); return this; };
var _ = require('lodash'), Promise = require('bluebird'), models = require('../../../../models'), utils = require('../../../../utils'), SubscribersImporter = require('./subscribers'), PostsImporter = require('./posts'), TagsImporter = require('./tags'), SettingsImporter = require('./settings'), UsersImporter = require('./users'), RolesImporter = require('./roles'), importers = {}, DataImporter; DataImporter = { type: 'data', preProcess: function preProcess(importData) { importData.preProcessedByData = true; return importData; }, init: function init(importData) { importers.roles = new RolesImporter(importData.data); importers.tags = new TagsImporter(importData.data); importers.users = new UsersImporter(importData.data); importers.subscribers = new SubscribersImporter(importData.data); importers.posts = new PostsImporter(importData.data); importers.settings = new SettingsImporter(importData.data); return importData; }, doImport: function doImport(importData) { var ops = [], errors = [], results = [], options = { importing: true, context: { internal: true } }; this.init(importData); return models.Base.transaction(function (transacting) { options.transacting = transacting; _.each(importers, function (importer) { ops.push(function doModelImport() { return importer.beforeImport(options) .then(function () { return importer.doImport(options) .then(function (_results) { results = results.concat(_results); }); }); }); }); _.each(importers, function (importer) { ops.push(function afterImport() { return importer.afterImport(options); }); }); utils.sequence(ops) .then(function () { results.forEach(function (promise) { if (!promise.isFulfilled()) { errors = errors.concat(promise.reason()); } }); if (errors.length === 0) { transacting.commit(); } else { transacting.rollback(errors); } }); }).then(function () { /** * data: imported data * originalData: data from the json file * problems: warnings */ var toReturn = { data: {}, originalData: importData.data, problems: [] }; _.each(importers, function (importer) { toReturn.problems = toReturn.problems.concat(importer.problems); toReturn.data[importer.dataKeyToImport] = importer.importedData; }); return toReturn; }).catch(function (errors) { return Promise.reject(errors); }); } }; module.exports = DataImporter;
var utils = require('../../../utils'); module.exports = function CodeType(config) { var self = { selector: '.field-type-code[for="' + config.fieldName + '"]', elements: { label: '.FormLabel', lineNumber: '.CodeMirror-linenumber', codeMirror: '.CodeMirror-container', }, commands: [{ assertUI: function() { this .expect.element('@label').to.be.visible; this .expect.element('@label').text.to.equal(utils.titlecase(config.fieldName)); this .expect.element('@lineNumber').to.be.visible; this .expect.element('@lineNumber').text.to.equal('1'); this .expect.element('@codeMirror').to.be.visible; return this; }, fillInput: function(input) { this.api .execute(function (selector, input) { var x = document.querySelector(selector); var y = x.getElementsByClassName('CodeMirror')[0]; y.CodeMirror.setValue(input.value); }, [self.selector, input]); return this; }, assertInput: function(input) { this.api .execute(function (selector) { var x = document.querySelector(selector); var y = x.getElementsByClassName('CodeMirror')[0]; return y.CodeMirror.getValue(); }, [self.selector], function (result) { this.assert.equal(result.value, input.value); }); return this; }, }], }; return self; };
// Run if you want to monitor unresolved promises (in properly working // application there should be no promises that are never resolved) 'use strict'; var max = Math.max , callable = require('es5-ext/lib/Object/valid-callable') , isCallable = require('es5-ext/lib/Object/is-callable') , toUint = require('es5-ext/lib/Number/to-uint') , deferred = require('./deferred'); exports = module.exports = function (timeout, cb) { if (timeout === false) { // Cancel monitor delete deferred._monitor; delete exports.timeout; delete exports.callback; return; } exports.timeout = timeout = max(toUint(timeout) || 5000, 50); if (cb == null) { if ((typeof console !== 'undefined') && console && isCallable(console.error)) { cb = function (e) { console.error(((e.stack && e.stack.toString()) || "Unresolved promise: no stack available")); }; } } else { callable(cb); } exports.callback = cb; deferred._monitor = function () { var e = new Error("Unresolved promise"); return setTimeout(function () { if (cb) cb(e); }, timeout); }; };
define( //begin v1.x content { "field-quarter-short-relative+0": "tento štvrťr.", "field-quarter-short-relative+1": "budúci štvrťr.", "dayPeriods-standAlone-abbr-noon": "pol.", "field-tue-relative+-1": "minulý utorok", "field-year": "rok", "dateFormatItem-yw": "w. 'týždeň' 'v' 'roku' y", "dayPeriods-format-abbr-afternoon1": "popol.", "dateFormatItem-Hm": "H:mm", "field-wed-relative+0": "túto stredu", "field-wed-relative+1": "budúcu stredu", "dateFormatItem-ms": "mm:ss", "timeFormat-short": "H:mm", "field-minute": "minúta", "field-tue-narrow-relative+0": "tento ut.", "field-tue-narrow-relative+1": "budúci ut.", "field-thu-short-relative+0": "tento št.", "dateTimeFormat-short": "{1} {0}", "field-thu-short-relative+1": "budúci št.", "field-day-relative+0": "dnes", "field-day-relative+1": "zajtra", "field-day-relative+2": "pozajtra", "field-wed-narrow-relative+-1": "minulú st.", "field-year-narrow": "r.", "field-tue-relative+0": "tento utorok", "field-tue-relative+1": "budúci utorok", "field-second-short": "s", "dayPeriods-format-narrow-am": "AM", "dayPeriods-standAlone-abbr-morning1": "ráno", "dayPeriods-standAlone-abbr-morning2": "dopol.", "dateFormatItem-MMMd": "d. M.", "dayPeriods-format-narrow-morning1": "ráno", "dayPeriods-format-narrow-morning2": "dop.", "dayPeriods-format-abbr-am": "AM", "field-week-relative+0": "tento týždeň", "field-month-relative+0": "tento mesiac", "field-week-relative+1": "budúci týždeň", "field-month-relative+1": "budúci mesiac", "field-sun-narrow-relative+0": "túto ne.", "timeFormat-medium": "H:mm:ss", "field-mon-short-relative+0": "tento pond.", "field-sun-narrow-relative+1": "budúcu ne.", "field-mon-short-relative+1": "budúci pond.", "field-second-relative+0": "teraz", "months-standAlone-narrow": [ "j", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d" ], "dayPeriods-standAlone-wide-noon": "poludnie", "eraNames": [ "pred Kristom", "po Kristovi" ], "dayPeriods-standAlone-abbr-pm": "PM", "field-month-short": "mes.", "dateFormatItem-GyMMMEd": "E, d. M. y G", "field-day": "deň", "dayPeriods-standAlone-wide-night1": "noc", "field-year-relative+-1": "minulý rok", "dayPeriods-format-wide-am": "AM", "field-sat-short-relative+-1": "minulú so.", "dayPeriods-format-narrow-afternoon1": "pop.", "dayPeriods-format-wide-afternoon1": "popoludní", "field-hour-relative+0": "v tejto hodine", "field-wed-relative+-1": "minulú stredu", "dateTimeFormat-medium": "{1}, {0}", "field-sat-narrow-relative+-1": "minulú so.", "field-second": "sekunda", "days-standAlone-narrow": [ "n", "p", "u", "s", "š", "p", "s" ], "dayPeriods-standAlone-narrow-noon": "pol.", "dayPeriods-standAlone-wide-pm": "PM", "dateFormatItem-Ehms": "E h:mm:ss a", "dateFormat-long": "d. MMMM y", "dateFormatItem-GyMMMd": "d. M. y G", "dayPeriods-standAlone-abbr-midnight": "poln.", "field-quarter": "štvrťrok", "field-week-short": "týž.", "dayPeriods-format-narrow-midnight": "o poln.", "dateFormatItem-yMMMEd": "E d. M. y", "quarters-standAlone-wide": [ "1. štvrťrok", "2. štvrťrok", "3. štvrťrok", "4. štvrťrok" ], "days-format-narrow": [ "n", "p", "u", "s", "š", "p", "s" ], "dayPeriods-format-wide-evening1": "večer", "dateTimeFormats-appendItem-Timezone": "{0} {1}", "field-tue-short-relative+0": "tento utor.", "field-tue-short-relative+1": "budúci utor.", "field-mon-relative+-1": "minulý pondelok", "dateFormatItem-GyMMM": "LLLL y G", "field-month": "mesiac", "field-day-narrow": "d.", "dayPeriods-standAlone-abbr-night1": "noc", "dayPeriods-standAlone-narrow-afternoon1": "pop.", "dateFormatItem-MMM": "LLL", "field-minute-short": "min", "field-dayperiod": "časť dňa", "field-sat-short-relative+0": "túto so.", "field-sat-short-relative+1": "budúcu so.", "dayPeriods-format-narrow-pm": "PM", "dateFormat-medium": "d. M. y", "eraAbbr": [ "pred Kr.", "po Kr." ], "quarters-standAlone-abbr": [ "Q1", "Q2", "Q3", "Q4" ], "dayPeriods-format-abbr-pm": "PM", "field-second-narrow": "s", "field-mon-relative+0": "tento pondelok", "dayPeriods-standAlone-narrow-night1": "noc", "field-mon-relative+1": "budúci pondelok", "field-year-short": "r.", "months-format-narrow": [ "j", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d" ], "dayPeriods-format-wide-morning1": "ráno", "dayPeriods-format-wide-morning2": "dopoludnia", "field-quarter-relative+-1": "minulý štvrťrok", "dayPeriods-standAlone-narrow-am": "AM", "days-format-short": [ "ne", "po", "ut", "st", "št", "pi", "so" ], "quarters-format-narrow": [ "1", "2", "3", "4" ], "dayPeriods-format-wide-pm": "PM", "field-sat-relative+-1": "minulú sobotu", "dateTimeFormat-long": "{1}, {0}", "dateFormatItem-Md": "d. M.", "field-hour": "hodina", "dateFormatItem-yQQQQ": "QQQQ y", "months-format-wide": [ "januára", "februára", "marca", "apríla", "mája", "júna", "júla", "augusta", "septembra", "októbra", "novembra", "decembra" ], "dayPeriods-format-wide-night1": "v noci", "dateFormat-full": "EEEE, d. MMMM y", "field-month-relative+-1": "minulý mesiac", "dateFormatItem-Hms": "H:mm:ss", "field-quarter-short": "Q", "field-sat-narrow-relative+0": "túto so.", "dateFormatItem-Hmv": "H:mm v", "field-fri-relative+0": "tento piatok", "field-sat-narrow-relative+1": "budúcu so.", "field-fri-relative+1": "budúci piatok", "dayPeriods-format-narrow-noon": "nap.", "field-sun-short-relative+0": "túto ned.", "field-sun-short-relative+1": "budúcu ned.", "field-week-relative+-1": "minulý týždeň", "field-quarter-short-relative+-1": "minulý štvrťr.", "dateFormatItem-Ehm": "E h:mm a", "months-format-abbr": [ "jan", "feb", "mar", "apr", "máj", "jún", "júl", "aug", "sep", "okt", "nov", "dec" ], "dayPeriods-format-wide-midnight": "o polnoci", "field-quarter-relative+0": "tento štvrťrok", "field-minute-relative+0": "v tejto minúte", "timeFormat-long": "H:mm:ss z", "field-quarter-relative+1": "budúci štvrťrok", "field-wed-short-relative+-1": "minulú str.", "dateFormatItem-yMMM": "M/y", "dateFormat-short": "d. M. y", "field-thu-short-relative+-1": "minulý št.", "dayPeriods-format-abbr-night1": "v noci", "dateFormatItem-MMMMW": "W. 'týždeň' 'v' MMM", "days-standAlone-wide": [ "nedeľa", "pondelok", "utorok", "streda", "štvrtok", "piatok", "sobota" ], "field-mon-narrow-relative+-1": "minulý po.", "dateFormatItem-MMMMd": "d. MMMM", "field-thu-narrow-relative+-1": "minulý št.", "dateFormatItem-E": "ccc", "dateFormatItem-mmss": "mm:ss", "dateFormatItem-H": "H", "field-tue-narrow-relative+-1": "minulý ut.", "dayPeriods-format-abbr-evening1": "večer", "dayPeriods-standAlone-narrow-pm": "PM", "dateFormatItem-M": "L.", "months-standAlone-wide": [ "január", "február", "marec", "apríl", "máj", "jún", "júl", "august", "september", "október", "november", "december" ], "field-wed-short-relative+0": "túto str.", "field-wed-short-relative+1": "budúcu str.", "dateFormatItem-Hmsv": "H:mm:ss v", "field-sun-relative+-1": "minulú nedeľu", "dateFormatItem-MMMMEd": "E d. MMMM", "days-standAlone-abbr": [ "ne", "po", "ut", "st", "št", "pi", "so" ], "dateTimeFormat-full": "{1}, {0}", "dateFormatItem-hm": "h:mm a", "dateFormatItem-d": "d.", "field-weekday": "deň týždňa", "dayPeriods-standAlone-wide-evening1": "večer", "field-quarter-narrow-relative+0": "tento štvrťr.", "field-sat-relative+0": "túto sobotu", "dateFormatItem-h": "h a", "field-quarter-narrow-relative+1": "budúci štvrťr.", "field-sat-relative+1": "budúcu sobotu", "months-standAlone-abbr": [ "jan", "feb", "mar", "apr", "máj", "jún", "júl", "aug", "sep", "okt", "nov", "dec" ], "dateFormatItem-hmsv": "h:mm:ss a v", "dayPeriods-format-abbr-morning1": "ráno", "dayPeriods-standAlone-narrow-evening1": "več.", "dayPeriods-format-abbr-morning2": "dopol.", "timeFormat-full": "H:mm:ss zzzz", "dateFormatItem-MEd": "E d. M.", "dateFormatItem-y": "y", "field-thu-narrow-relative+0": "tento št.", "field-sun-narrow-relative+-1": "minulú ne.", "field-mon-short-relative+-1": "minulý pond.", "field-thu-narrow-relative+1": "budúci št.", "field-thu-relative+0": "tento štvrtok", "dayPeriods-standAlone-abbr-afternoon1": "popol.", "field-thu-relative+1": "budúci štvrtok", "dateFormatItem-hms": "h:mm:ss a", "field-fri-short-relative+-1": "minulý pi.", "dateFormatItem-hmv": "h:mm a v", "dayPeriods-format-abbr-noon": "napol.", "field-thu-relative+-1": "minulý štvrtok", "dateFormatItem-yMd": "d. M. y", "quarters-standAlone-narrow": [ "1", "2", "3", "4" ], "field-week": "týždeň", "quarters-format-wide": [ "1. štvrťrok", "2. štvrťrok", "3. štvrťrok", "4. štvrťrok" ], "dateFormatItem-Ed": "E d.", "field-wed-narrow-relative+0": "túto st.", "field-wed-narrow-relative+1": "budúcu st.", "dayPeriods-standAlone-wide-morning1": "ráno", "dayPeriods-standAlone-wide-morning2": "dopoludnie", "field-quarter-narrow-relative+-1": "minulý štvrťr.", "field-fri-short-relative+0": "tento pi.", "field-fri-short-relative+1": "budúci pi.", "days-standAlone-short": [ "ne", "po", "ut", "st", "št", "pi", "so" ], "dayPeriods-standAlone-narrow-morning1": "ráno", "dayPeriods-standAlone-narrow-morning2": "dop.", "dateFormatItem-GyMMMMd": "d. M. y G", "dayPeriods-format-abbr-midnight": "o poln.", "field-hour-short": "h", "quarters-format-abbr": [ "Q1", "Q2", "Q3", "Q4" ], "field-month-narrow": "mes.", "field-hour-narrow": "h", "field-fri-narrow-relative+-1": "minulý pi.", "field-year-relative+0": "tento rok", "field-year-relative+1": "budúci rok", "field-fri-relative+-1": "minulý piatok", "eraNarrow": [ "pred Kr.", "po Kr." ], "dayPeriods-format-wide-noon": "napoludnie", "field-tue-short-relative+-1": "minulý utor.", "field-minute-narrow": "min", "dayPeriods-standAlone-wide-afternoon1": "popoludnie", "dateFormatItem-yQQQ": "QQQ y", "days-format-wide": [ "nedeľa", "pondelok", "utorok", "streda", "štvrtok", "piatok", "sobota" ], "dateFormatItem-yMMMMd": "d. MMMM y", "field-mon-narrow-relative+0": "tento po.", "dateFormatItem-EHm": "E HH:mm", "field-mon-narrow-relative+1": "budúci po.", "dayPeriods-standAlone-wide-midnight": "polnoc", "dateFormatItem-yM": "M/y", "field-zone": "časové pásmo", "dateFormatItem-yMMMM": "LLLL y", "dateFormatItem-MMMEd": "E d. M.", "dateFormatItem-EHms": "E HH:mm:ss", "dateFormatItem-yMEd": "E d. M. y", "dayPeriods-standAlone-narrow-midnight": "poln.", "field-quarter-narrow": "Q", "dayPeriods-standAlone-abbr-am": "AM", "field-day-relative+-1": "včera", "field-sun-short-relative+-1": "minulú ned.", "field-day-relative+-2": "predvčerom", "dayPeriods-format-narrow-night1": "v n.", "days-format-abbr": [ "ne", "po", "ut", "st", "št", "pi", "so" ], "field-sun-relative+0": "túto nedeľu", "field-sun-relative+1": "budúcu nedeľu", "dateFormatItem-yMMMd": "d. M. y", "dateFormatItem-Gy": "y G", "field-era": "letopočet", "field-week-narrow": "týž.", "field-day-short": "d.", "dayPeriods-standAlone-abbr-evening1": "večer", "field-fri-narrow-relative+0": "tento pi.", "dayPeriods-format-narrow-evening1": "več.", "field-fri-narrow-relative+1": "budúci pi.", "dayPeriods-standAlone-wide-am": "AM" } //end v1.x content );
; (function() { var app = angular.module('dashboardApp', [ 'ngRoute', 'dashboard' ]); var dashboard = angular.module('dashboard', []); dashboard.run(function($rootScope, invocationUtils, stringUtils, api, urls) { $rootScope.invocationUtils = invocationUtils; $rootScope.stringUtils = stringUtils; $rootScope._api = api; $rootScope._urls = urls; }); // this is a basis for some perf improvements // for things that only needs to bind, well, once. app.directive('bindOnce', function () { return { scope: true, link: function($scope, $element) { setTimeout(function () { $scope.$destroy(); $element.removeClass('ng-binding ng-scope'); }, 0); } }; }); dashboard.factory('$exceptionHandler', function() { return function(exception, cause) { exception.message += ' (caused by "' + cause + '")'; console.log(["CATCH", exception, cause]); throw exception; }; }); app.config(['$routeProvider', function ($routeProvider) { var defaultHomePage = '/jobs'; //or /functions if not in Azure Web Sites $routeProvider. when('/', { redirectTo: defaultHomePage }). when('/jobs', { templateUrl: 'app/views/JobsList.html', controller: 'JobsListController' }). when('/jobs/triggered/:jobName', { templateUrl: 'app/views/TriggeredJob.html', controller: 'TriggeredJobController' }). when('/jobs/continuous/:jobName', { templateUrl: 'app/views/ContinuousJob.html', controller: 'ContinuousJobController' }). when('/jobs/triggered/:jobName/runs/:runId', { templateUrl: 'app/views/TriggeredJobRun.html', controller: 'TriggeredJobRunController' }). when('/functions', { templateUrl: 'app/views/FunctionsHome.html', controller: 'FunctionsHomeController' }). when('/functions/definitions/:functionId', { templateUrl: 'app/views/Function.html', controller: 'FunctionController' }). when('/functions/invocations/:invocationId', { templateUrl: 'app/views/FunctionInvocation.html', controller: 'FunctionInvocationController' }). when('/about', { templateUrl: 'app/views/AboutHome.html', controller: 'AboutController' }). when('/diagnostics/indexerLogEntry/:entryId', { templateUrl: 'app/views/IndexerLogEntry.html', controller: 'IndexerLogEntryController' }). otherwise({ redirectTo: '/' }); }]); // simple paging support app.filter('startFrom', function() { return function(input, start) { start = +start; // ensure int return input.slice(start); }; }); app.run(function ($rootScope) { // Initialize errors / warnings $rootScope.errors = []; $rootScope.warnings = []; }); })();
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize exports="amd" -o ./compat/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../internals/baseIndexOf', './sortedIndex'], function(baseIndexOf, sortedIndex) { /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeMax = Math.max; /** * Gets the index at which the first occurrence of `value` is found using * strict equality for comparisons, i.e. `===`. If the array is already sorted * providing `true` for `fromIndex` will run a faster binary search. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=0] The index to search from or `true` * to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.indexOf([1, 2, 3, 1, 2, 3], 2); * // => 1 * * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 4 * * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { if (typeof fromIndex == 'number') { var length = array ? array.length : 0; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); } else if (fromIndex) { var index = sortedIndex(array, value); return array[index] === value ? index : -1; } return baseIndexOf(array, value, fromIndex); } return indexOf; });
version https://git-lfs.github.com/spec/v1 oid sha256:44bac44ffbed21920407278ce3bc7678e40959a50ea1544d0cb61289445b900e size 3181
/* * * 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. * */ module.exports = { id: 'windows', bootstrap:function() { var cordova = require('cordova'), exec = require('cordova/exec'), channel = cordova.require('cordova/channel'), modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy'); channel.onNativeReady.fire(); var onWinJSReady = function () { var app = WinJS.Application; var checkpointHandler = function checkpointHandler() { cordova.fireDocumentEvent('pause',null,true); }; var resumingHandler = function resumingHandler() { cordova.fireDocumentEvent('resume',null,true); }; app.addEventListener("checkpoint", checkpointHandler); Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", resumingHandler, false); app.start(); }; if (!window.WinJS) { var scriptElem = document.createElement("script"); if (navigator.appVersion.indexOf('MSAppHost/3.0') !== -1) { // Windows 10 UWP scriptElem.src = '/WinJS/js/base.js'; } else if (navigator.appVersion.indexOf("Windows Phone 8.1;") !== -1) { // windows phone 8.1 + Mobile IE 11 scriptElem.src = "//Microsoft.Phone.WinJS.2.1/js/base.js"; } else if (navigator.appVersion.indexOf("MSAppHost/2.0;") !== -1) { // windows 8.1 + IE 11 scriptElem.src = "//Microsoft.WinJS.2.0/js/base.js"; } scriptElem.addEventListener("load", onWinJSReady); document.head.appendChild(scriptElem); } else { onWinJSReady(); } } };
describe('zoom normal animation', function() { var prefixes = { '-webkit-transform': true, '-moz-transform': true, '-o-transform': true, 'transform': true }; var transform; beforeEach(module('ngAnimate')); beforeEach(module('ngAnimateMock')); beforeEach(module('fx.animations')); it("should zoom-normal in", function(done) { inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) { var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $rootScope.$digest(); $animate.enabled(true); $animate.enter(element, $rootElement); $rootScope.$digest(); $timeout.flush(); $window.setTimeout(function(){ angular.forEach(prefixes, function(bool, prefix){ if(element.css(prefix)){ transform = prefix; } }); expect(element.css('opacity')).to.be('1'); expect(element.css(transform)).to.be('matrix(1, 0, 0, 1, 0, 0)'); done(); },500); }); }); it('should zoom-normal out', function(done){ inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) { var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $rootScope.$digest(); $animate.enabled(true); $animate.leave(element); $rootScope.$digest(); $timeout.flush(); $window.setTimeout(function(){ expect(element.css('opacity')).to.be('0'); done(); },500); }); }); it('should zoom-normal move', function(done){ inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) { var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $rootScope.$digest(); $animate.enabled(true); $animate.move(element, $rootElement); $rootScope.$digest(); $timeout.flush(); $window.setTimeout(function(){ angular.forEach(prefixes, function(bool, prefix){ if(element.css(prefix)){ transform = prefix; } }); expect(element.css('opacity')).to.be('1'); expect(element.css(transform)).to.be('matrix(1, 0, 0, 1, 0, 0)'); done(); },500); }); }); xit('should zoom-normal removeClass', function(done){ inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) { var element = $compile('<div class="fx-zoom-normal ng-hide">zoom-normal</div>')($rootScope); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $rootScope.$digest(); $animate.enabled(true); $animate.removeClass(element, 'ng-hide'); $rootScope.$digest(); $window.setTimeout(function(){ angular.forEach(prefixes, function(bool, prefix){ if(element.css(prefix)){ transform = prefix; } }); expect(element.css('opacity')).to.be('1'); expect(element.css(transform)).to.be('matrix(1, 0, 0, 1, 0, 0)'); done(); },500); }); }); xit('should zoom-normal addClass', function(done){ inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) { var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $rootScope.$digest(); $animate.enabled(true); $animate.addClass(element, 'ng-hide'); $rootScope.$digest(); $window.setTimeout(function(){ expect(element.css('opacity')).to.be('0'); done(); },500); }); }); });
/** * Original shader from http://glsl.heroku.com/e#4122.10 * Tweaked, uniforms added and converted to Phaser/PIXI by Richard Davey */ Phaser.Filter.LightBeam = function (game) { Phaser.Filter.call(this, game); this.uniforms.alpha = { type: '1f', value: 1 }; this.uniforms.thickness = { type: '1f', value: 70.0 }; this.uniforms.speed = { type: '1f', value: 1.0 }; this.uniforms.red = { type: '1f', value: 2.0 }; this.uniforms.green = { type: '1f', value: 1.0 }; this.uniforms.blue = { type: '1f', value: 1.0 }; this.fragmentSrc = [ "precision mediump float;", "uniform vec2 resolution;", "uniform float time;", "uniform float alpha;", "uniform float thickness;", "uniform float speed;", "uniform float red;", "uniform float green;", "uniform float blue;", "void main(void) {", "vec2 uPos = (gl_FragCoord.xy / resolution.xy);", "uPos.y -= 0.50;", "float vertColor = 0.0;", "for (float i = 0.0; i < 1.0; i++)", "{", "float t = time * (i + speed);", "uPos.y += sin(uPos.x + t) * 0.2;", "float fTemp = abs(1.0 / uPos.y / thickness);", "vertColor += fTemp;", "}", "vec4 color = vec4(vertColor * red, vertColor * green, vertColor * blue, alpha);", "gl_FragColor = color;", "}" ]; }; Phaser.Filter.LightBeam.prototype = Object.create(Phaser.Filter.prototype); Phaser.Filter.LightBeam.prototype.constructor = Phaser.Filter.LightBeam; Phaser.Filter.LightBeam.prototype.init = function (width, height) { this.setResolution(width, height); }; Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'alpha', { get: function() { return this.uniforms.alpha.value; }, set: function(value) { this.uniforms.alpha.value = value; } }); Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'red', { get: function() { return this.uniforms.red.value; }, set: function(value) { this.uniforms.red.value = value; } }); Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'green', { get: function() { return this.uniforms.green.value; }, set: function(value) { this.uniforms.green.value = value; } }); Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'blue', { get: function() { return this.uniforms.blue.value; }, set: function(value) { this.uniforms.blue.value = value; } }); Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'thickness', { get: function() { return this.uniforms.thickness.value; }, set: function(value) { this.uniforms.thickness.value = value; } }); Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'speed', { get: function() { return this.uniforms.speed.value; }, set: function(value) { this.uniforms.speed.value = value; } });
/** @ngdoc directive @name umbraco.directives.directive:umbIcon @restrict E @scope @description Use this directive to show an render an umbraco backoffice svg icon. All svg icons used by this directive should use the following naming convention to keep things consistent: icon-[name of icon]. For example <pre>icon-alert.svg</pre> <h3>Markup example</h3> Simple icon <pre> <umb-icon icon="icon-alert"></umb-icon> </pre> Icon with additional attribute. It can be treated like any other dom element <pre> <umb-icon icon="icon-alert" class="another-class"></umb-icon> </pre> @example **/ (function () { "use strict"; function UmbIconDirective(iconHelper) { var directive = { replace: true, transclude: true, templateUrl: "views/components/umb-icon.html", scope: { icon: "@", svgString: "=?" }, link: function (scope, element) { if (scope.svgString === undefined && scope.svgString !== null && scope.icon !== undefined && scope.icon !== null) { const observer = new IntersectionObserver(_lazyRequestIcon, {rootMargin: "100px"}); const iconEl = element[0]; observer.observe(iconEl); // make sure to disconnect the observer when the scope is destroyed scope.$on('$destroy', function () { observer.disconnect(); }); } scope.$watch("icon", function (newValue, oldValue) { if (newValue && oldValue) { var newicon = newValue.split(" ")[0]; var oldicon = oldValue.split(" ")[0]; if (newicon !== oldicon) { _requestIcon(newicon); } } }); function _lazyRequestIcon(entries, observer) { entries.forEach(entry => { if (entry.isIntersecting === true) { observer.disconnect(); var icon = scope.icon.split(" ")[0]; // Ensure that only the first part of the icon is used as sometimes the color is added too, e.g. see umbeditorheader.directive scope.openIconPicker _requestIcon(icon); } }); } function _requestIcon(icon) { // Reset svg string before requesting new icon. scope.svgString = null; iconHelper.getIcon(icon) .then(data => { if (data && data.svgString) { // Watch source SVG string scope.svgString = data.svgString; } }); } } }; return directive; } angular.module("umbraco.directives").directive("umbIcon", UmbIconDirective); })();